gifted-baileys 1.5.0 → 1.5.5

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 (222) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +1429 -684
  3. package/package.json +11 -26
  4. package/src/Defaults/baileys-version.json +3 -0
  5. package/{lib → src}/Defaults/index.js +16 -8
  6. package/src/Defaults/index.ts +131 -0
  7. package/src/Defaults/phonenumber-mcc.json +223 -0
  8. package/src/Signal/libsignal.js +180 -0
  9. package/src/Signal/libsignal.ts +141 -0
  10. package/src/Socket/Client/abstract-socket-client.ts +19 -0
  11. package/src/Socket/Client/index.ts +3 -0
  12. package/src/Socket/Client/mobile-socket-client.js +78 -0
  13. package/src/Socket/Client/mobile-socket-client.ts +66 -0
  14. package/src/Socket/Client/web-socket-client.js +75 -0
  15. package/src/Socket/Client/web-socket-client.ts +57 -0
  16. package/{lib → src}/Socket/business.js +33 -27
  17. package/src/Socket/business.ts +281 -0
  18. package/{lib → src}/Socket/chats.js +197 -178
  19. package/src/Socket/chats.ts +1030 -0
  20. package/{lib → src}/Socket/groups.js +69 -79
  21. package/src/Socket/groups.ts +356 -0
  22. package/{lib → src}/Socket/index.js +1 -4
  23. package/src/Socket/index.ts +13 -0
  24. package/{lib → src}/Socket/messages-recv.js +160 -108
  25. package/src/Socket/messages-recv.ts +985 -0
  26. package/{lib → src}/Socket/messages-send.js +183 -100
  27. package/src/Socket/messages-send.ts +871 -0
  28. package/src/Socket/newsletter.js +227 -0
  29. package/src/Socket/newsletter.ts +282 -0
  30. package/{lib → src}/Socket/registration.js +55 -63
  31. package/src/Socket/registration.ts +250 -0
  32. package/{lib → src}/Socket/socket.js +107 -66
  33. package/src/Socket/socket.ts +777 -0
  34. package/src/Store/index.ts +3 -0
  35. package/{lib → src}/Store/make-cache-manager-store.js +34 -25
  36. package/src/Store/make-cache-manager-store.ts +100 -0
  37. package/{lib → src}/Store/make-in-memory-store.js +51 -61
  38. package/src/Store/make-in-memory-store.ts +475 -0
  39. package/src/Store/make-ordered-dictionary.ts +86 -0
  40. package/{lib → src}/Store/object-repository.js +1 -1
  41. package/src/Store/object-repository.ts +32 -0
  42. package/src/Tests/test.app-state-sync.js +204 -0
  43. package/src/Tests/test.app-state-sync.ts +207 -0
  44. package/src/Tests/test.event-buffer.js +270 -0
  45. package/src/Tests/test.event-buffer.ts +319 -0
  46. package/src/Tests/test.key-store.js +76 -0
  47. package/src/Tests/test.key-store.ts +92 -0
  48. package/src/Tests/test.libsignal.js +141 -0
  49. package/src/Tests/test.libsignal.ts +186 -0
  50. package/src/Tests/test.media-download.js +93 -0
  51. package/src/Tests/test.media-download.ts +76 -0
  52. package/src/Tests/test.messages.js +33 -0
  53. package/src/Tests/test.messages.ts +37 -0
  54. package/src/Tests/utils.js +34 -0
  55. package/src/Tests/utils.ts +36 -0
  56. package/src/Types/Auth.ts +113 -0
  57. package/src/Types/Call.ts +15 -0
  58. package/src/Types/Chat.ts +106 -0
  59. package/{lib/Types/Contact.d.ts → src/Types/Contact.ts} +9 -8
  60. package/src/Types/Events.ts +93 -0
  61. package/src/Types/GroupMetadata.ts +53 -0
  62. package/{lib → src}/Types/Label.js +1 -1
  63. package/src/Types/Label.ts +36 -0
  64. package/{lib → src}/Types/LabelAssociation.js +1 -1
  65. package/{lib/Types/LabelAssociation.d.ts → src/Types/LabelAssociation.ts} +22 -16
  66. package/src/Types/Message.ts +288 -0
  67. package/src/Types/Newsletter.js +32 -0
  68. package/src/Types/Newsletter.ts +98 -0
  69. package/src/Types/Product.ts +85 -0
  70. package/src/Types/Signal.ts +68 -0
  71. package/{lib/Types/Socket.d.ts → src/Types/Socket.ts} +68 -56
  72. package/src/Types/State.ts +29 -0
  73. package/{lib → src}/Types/index.js +2 -1
  74. package/src/Types/index.ts +59 -0
  75. package/{lib → src}/Utils/auth-utils.js +95 -76
  76. package/src/Utils/auth-utils.ts +222 -0
  77. package/src/Utils/baileys-event-stream.js +92 -0
  78. package/src/Utils/baileys-event-stream.ts +66 -0
  79. package/{lib → src}/Utils/business.js +45 -17
  80. package/src/Utils/business.ts +275 -0
  81. package/{lib → src}/Utils/chat-utils.js +74 -46
  82. package/src/Utils/chat-utils.ts +860 -0
  83. package/{lib → src}/Utils/crypto.js +31 -21
  84. package/src/Utils/crypto.ts +131 -0
  85. package/src/Utils/decode-wa-message.js +211 -0
  86. package/src/Utils/decode-wa-message.ts +228 -0
  87. package/{lib → src}/Utils/event-buffer.js +13 -4
  88. package/src/Utils/event-buffer.ts +613 -0
  89. package/{lib → src}/Utils/generics.js +98 -45
  90. package/src/Utils/generics.ts +434 -0
  91. package/{lib → src}/Utils/history.js +39 -10
  92. package/src/Utils/history.ts +112 -0
  93. package/src/Utils/index.ts +17 -0
  94. package/{lib → src}/Utils/link-preview.js +54 -17
  95. package/src/Utils/link-preview.ts +122 -0
  96. package/src/Utils/logger.ts +3 -0
  97. package/src/Utils/lt-hash.ts +61 -0
  98. package/{lib → src}/Utils/make-mutex.js +13 -4
  99. package/src/Utils/make-mutex.ts +44 -0
  100. package/{lib → src}/Utils/messages-media.js +296 -192
  101. package/src/Utils/messages-media.ts +847 -0
  102. package/{lib → src}/Utils/messages.js +124 -113
  103. package/src/Utils/messages.ts +956 -0
  104. package/{lib → src}/Utils/noise-handler.js +16 -3
  105. package/src/Utils/noise-handler.ts +197 -0
  106. package/{lib → src}/Utils/process-message.js +33 -29
  107. package/src/Utils/process-message.ts +414 -0
  108. package/{lib → src}/Utils/signal.js +23 -14
  109. package/src/Utils/signal.ts +177 -0
  110. package/{lib → src}/Utils/use-multi-file-auth-state.js +28 -19
  111. package/src/Utils/use-multi-file-auth-state.ts +90 -0
  112. package/{lib → src}/Utils/validate-connection.js +25 -42
  113. package/src/Utils/validate-connection.ts +238 -0
  114. package/src/WABinary/constants.ts +42 -0
  115. package/{lib → src}/WABinary/decode.js +17 -7
  116. package/src/WABinary/decode.ts +265 -0
  117. package/{lib → src}/WABinary/encode.js +17 -7
  118. package/src/WABinary/encode.ts +236 -0
  119. package/{lib → src}/WABinary/generic-utils.js +2 -2
  120. package/src/WABinary/generic-utils.ts +121 -0
  121. package/src/WABinary/index.ts +5 -0
  122. package/{lib → src}/WABinary/jid-utils.js +4 -1
  123. package/src/WABinary/jid-utils.ts +68 -0
  124. package/src/WABinary/types.ts +17 -0
  125. package/src/WAM/BinaryInfo.js +13 -0
  126. package/src/WAM/BinaryInfo.ts +12 -0
  127. package/src/WAM/constants.js +15350 -0
  128. package/src/WAM/constants.ts +15382 -0
  129. package/src/WAM/encode.js +155 -0
  130. package/src/WAM/encode.ts +174 -0
  131. package/src/WAM/index.js +19 -0
  132. package/src/WAM/index.ts +3 -0
  133. package/src/gifted +1 -0
  134. package/{lib → src}/index.js +1 -0
  135. package/src/index.ts +13 -0
  136. package/lib/Defaults/baileys-version.json +0 -3
  137. package/lib/Defaults/index.d.ts +0 -284
  138. package/lib/Defaults/phonenumber-mcc.json +0 -223
  139. package/lib/Signal/libsignal.d.ts +0 -3
  140. package/lib/Signal/libsignal.js +0 -152
  141. package/lib/Socket/Client/abstract-socket-client.d.ts +0 -17
  142. package/lib/Socket/Client/index.d.ts +0 -3
  143. package/lib/Socket/Client/mobile-socket-client.d.ts +0 -13
  144. package/lib/Socket/Client/mobile-socket-client.js +0 -65
  145. package/lib/Socket/Client/web-socket-client.d.ts +0 -12
  146. package/lib/Socket/Client/web-socket-client.js +0 -62
  147. package/lib/Socket/business.d.ts +0 -135
  148. package/lib/Socket/chats.d.ts +0 -79
  149. package/lib/Socket/groups.d.ts +0 -113
  150. package/lib/Socket/index.d.ts +0 -137
  151. package/lib/Socket/messages-recv.d.ts +0 -124
  152. package/lib/Socket/messages-send.d.ts +0 -119
  153. package/lib/Socket/registration.d.ts +0 -232
  154. package/lib/Socket/socket.d.ts +0 -42
  155. package/lib/Store/index.d.ts +0 -3
  156. package/lib/Store/make-cache-manager-store.d.ts +0 -13
  157. package/lib/Store/make-in-memory-store.d.ts +0 -117
  158. package/lib/Store/make-ordered-dictionary.d.ts +0 -13
  159. package/lib/Store/object-repository.d.ts +0 -10
  160. package/lib/Types/Auth.d.ts +0 -108
  161. package/lib/Types/Call.d.ts +0 -13
  162. package/lib/Types/Chat.d.ts +0 -102
  163. package/lib/Types/Events.d.ts +0 -157
  164. package/lib/Types/GroupMetadata.d.ts +0 -52
  165. package/lib/Types/Label.d.ts +0 -35
  166. package/lib/Types/Message.d.ts +0 -261
  167. package/lib/Types/Product.d.ts +0 -78
  168. package/lib/Types/Signal.d.ts +0 -57
  169. package/lib/Types/State.d.ts +0 -27
  170. package/lib/Types/index.d.ts +0 -56
  171. package/lib/Utils/auth-utils.d.ts +0 -18
  172. package/lib/Utils/baileys-event-stream.d.ts +0 -16
  173. package/lib/Utils/baileys-event-stream.js +0 -63
  174. package/lib/Utils/business.d.ts +0 -22
  175. package/lib/Utils/chat-utils.d.ts +0 -71
  176. package/lib/Utils/crypto.d.ts +0 -41
  177. package/lib/Utils/decode-wa-message.d.ts +0 -19
  178. package/lib/Utils/decode-wa-message.js +0 -174
  179. package/lib/Utils/event-buffer.d.ts +0 -35
  180. package/lib/Utils/generics.d.ts +0 -94
  181. package/lib/Utils/history.d.ts +0 -15
  182. package/lib/Utils/index.d.ts +0 -17
  183. package/lib/Utils/link-preview.d.ts +0 -21
  184. package/lib/Utils/logger.d.ts +0 -4
  185. package/lib/Utils/lt-hash.d.ts +0 -12
  186. package/lib/Utils/make-mutex.d.ts +0 -7
  187. package/lib/Utils/messages-media.d.ts +0 -107
  188. package/lib/Utils/messages.d.ts +0 -76
  189. package/lib/Utils/noise-handler.d.ts +0 -20
  190. package/lib/Utils/process-message.d.ts +0 -41
  191. package/lib/Utils/signal.d.ts +0 -32
  192. package/lib/Utils/use-multi-file-auth-state.d.ts +0 -12
  193. package/lib/Utils/validate-connection.d.ts +0 -11
  194. package/lib/WABinary/constants.d.ts +0 -27
  195. package/lib/WABinary/decode.d.ts +0 -7
  196. package/lib/WABinary/encode.d.ts +0 -3
  197. package/lib/WABinary/generic-utils.d.ts +0 -15
  198. package/lib/WABinary/index.d.ts +0 -5
  199. package/lib/WABinary/jid-utils.d.ts +0 -29
  200. package/lib/WABinary/types.d.ts +0 -18
  201. package/lib/index.d.ts +0 -10
  202. /package/{lib → src}/Socket/Client/abstract-socket-client.js +0 -0
  203. /package/{lib → src}/Socket/Client/index.js +0 -0
  204. /package/{lib → src}/Store/index.js +0 -0
  205. /package/{lib → src}/Store/make-ordered-dictionary.js +0 -0
  206. /package/{lib → src}/Types/Auth.js +0 -0
  207. /package/{lib → src}/Types/Call.js +0 -0
  208. /package/{lib → src}/Types/Chat.js +0 -0
  209. /package/{lib → src}/Types/Contact.js +0 -0
  210. /package/{lib → src}/Types/Events.js +0 -0
  211. /package/{lib → src}/Types/GroupMetadata.js +0 -0
  212. /package/{lib → src}/Types/Message.js +0 -0
  213. /package/{lib → src}/Types/Product.js +0 -0
  214. /package/{lib → src}/Types/Signal.js +0 -0
  215. /package/{lib → src}/Types/Socket.js +0 -0
  216. /package/{lib → src}/Types/State.js +0 -0
  217. /package/{lib → src}/Utils/index.js +0 -0
  218. /package/{lib → src}/Utils/logger.js +0 -0
  219. /package/{lib → src}/Utils/lt-hash.js +0 -0
  220. /package/{lib → src}/WABinary/constants.js +0 -0
  221. /package/{lib → src}/WABinary/index.js +0 -0
  222. /package/{lib → src}/WABinary/types.js +0 -0
@@ -1,4 +1,20 @@
1
1
  "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __asyncValues = (this && this.__asyncValues) || function (o) {
12
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
13
+ var m = o[Symbol.asyncIterator], i;
14
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
15
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
16
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
17
+ };
2
18
  Object.defineProperty(exports, "__esModule", { value: true });
3
19
  exports.getHistoryMsg = exports.downloadAndProcessHistorySyncNotification = exports.processHistoryMessage = exports.downloadHistory = void 0;
4
20
  const util_1 = require("util");
@@ -10,18 +26,31 @@ const generics_1 = require("./generics");
10
26
  const messages_1 = require("./messages");
11
27
  const messages_media_1 = require("./messages-media");
12
28
  const inflatePromise = (0, util_1.promisify)(zlib_1.inflate);
13
- const downloadHistory = async (msg, options) => {
14
- const stream = await (0, messages_media_1.downloadContentFromMessage)(msg, 'md-msg-hist', { options });
29
+ const downloadHistory = (msg, options) => __awaiter(void 0, void 0, void 0, function* () {
30
+ var _a, e_1, _b, _c;
31
+ const stream = yield (0, messages_media_1.downloadContentFromMessage)(msg, 'md-msg-hist', { options });
15
32
  const bufferArray = [];
16
- for await (const chunk of stream) {
17
- bufferArray.push(chunk);
33
+ try {
34
+ for (var _d = true, stream_1 = __asyncValues(stream), stream_1_1; stream_1_1 = yield stream_1.next(), _a = stream_1_1.done, !_a; _d = true) {
35
+ _c = stream_1_1.value;
36
+ _d = false;
37
+ const chunk = _c;
38
+ bufferArray.push(chunk);
39
+ }
40
+ }
41
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
42
+ finally {
43
+ try {
44
+ if (!_d && !_a && (_b = stream_1.return)) yield _b.call(stream_1);
45
+ }
46
+ finally { if (e_1) throw e_1.error; }
18
47
  }
19
48
  let buffer = Buffer.concat(bufferArray);
20
49
  // decompress buffer
21
- buffer = await inflatePromise(buffer);
50
+ buffer = yield inflatePromise(buffer);
22
51
  const syncData = WAProto_1.proto.HistorySync.decode(buffer);
23
52
  return syncData;
24
- };
53
+ });
25
54
  exports.downloadHistory = downloadHistory;
26
55
  const processHistoryMessage = (item) => {
27
56
  var _a, _b, _c;
@@ -61,7 +90,7 @@ const processHistoryMessage = (item) => {
61
90
  if ((0, WABinary_1.isJidUser)(chat.id) && chat.readOnly && chat.archived) {
62
91
  delete chat.readOnly;
63
92
  }
64
- chats.push({ ...chat });
93
+ chats.push(Object.assign({}, chat));
65
94
  }
66
95
  break;
67
96
  case WAProto_1.proto.HistorySync.HistorySyncType.PUSH_NAME:
@@ -77,10 +106,10 @@ const processHistoryMessage = (item) => {
77
106
  };
78
107
  };
79
108
  exports.processHistoryMessage = processHistoryMessage;
80
- const downloadAndProcessHistorySyncNotification = async (msg, options) => {
81
- const historyMsg = await (0, exports.downloadHistory)(msg, options);
109
+ const downloadAndProcessHistorySyncNotification = (msg, options) => __awaiter(void 0, void 0, void 0, function* () {
110
+ const historyMsg = yield (0, exports.downloadHistory)(msg, options);
82
111
  return (0, exports.processHistoryMessage)(historyMsg);
83
- };
112
+ });
84
113
  exports.downloadAndProcessHistorySyncNotification = downloadAndProcessHistorySyncNotification;
85
114
  const getHistoryMsg = (message) => {
86
115
  var _a;
@@ -0,0 +1,112 @@
1
+ import { AxiosRequestConfig } from 'axios'
2
+ import { promisify } from 'util'
3
+ import { inflate } from 'zlib'
4
+ import { proto } from '../../WAProto'
5
+ import { Chat, Contact, WAMessageStubType } from '../Types'
6
+ import { isJidUser } from '../WABinary'
7
+ import { toNumber } from './generics'
8
+ import { normalizeMessageContent } from './messages'
9
+ import { downloadContentFromMessage } from './messages-media'
10
+
11
+ const inflatePromise = promisify(inflate)
12
+
13
+ export const downloadHistory = async(
14
+ msg: proto.Message.IHistorySyncNotification,
15
+ options: AxiosRequestConfig<any>
16
+ ) => {
17
+ const stream = await downloadContentFromMessage(msg, 'md-msg-hist', { options })
18
+ const bufferArray: Buffer[] = []
19
+ for await (const chunk of stream) {
20
+ bufferArray.push(chunk)
21
+ }
22
+
23
+ let buffer = Buffer.concat(bufferArray)
24
+
25
+ // decompress buffer
26
+ buffer = await inflatePromise(buffer)
27
+
28
+ const syncData = proto.HistorySync.decode(buffer)
29
+ return syncData
30
+ }
31
+
32
+ export const processHistoryMessage = (item: proto.IHistorySync) => {
33
+ const messages: proto.IWebMessageInfo[] = []
34
+ const contacts: Contact[] = []
35
+ const chats: Chat[] = []
36
+
37
+ switch (item.syncType) {
38
+ case proto.HistorySync.HistorySyncType.INITIAL_BOOTSTRAP:
39
+ case proto.HistorySync.HistorySyncType.RECENT:
40
+ case proto.HistorySync.HistorySyncType.FULL:
41
+ for(const chat of item.conversations! as Chat[]) {
42
+ contacts.push({ id: chat.id, name: chat.name || undefined })
43
+
44
+ const msgs = chat.messages || []
45
+ delete chat.messages
46
+ delete chat.archived
47
+ delete chat.muteEndTime
48
+ delete chat.pinned
49
+
50
+ for(const item of msgs) {
51
+ const message = item.message!
52
+ messages.push(message)
53
+
54
+ if(!chat.messages?.length) {
55
+ // keep only the most recent message in the chat array
56
+ chat.messages = [{ message }]
57
+ }
58
+
59
+ if(!message.key.fromMe && !chat.lastMessageRecvTimestamp) {
60
+ chat.lastMessageRecvTimestamp = toNumber(message.messageTimestamp)
61
+ }
62
+
63
+ if(
64
+ (message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_BSP
65
+ || message.messageStubType === WAMessageStubType.BIZ_PRIVACY_MODE_TO_FB
66
+ )
67
+ && message.messageStubParameters?.[0]
68
+ ) {
69
+ contacts.push({
70
+ id: message.key.participant || message.key.remoteJid!,
71
+ verifiedName: message.messageStubParameters?.[0],
72
+ })
73
+ }
74
+ }
75
+
76
+ if(isJidUser(chat.id) && chat.readOnly && chat.archived) {
77
+ delete chat.readOnly
78
+ }
79
+
80
+ chats.push({ ...chat })
81
+ }
82
+
83
+ break
84
+ case proto.HistorySync.HistorySyncType.PUSH_NAME:
85
+ for(const c of item.pushnames!) {
86
+ contacts.push({ id: c.id!, notify: c.pushname! })
87
+ }
88
+
89
+ break
90
+ }
91
+
92
+ return {
93
+ chats,
94
+ contacts,
95
+ messages,
96
+ }
97
+ }
98
+
99
+ export const downloadAndProcessHistorySyncNotification = async(
100
+ msg: proto.Message.IHistorySyncNotification,
101
+ options: AxiosRequestConfig<any>
102
+ ) => {
103
+ const historyMsg = await downloadHistory(msg, options)
104
+ return processHistoryMessage(historyMsg)
105
+ }
106
+
107
+ export const getHistoryMsg = (message: proto.IMessage) => {
108
+ const normalizedContent = !!message ? normalizeMessageContent(message) : undefined
109
+ const anyHistoryMsg = normalizedContent?.protocolMessage?.historySyncNotification
110
+
111
+ return anyHistoryMsg
112
+ }
@@ -0,0 +1,17 @@
1
+ export * from './generics'
2
+ export * from './decode-wa-message'
3
+ export * from './messages'
4
+ export * from './messages-media'
5
+ export * from './validate-connection'
6
+ export * from './crypto'
7
+ export * from './signal'
8
+ export * from './noise-handler'
9
+ export * from './history'
10
+ export * from './chat-utils'
11
+ export * from './lt-hash'
12
+ export * from './auth-utils'
13
+ export * from './baileys-event-stream'
14
+ export * from './use-multi-file-auth-state'
15
+ export * from './link-preview'
16
+ export * from './event-buffer'
17
+ export * from './process-message'
@@ -1,39 +1,78 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
36
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
37
+ return new (P || (P = Promise))(function (resolve, reject) {
38
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
39
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
40
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
41
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
42
+ });
43
+ };
2
44
  Object.defineProperty(exports, "__esModule", { value: true });
3
45
  exports.getUrlInfo = void 0;
4
46
  const messages_1 = require("./messages");
5
47
  const messages_media_1 = require("./messages-media");
6
48
  const THUMBNAIL_WIDTH_PX = 192;
7
49
  /** Fetches an image and generates a thumbnail for it */
8
- const getCompressedJpegThumbnail = async (url, { thumbnailWidth, fetchOpts }) => {
9
- const stream = await (0, messages_media_1.getHttpStream)(url, fetchOpts);
10
- const result = await (0, messages_media_1.extractImageThumb)(stream, thumbnailWidth);
50
+ const getCompressedJpegThumbnail = (url_1, _a) => __awaiter(void 0, [url_1, _a], void 0, function* (url, { thumbnailWidth, fetchOpts }) {
51
+ const stream = yield (0, messages_media_1.getHttpStream)(url, fetchOpts);
52
+ const result = yield (0, messages_media_1.extractImageThumb)(stream, thumbnailWidth);
11
53
  return result;
12
- };
54
+ });
13
55
  /**
14
56
  * Given a piece of text, checks for any URL present, generates link preview for the same and returns it
15
57
  * Return undefined if the fetch failed or no URL was found
16
58
  * @param text first matched URL in text
17
59
  * @returns the URL info required to generate link preview
18
60
  */
19
- const getUrlInfo = async (text, opts = {
61
+ const getUrlInfo = (text_1, ...args_1) => __awaiter(void 0, [text_1, ...args_1], void 0, function* (text, opts = {
20
62
  thumbnailWidth: THUMBNAIL_WIDTH_PX,
21
63
  fetchOpts: { timeout: 3000 }
22
- }) => {
64
+ }) {
23
65
  var _a;
24
66
  try {
25
67
  // retries
26
68
  const retries = 0;
27
69
  const maxRetry = 5;
28
- const { getLinkPreview } = await import('link-preview-js');
70
+ const { getLinkPreview } = yield Promise.resolve().then(() => __importStar(require('link-preview-js')));
29
71
  let previewLink = text;
30
72
  if (!text.startsWith('https://') && !text.startsWith('http://')) {
31
73
  previewLink = 'https://' + previewLink;
32
74
  }
33
- const info = await getLinkPreview(previewLink, {
34
- ...opts.fetchOpts,
35
- followRedirects: 'manual',
36
- handleRedirects: (baseURL, forwardedURL) => {
75
+ const info = yield getLinkPreview(previewLink, Object.assign(Object.assign({}, opts.fetchOpts), { followRedirects: 'follow', handleRedirects: (baseURL, forwardedURL) => {
37
76
  const urlObj = new URL(baseURL);
38
77
  const forwardedURLObj = new URL(forwardedURL);
39
78
  if (retries >= maxRetry) {
@@ -48,9 +87,7 @@ const getUrlInfo = async (text, opts = {
48
87
  else {
49
88
  return false;
50
89
  }
51
- },
52
- headers: opts.fetchOpts
53
- });
90
+ }, headers: opts.fetchOpts }));
54
91
  if (info && 'title' in info && info.title) {
55
92
  const [image] = info.images;
56
93
  const urlInfo = {
@@ -61,7 +98,7 @@ const getUrlInfo = async (text, opts = {
61
98
  originalThumbnailUrl: image
62
99
  };
63
100
  if (opts.uploadImage) {
64
- const { imageMessage } = await (0, messages_1.prepareWAMessageMedia)({ image: { url: image } }, {
101
+ const { imageMessage } = yield (0, messages_1.prepareWAMessageMedia)({ image: { url: image } }, {
65
102
  upload: opts.uploadImage,
66
103
  mediaTypeOverride: 'thumbnail-link',
67
104
  options: opts.fetchOpts
@@ -74,7 +111,7 @@ const getUrlInfo = async (text, opts = {
74
111
  else {
75
112
  try {
76
113
  urlInfo.jpegThumbnail = image
77
- ? (await getCompressedJpegThumbnail(image, opts)).buffer
114
+ ? (yield getCompressedJpegThumbnail(image, opts)).buffer
78
115
  : undefined;
79
116
  }
80
117
  catch (error) {
@@ -89,5 +126,5 @@ const getUrlInfo = async (text, opts = {
89
126
  throw error;
90
127
  }
91
128
  }
92
- };
129
+ });
93
130
  exports.getUrlInfo = getUrlInfo;
@@ -0,0 +1,122 @@
1
+ import { AxiosRequestConfig } from 'axios'
2
+ import { Logger } from 'pino'
3
+ import { WAMediaUploadFunction, WAUrlInfo } from '../Types'
4
+ import { prepareWAMessageMedia } from './messages'
5
+ import { extractImageThumb, getHttpStream } from './messages-media'
6
+
7
+ const THUMBNAIL_WIDTH_PX = 192
8
+
9
+ /** Fetches an image and generates a thumbnail for it */
10
+ const getCompressedJpegThumbnail = async(
11
+ url: string,
12
+ { thumbnailWidth, fetchOpts }: URLGenerationOptions
13
+ ) => {
14
+ const stream = await getHttpStream(url, fetchOpts)
15
+ const result = await extractImageThumb(stream, thumbnailWidth)
16
+ return result
17
+ }
18
+
19
+ export type URLGenerationOptions = {
20
+ thumbnailWidth: number
21
+ fetchOpts: {
22
+ /** Timeout in ms */
23
+ timeout: number
24
+ proxyUrl?: string
25
+ headers?: AxiosRequestConfig<{}>['headers']
26
+ }
27
+ uploadImage?: WAMediaUploadFunction
28
+ logger?: Logger
29
+ }
30
+
31
+ /**
32
+ * Given a piece of text, checks for any URL present, generates link preview for the same and returns it
33
+ * Return undefined if the fetch failed or no URL was found
34
+ * @param text first matched URL in text
35
+ * @returns the URL info required to generate link preview
36
+ */
37
+ export const getUrlInfo = async(
38
+ text: string,
39
+ opts: URLGenerationOptions = {
40
+ thumbnailWidth: THUMBNAIL_WIDTH_PX,
41
+ fetchOpts: { timeout: 3000 }
42
+ },
43
+ ): Promise<WAUrlInfo | undefined> => {
44
+ try {
45
+ // retries
46
+ const retries = 0
47
+ const maxRetry = 5
48
+
49
+ const { getLinkPreview } = await import('link-preview-js')
50
+ let previewLink = text
51
+ if(!text.startsWith('https://') && !text.startsWith('http://')) {
52
+ previewLink = 'https://' + previewLink
53
+ }
54
+
55
+ const info = await getLinkPreview(previewLink, {
56
+ ...opts.fetchOpts,
57
+ followRedirects: 'follow',
58
+ handleRedirects: (baseURL: string, forwardedURL: string) => {
59
+ const urlObj = new URL(baseURL)
60
+ const forwardedURLObj = new URL(forwardedURL)
61
+ if(retries >= maxRetry) {
62
+ return false
63
+ }
64
+
65
+ if(
66
+ forwardedURLObj.hostname === urlObj.hostname
67
+ || forwardedURLObj.hostname === 'www.' + urlObj.hostname
68
+ || 'www.' + forwardedURLObj.hostname === urlObj.hostname
69
+ ) {
70
+ retries + 1
71
+ return true
72
+ } else {
73
+ return false
74
+ }
75
+ },
76
+ headers: opts.fetchOpts as {}
77
+ })
78
+ if(info && 'title' in info && info.title) {
79
+ const [image] = info.images
80
+
81
+ const urlInfo: WAUrlInfo = {
82
+ 'canonical-url': info.url,
83
+ 'matched-text': text,
84
+ title: info.title,
85
+ description: info.description,
86
+ originalThumbnailUrl: image
87
+ }
88
+
89
+ if(opts.uploadImage) {
90
+ const { imageMessage } = await prepareWAMessageMedia(
91
+ { image: { url: image } },
92
+ {
93
+ upload: opts.uploadImage,
94
+ mediaTypeOverride: 'thumbnail-link',
95
+ options: opts.fetchOpts
96
+ }
97
+ )
98
+ urlInfo.jpegThumbnail = imageMessage?.jpegThumbnail
99
+ ? Buffer.from(imageMessage.jpegThumbnail)
100
+ : undefined
101
+ urlInfo.highQualityThumbnail = imageMessage || undefined
102
+ } else {
103
+ try {
104
+ urlInfo.jpegThumbnail = image
105
+ ? (await getCompressedJpegThumbnail(image, opts)).buffer
106
+ : undefined
107
+ } catch(error) {
108
+ opts.logger?.debug(
109
+ { err: error.stack, url: previewLink },
110
+ 'error in generating thumbnail'
111
+ )
112
+ }
113
+ }
114
+
115
+ return urlInfo
116
+ }
117
+ } catch(error) {
118
+ if(!error.message.includes('receive a valid')) {
119
+ throw error
120
+ }
121
+ }
122
+ }
@@ -0,0 +1,3 @@
1
+ import P from 'pino'
2
+
3
+ export default P({ timestamp: () => `,"time":"${new Date().toJSON()}"` })
@@ -0,0 +1,61 @@
1
+ import { hkdf } from './crypto'
2
+
3
+ /**
4
+ * LT Hash is a summation based hash algorithm that maintains the integrity of a piece of data
5
+ * over a series of mutations. You can add/remove mutations and it'll return a hash equal to
6
+ * if the same series of mutations was made sequentially.
7
+ */
8
+
9
+ const o = 128
10
+
11
+ class d {
12
+
13
+ salt: string
14
+
15
+ constructor(e: string) {
16
+ this.salt = e
17
+ }
18
+ add(e, t) {
19
+ var r = this
20
+ for(const item of t) {
21
+ e = r._addSingle(e, item)
22
+ }
23
+
24
+ return e
25
+ }
26
+ subtract(e, t) {
27
+ var r = this
28
+ for(const item of t) {
29
+ e = r._subtractSingle(e, item)
30
+ }
31
+
32
+ return e
33
+ }
34
+ subtractThenAdd(e, t, r) {
35
+ var n = this
36
+ return n.add(n.subtract(e, r), t)
37
+ }
38
+ _addSingle(e, t) {
39
+ var r = this
40
+ const n = new Uint8Array(hkdf(Buffer.from(t), o, { info: r.salt })).buffer
41
+ return r.performPointwiseWithOverflow(e, n, ((e, t) => e + t))
42
+ }
43
+ _subtractSingle(e, t) {
44
+ var r = this
45
+
46
+ const n = new Uint8Array(hkdf(Buffer.from(t), o, { info: r.salt })).buffer
47
+ return r.performPointwiseWithOverflow(e, n, ((e, t) => e - t))
48
+ }
49
+ performPointwiseWithOverflow(e, t, r) {
50
+ const n = new DataView(e)
51
+ , i = new DataView(t)
52
+ , a = new ArrayBuffer(n.byteLength)
53
+ , s = new DataView(a)
54
+ for(let e = 0; e < n.byteLength; e += 2) {
55
+ s.setUint16(e, r(n.getUint16(e, !0), i.getUint16(e, !0)), !0)
56
+ }
57
+
58
+ return a
59
+ }
60
+ }
61
+ export const LT_HASH_ANTI_TAMPERING = new d('WhatsApp Patch Integrity')
@@ -1,4 +1,13 @@
1
1
  "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
2
11
  Object.defineProperty(exports, "__esModule", { value: true });
3
12
  exports.makeKeyedMutex = exports.makeMutex = void 0;
4
13
  const makeMutex = () => {
@@ -6,22 +15,22 @@ const makeMutex = () => {
6
15
  let taskTimeout;
7
16
  return {
8
17
  mutex(code) {
9
- task = (async () => {
18
+ task = (() => __awaiter(this, void 0, void 0, function* () {
10
19
  // wait for the previous task to complete
11
20
  // if there is an error, we swallow so as to not block the queue
12
21
  try {
13
- await task;
22
+ yield task;
14
23
  }
15
24
  catch (_a) { }
16
25
  try {
17
26
  // execute the current task
18
- const result = await code();
27
+ const result = yield code();
19
28
  return result;
20
29
  }
21
30
  finally {
22
31
  clearTimeout(taskTimeout);
23
32
  }
24
- })();
33
+ }))();
25
34
  // we replace the existing task, appending the new piece of execution to it
26
35
  // so the next task will have to wait for this one to finish
27
36
  return task;
@@ -0,0 +1,44 @@
1
+ export const makeMutex = () => {
2
+ let task = Promise.resolve() as Promise<any>
3
+
4
+ let taskTimeout: NodeJS.Timeout | undefined
5
+
6
+ return {
7
+ mutex<T>(code: () => Promise<T> | T): Promise<T> {
8
+ task = (async() => {
9
+ // wait for the previous task to complete
10
+ // if there is an error, we swallow so as to not block the queue
11
+ try {
12
+ await task
13
+ } catch{ }
14
+
15
+ try {
16
+ // execute the current task
17
+ const result = await code()
18
+ return result
19
+ } finally {
20
+ clearTimeout(taskTimeout)
21
+ }
22
+ })()
23
+ // we replace the existing task, appending the new piece of execution to it
24
+ // so the next task will have to wait for this one to finish
25
+ return task
26
+ },
27
+ }
28
+ }
29
+
30
+ export type Mutex = ReturnType<typeof makeMutex>
31
+
32
+ export const makeKeyedMutex = () => {
33
+ const map: { [id: string]: Mutex } = {}
34
+
35
+ return {
36
+ mutex<T>(key: string, task: () => Promise<T> | T): Promise<T> {
37
+ if(!map[key]) {
38
+ map[key] = makeMutex()
39
+ }
40
+
41
+ return map[key].mutex(task)
42
+ }
43
+ }
44
+ }