sroosh 1.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 (250) hide show
  1. package/CryptoFile-BROWSER.d.ts +2 -0
  2. package/CryptoFile-BROWSER.js +23 -0
  3. package/CryptoFile.d.ts +2 -0
  4. package/CryptoFile.js +23 -0
  5. package/Helpers.d.ts +151 -0
  6. package/Helpers.js +480 -0
  7. package/Password.d.ts +15 -0
  8. package/Password.js +271 -0
  9. package/README.md +105 -0
  10. package/Utils.d.ts +228 -0
  11. package/Utils.js +1248 -0
  12. package/Version.d.ts +1 -0
  13. package/Version.js +4 -0
  14. package/client/2fa.d.ts +48 -0
  15. package/client/2fa.js +109 -0
  16. package/client/TelegramClient.d.ts +1042 -0
  17. package/client/TelegramClient.js +1244 -0
  18. package/client/account.d.ts +0 -0
  19. package/client/account.js +1 -0
  20. package/client/auth.d.ts +93 -0
  21. package/client/auth.js +363 -0
  22. package/client/bots.d.ts +6 -0
  23. package/client/bots.js +24 -0
  24. package/client/buttons.d.ts +4 -0
  25. package/client/buttons.js +87 -0
  26. package/client/chats.d.ts +46 -0
  27. package/client/chats.js +350 -0
  28. package/client/dialogs.d.ts +52 -0
  29. package/client/dialogs.js +174 -0
  30. package/client/downloads.d.ts +157 -0
  31. package/client/downloads.js +598 -0
  32. package/client/fs-BROWSER.d.ts +10 -0
  33. package/client/fs-BROWSER.js +13 -0
  34. package/client/fs.d.ts +1 -0
  35. package/client/fs.js +13 -0
  36. package/client/index.d.ts +15 -0
  37. package/client/index.js +50 -0
  38. package/client/messageParse.d.ts +17 -0
  39. package/client/messageParse.js +191 -0
  40. package/client/messages.d.ts +259 -0
  41. package/client/messages.js +804 -0
  42. package/client/os-BROWSER.d.ts +5 -0
  43. package/client/os-BROWSER.js +10 -0
  44. package/client/os.d.ts +2 -0
  45. package/client/os.js +23 -0
  46. package/client/path-BROWSER.d.ts +7 -0
  47. package/client/path-BROWSER.js +8 -0
  48. package/client/path.d.ts +2 -0
  49. package/client/path.js +7 -0
  50. package/client/telegramBaseClient.d.ts +239 -0
  51. package/client/telegramBaseClient.js +369 -0
  52. package/client/updates.d.ts +31 -0
  53. package/client/updates.js +254 -0
  54. package/client/uploads.d.ts +137 -0
  55. package/client/uploads.js +514 -0
  56. package/client/users.d.ts +29 -0
  57. package/client/users.js +491 -0
  58. package/crypto/AuthKey.d.ts +20 -0
  59. package/crypto/AuthKey.js +76 -0
  60. package/crypto/CTR.d.ts +6 -0
  61. package/crypto/CTR.js +35 -0
  62. package/crypto/Factorizator.d.ts +19 -0
  63. package/crypto/Factorizator.js +74 -0
  64. package/crypto/IGE.d.ts +18 -0
  65. package/crypto/IGE.js +34 -0
  66. package/crypto/RSA.d.ts +15 -0
  67. package/crypto/RSA.js +150 -0
  68. package/crypto/converters.d.ts +19 -0
  69. package/crypto/converters.js +52 -0
  70. package/crypto/crypto.d.ts +27 -0
  71. package/crypto/crypto.js +117 -0
  72. package/crypto/words.d.ts +6 -0
  73. package/crypto/words.js +48 -0
  74. package/entityCache.d.ts +7 -0
  75. package/entityCache.js +79 -0
  76. package/errors/Common.d.ts +72 -0
  77. package/errors/Common.js +122 -0
  78. package/errors/RPCBaseErrors.d.ts +84 -0
  79. package/errors/RPCBaseErrors.js +134 -0
  80. package/errors/RPCErrorList.d.ts +37 -0
  81. package/errors/RPCErrorList.js +117 -0
  82. package/errors/index.d.ts +11 -0
  83. package/errors/index.js +29 -0
  84. package/events/Album.d.ts +36 -0
  85. package/events/Album.js +104 -0
  86. package/events/CallbackQuery.d.ts +74 -0
  87. package/events/CallbackQuery.js +193 -0
  88. package/events/DeletedMessage.d.ts +45 -0
  89. package/events/DeletedMessage.js +63 -0
  90. package/events/EditedMessage.d.ts +30 -0
  91. package/events/EditedMessage.js +41 -0
  92. package/events/NewMessage.d.ts +89 -0
  93. package/events/NewMessage.js +182 -0
  94. package/events/Raw.d.ts +29 -0
  95. package/events/Raw.js +43 -0
  96. package/events/common.d.ts +66 -0
  97. package/events/common.js +141 -0
  98. package/events/index.d.ts +2 -0
  99. package/events/index.js +8 -0
  100. package/extensions/AsyncQueue.d.ts +10 -0
  101. package/extensions/AsyncQueue.js +32 -0
  102. package/extensions/BinaryReader.d.ts +100 -0
  103. package/extensions/BinaryReader.js +242 -0
  104. package/extensions/BinaryWriter.d.ts +7 -0
  105. package/extensions/BinaryWriter.js +15 -0
  106. package/extensions/Deferred.d.ts +8 -0
  107. package/extensions/Deferred.js +16 -0
  108. package/extensions/Logger.d.ts +58 -0
  109. package/extensions/Logger.js +127 -0
  110. package/extensions/MessagePacker.d.ts +22 -0
  111. package/extensions/MessagePacker.js +154 -0
  112. package/extensions/PendingState.d.ts +12 -0
  113. package/extensions/PendingState.js +29 -0
  114. package/extensions/PromisedNetSockets-BROWSER.d.ts +8 -0
  115. package/extensions/PromisedNetSockets-BROWSER.js +12 -0
  116. package/extensions/PromisedNetSockets.d.ts +25 -0
  117. package/extensions/PromisedNetSockets.js +178 -0
  118. package/extensions/PromisedWebSockets.d.ts +19 -0
  119. package/extensions/PromisedWebSockets.js +134 -0
  120. package/extensions/html.d.ts +5 -0
  121. package/extensions/html.js +213 -0
  122. package/extensions/index.d.ts +7 -0
  123. package/extensions/index.js +17 -0
  124. package/extensions/markdown.d.ts +5 -0
  125. package/extensions/markdown.js +76 -0
  126. package/extensions/markdownv2.d.ts +5 -0
  127. package/extensions/markdownv2.js +51 -0
  128. package/extensions/net-BROWSER.d.ts +8 -0
  129. package/extensions/net-BROWSER.js +11 -0
  130. package/extensions/net.d.ts +1 -0
  131. package/extensions/net.js +13 -0
  132. package/extensions/socks-BROWSER.d.ts +3 -0
  133. package/extensions/socks-BROWSER.js +6 -0
  134. package/extensions/socks.d.ts +1 -0
  135. package/extensions/socks.js +13 -0
  136. package/index.d.ts +14 -0
  137. package/index.js +48 -0
  138. package/inspect-BROWSER.d.ts +3 -0
  139. package/inspect-BROWSER.js +6 -0
  140. package/inspect.d.ts +1 -0
  141. package/inspect.js +5 -0
  142. package/network/Authenticator.d.ts +12 -0
  143. package/network/Authenticator.js +193 -0
  144. package/network/MTProtoPlainSender.d.ts +19 -0
  145. package/network/MTProtoPlainSender.js +74 -0
  146. package/network/MTProtoSender.d.ts +291 -0
  147. package/network/MTProtoSender.js +854 -0
  148. package/network/MTProtoState.d.ts +103 -0
  149. package/network/MTProtoState.js +267 -0
  150. package/network/RequestState.d.ts +19 -0
  151. package/network/RequestState.js +35 -0
  152. package/network/connection/Connection.d.ts +71 -0
  153. package/network/connection/Connection.js +157 -0
  154. package/network/connection/ConnectionWebSocket.d.ts +19 -0
  155. package/network/connection/ConnectionWebSocket.js +77 -0
  156. package/network/connection/CustomIntermediatePacketCodec.d.ts +8 -0
  157. package/network/connection/CustomIntermediatePacketCodec.js +25 -0
  158. package/network/connection/CustomPromisedWebSockets.d.ts +22 -0
  159. package/network/connection/CustomPromisedWebSockets.js +170 -0
  160. package/network/connection/ObfuscatedIO.d.ts +12 -0
  161. package/network/connection/ObfuscatedIO.js +64 -0
  162. package/network/connection/TCPAbridged.d.ts +20 -0
  163. package/network/connection/TCPAbridged.js +58 -0
  164. package/network/connection/TCPFull.d.ts +17 -0
  165. package/network/connection/TCPFull.js +61 -0
  166. package/network/connection/TCPMTProxy.d.ts +50 -0
  167. package/network/connection/TCPMTProxy.js +121 -0
  168. package/network/connection/TCPObfuscated.d.ts +18 -0
  169. package/network/connection/TCPObfuscated.js +79 -0
  170. package/network/connection/index.d.ts +5 -0
  171. package/network/connection/index.js +13 -0
  172. package/network/index.d.ts +11 -0
  173. package/network/index.js +24 -0
  174. package/package.json +73 -0
  175. package/platform.d.ts +3 -0
  176. package/platform.js +6 -0
  177. package/requestIter.d.ts +24 -0
  178. package/requestIter.js +107 -0
  179. package/sessions/Abstract.d.ts +103 -0
  180. package/sessions/Abstract.js +6 -0
  181. package/sessions/CacheApiSession.d.ts +18 -0
  182. package/sessions/CacheApiSession.js +99 -0
  183. package/sessions/Memory.d.ts +38 -0
  184. package/sessions/Memory.js +272 -0
  185. package/sessions/StoreSession.d.ts +14 -0
  186. package/sessions/StoreSession.js +77 -0
  187. package/sessions/StringSession.d.ts +33 -0
  188. package/sessions/StringSession.js +116 -0
  189. package/sessions/index.d.ts +4 -0
  190. package/sessions/index.js +13 -0
  191. package/sessions/localStorage-BROWSER.d.ts +3 -0
  192. package/sessions/localStorage-BROWSER.js +9 -0
  193. package/sessions/localStorage.d.ts +1 -0
  194. package/sessions/localStorage.js +4 -0
  195. package/tl/AllTLObjects.d.ts +3 -0
  196. package/tl/AllTLObjects.js +17 -0
  197. package/tl/MTProtoRequest.d.ts +19 -0
  198. package/tl/MTProtoRequest.js +38 -0
  199. package/tl/api.d.ts +2 -0
  200. package/tl/api.js +507 -0
  201. package/tl/apiTl.d.ts +2 -0
  202. package/tl/apiTl.js +1638 -0
  203. package/tl/core/GZIPPacked.d.ts +16 -0
  204. package/tl/core/GZIPPacked.js +51 -0
  205. package/tl/core/MessageContainer.d.ts +12 -0
  206. package/tl/core/MessageContainer.js +42 -0
  207. package/tl/core/RPCResult.d.ts +15 -0
  208. package/tl/core/RPCResult.js +32 -0
  209. package/tl/core/TLMessage.d.ts +10 -0
  210. package/tl/core/TLMessage.js +14 -0
  211. package/tl/core/index.d.ts +6 -0
  212. package/tl/core/index.js +16 -0
  213. package/tl/custom/button.d.ts +25 -0
  214. package/tl/custom/button.js +78 -0
  215. package/tl/custom/chatGetter.d.ts +30 -0
  216. package/tl/custom/chatGetter.js +114 -0
  217. package/tl/custom/dialog.d.ts +31 -0
  218. package/tl/custom/dialog.js +40 -0
  219. package/tl/custom/draft.d.ts +22 -0
  220. package/tl/custom/draft.js +48 -0
  221. package/tl/custom/file.d.ts +22 -0
  222. package/tl/custom/file.js +68 -0
  223. package/tl/custom/forward.d.ts +16 -0
  224. package/tl/custom/forward.js +47 -0
  225. package/tl/custom/index.d.ts +1 -0
  226. package/tl/custom/index.js +5 -0
  227. package/tl/custom/inlineResult.d.ts +33 -0
  228. package/tl/custom/inlineResult.js +87 -0
  229. package/tl/custom/inlineResults.d.ts +21 -0
  230. package/tl/custom/inlineResults.js +26 -0
  231. package/tl/custom/message.d.ts +428 -0
  232. package/tl/custom/message.js +702 -0
  233. package/tl/custom/messageButton.d.ts +55 -0
  234. package/tl/custom/messageButton.js +152 -0
  235. package/tl/custom/senderGetter.d.ts +29 -0
  236. package/tl/custom/senderGetter.js +55 -0
  237. package/tl/generateModule.d.ts +1 -0
  238. package/tl/generateModule.js +17 -0
  239. package/tl/generationHelpers.d.ts +12 -0
  240. package/tl/generationHelpers.js +289 -0
  241. package/tl/index.d.ts +3 -0
  242. package/tl/index.js +10 -0
  243. package/tl/patched/index.d.ts +2 -0
  244. package/tl/patched/index.js +77 -0
  245. package/tl/schemaTl.d.ts +2 -0
  246. package/tl/schemaTl.js +64 -0
  247. package/tl/types-generator/generate.d.ts +1 -0
  248. package/tl/types-generator/generate.js +84 -0
  249. package/tl/types-generator/template.d.ts +6 -0
  250. package/tl/types-generator/template.js +257 -0
@@ -0,0 +1,854 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.MTProtoSender = void 0;
7
+ /**
8
+ * MTProto Mobile Protocol sender
9
+ * (https://core.telegram.org/mtproto/description)
10
+ * This class is responsible for wrapping requests into `TLMessage`'s,
11
+ * sending them over the network and receiving them in a safe manner.
12
+ *
13
+ * Automatic reconnection due to temporary network issues is a concern
14
+ * for this class as well, including retry of messages that could not
15
+ * be sent successfully.
16
+ *
17
+ * A new authorization key will be generated on connection if no other
18
+ * key exists yet.
19
+ */
20
+ const AuthKey_1 = require("../crypto/AuthKey");
21
+ const MTProtoState_1 = require("./MTProtoState");
22
+ const extensions_1 = require("../extensions");
23
+ const core_1 = require("../tl/core");
24
+ const tl_1 = require("../tl");
25
+ const big_integer_1 = __importDefault(require("big-integer"));
26
+ const Helpers_1 = require("../Helpers");
27
+ const RequestState_1 = require("./RequestState");
28
+ const Authenticator_1 = require("./Authenticator");
29
+ const MTProtoPlainSender_1 = require("./MTProtoPlainSender");
30
+ const errors_1 = require("../errors");
31
+ const _1 = require("./");
32
+ const Logger_1 = require("../extensions/Logger");
33
+ const async_mutex_1 = require("async-mutex");
34
+ const PendingState_1 = require("../extensions/PendingState");
35
+ var MsgsAck = tl_1.Api.MsgsAck;
36
+ class MTProtoSender {
37
+ /**
38
+ * @param authKey
39
+ * @param opts
40
+ */
41
+ constructor(authKey, opts) {
42
+ this._exportedSenderPromises = new Map();
43
+ const args = Object.assign(Object.assign({}, MTProtoSender.DEFAULT_OPTIONS), opts);
44
+ this._finishedConnecting = false;
45
+ this._cancelSend = false;
46
+ this._connection = undefined;
47
+ this._log = args.logger;
48
+ this._dcId = args.dcId;
49
+ this._retries = args.retries;
50
+ this._currentRetries = 0;
51
+ this._reconnectRetries = args.reconnectRetries;
52
+ this._delay = args.delay;
53
+ this._autoReconnect = args.autoReconnect;
54
+ this._connectTimeout = args.connectTimeout;
55
+ this._authKeyCallback = args.authKeyCallback;
56
+ this._updateCallback = args.updateCallback;
57
+ this._autoReconnectCallback = args.autoReconnectCallback;
58
+ this._isMainSender = args.isMainSender;
59
+ this._senderCallback = args.senderCallback;
60
+ this._client = args.client;
61
+ this._onConnectionBreak = args.onConnectionBreak;
62
+ this._securityChecks = args.securityChecks;
63
+ this._connectMutex = new async_mutex_1.Mutex();
64
+ this._exportedSenderPromises = args._exportedSenderPromises;
65
+ /**
66
+ * whether we disconnected ourself or telegram did it.
67
+ */
68
+ this.userDisconnected = false;
69
+ /**
70
+ * If a disconnection happens for any other reason and it
71
+ * was *not* user action then the pending messages won't
72
+ * be cleared but on explicit user disconnection all the
73
+ * pending futures should be cancelled.
74
+ */
75
+ this.isConnecting = false;
76
+ this._authenticated = false;
77
+ this._userConnected = false;
78
+ this.isReconnecting = false;
79
+ this._reconnecting = false;
80
+ this._disconnected = true;
81
+ /**
82
+ * We need to join the loops upon disconnection
83
+ */
84
+ this._sendLoopHandle = null;
85
+ this._recvLoopHandle = null;
86
+ /**
87
+ * Preserving the references of the AuthKey and state is important
88
+ */
89
+ this.authKey = authKey || new AuthKey_1.AuthKey();
90
+ this._state = new MTProtoState_1.MTProtoState(this.authKey, this._log, this._securityChecks);
91
+ /**
92
+ * Outgoing messages are put in a queue and sent in a batch.
93
+ * Note that here we're also storing their ``_RequestState``.
94
+ */
95
+ this._sendQueue = new extensions_1.MessagePacker(this._state, this._log);
96
+ /**
97
+ * Sent states are remembered until a response is received.
98
+ */
99
+ this._pendingState = new PendingState_1.PendingState();
100
+ /**
101
+ * Responses must be acknowledged, and we can also batch these.
102
+ */
103
+ this._pendingAck = new Set();
104
+ /**
105
+ * Similar to pending_messages but only for the last acknowledges.
106
+ * These can't go in pending_messages because no acknowledge for them
107
+ * is received, but we may still need to resend their state on bad salts.
108
+ */
109
+ this._lastAcks = [];
110
+ /**
111
+ * Jump table from response ID to method that handles it
112
+ */
113
+ this._handlers = {
114
+ [core_1.RPCResult.CONSTRUCTOR_ID.toString()]: this._handleRPCResult.bind(this),
115
+ [core_1.MessageContainer.CONSTRUCTOR_ID.toString()]: this._handleContainer.bind(this),
116
+ [core_1.GZIPPacked.CONSTRUCTOR_ID.toString()]: this._handleGzipPacked.bind(this),
117
+ [tl_1.Api.Pong.CONSTRUCTOR_ID.toString()]: this._handlePong.bind(this),
118
+ [tl_1.Api.BadServerSalt.CONSTRUCTOR_ID.toString()]: this._handleBadServerSalt.bind(this),
119
+ [tl_1.Api.BadMsgNotification.CONSTRUCTOR_ID.toString()]: this._handleBadNotification.bind(this),
120
+ [tl_1.Api.MsgDetailedInfo.CONSTRUCTOR_ID.toString()]: this._handleDetailedInfo.bind(this),
121
+ [tl_1.Api.MsgNewDetailedInfo.CONSTRUCTOR_ID.toString()]: this._handleNewDetailedInfo.bind(this),
122
+ [tl_1.Api.NewSessionCreated.CONSTRUCTOR_ID.toString()]: this._handleNewSessionCreated.bind(this),
123
+ [tl_1.Api.MsgsAck.CONSTRUCTOR_ID.toString()]: this._handleAck.bind(this),
124
+ [tl_1.Api.FutureSalts.CONSTRUCTOR_ID.toString()]: this._handleFutureSalts.bind(this),
125
+ [tl_1.Api.MsgsStateReq.CONSTRUCTOR_ID.toString()]: this._handleStateForgotten.bind(this),
126
+ [tl_1.Api.MsgResendReq.CONSTRUCTOR_ID.toString()]: this._handleStateForgotten.bind(this),
127
+ [tl_1.Api.MsgsAllInfo.CONSTRUCTOR_ID.toString()]: this._handleMsgAll.bind(this),
128
+ };
129
+ }
130
+ set dcId(dcId) {
131
+ this._dcId = dcId;
132
+ }
133
+ get dcId() {
134
+ return this._dcId;
135
+ }
136
+ // Public API
137
+ /**
138
+ * Connects to the specified given connection using the given auth key.
139
+ */
140
+ async connect(connection, force) {
141
+ this.userDisconnected = false;
142
+ if (this._userConnected && !force) {
143
+ this._log.info("User is already connected!");
144
+ return false;
145
+ }
146
+ this.isConnecting = true;
147
+ this._connection = connection;
148
+ this._finishedConnecting = false;
149
+ for (let attempt = 0; attempt < this._retries; attempt++) {
150
+ try {
151
+ await this._connect();
152
+ if (this._updateCallback) {
153
+ this._updateCallback(this._client, new _1.UpdateConnectionState(_1.UpdateConnectionState.connected));
154
+ }
155
+ this._finishedConnecting = true;
156
+ break;
157
+ }
158
+ catch (err) {
159
+ if (this._updateCallback && attempt === 0) {
160
+ this._updateCallback(this._client, new _1.UpdateConnectionState(_1.UpdateConnectionState.disconnected));
161
+ }
162
+ this._log.error(`WebSocket connection failed attempt: ${attempt + 1}`);
163
+ if (this._client._errorHandler) {
164
+ await this._client._errorHandler(err);
165
+ }
166
+ if (this._log.canSend(Logger_1.LogLevel.ERROR)) {
167
+ console.error(err);
168
+ }
169
+ await (0, Helpers_1.sleep)(this._delay);
170
+ }
171
+ }
172
+ this.isConnecting = false;
173
+ return this._finishedConnecting;
174
+ }
175
+ isConnected() {
176
+ return this._userConnected;
177
+ }
178
+ _transportConnected() {
179
+ return (!this._reconnecting &&
180
+ this._connection &&
181
+ this._connection._connected);
182
+ }
183
+ /**
184
+ * Cleanly disconnects the instance from the network, cancels
185
+ * all pending requests, and closes the send and receive loops.
186
+ */
187
+ async disconnect() {
188
+ this.userDisconnected = true;
189
+ this._log.warn("Disconnecting...");
190
+ await this._disconnect();
191
+ }
192
+ /**
193
+ *
194
+ This method enqueues the given request to be sent. Its send
195
+ state will be saved until a response arrives, and a ``Future``
196
+ that will be resolved when the response arrives will be returned:
197
+
198
+ .. code-block:: javascript
199
+
200
+ async def method():
201
+ # Sending (enqueued for the send loop)
202
+ future = sender.send(request)
203
+ # Receiving (waits for the receive loop to read the result)
204
+ result = await future
205
+
206
+ Designed like this because Telegram may send the response at
207
+ any point, and it can send other items while one waits for it.
208
+ Once the response for this future arrives, it is set with the
209
+ received result, quite similar to how a ``receive()`` call
210
+ would otherwise work.
211
+
212
+ Since the receiving part is "built in" the future, it's
213
+ impossible to await receive a result that was never sent.
214
+ * @param request
215
+ * @returns {RequestState}
216
+ */
217
+ send(request) {
218
+ const state = new RequestState_1.RequestState(request);
219
+ this._log.debug(`Send ${request.className}`);
220
+ this._sendQueue.append(state);
221
+ return state.promise;
222
+ }
223
+ addStateToQueue(state) {
224
+ this._sendQueue.append(state);
225
+ }
226
+ /**
227
+ * Performs the actual connection, retrying, generating the
228
+ * authorization key if necessary, and starting the send and
229
+ * receive loops.
230
+ * @returns {Promise<void>}
231
+ * @private
232
+ */
233
+ async _connect() {
234
+ const connection = this._connection;
235
+ if (!connection.isConnected()) {
236
+ this._log.info("Connecting to {0}...".replace("{0}", connection.toString()));
237
+ await connection.connect();
238
+ this._log.debug("Connection success!");
239
+ }
240
+ if (!this.authKey.getKey()) {
241
+ const plain = new MTProtoPlainSender_1.MTProtoPlainSender(connection, this._log);
242
+ this._log.debug("New auth_key attempt ...");
243
+ const res = await (0, Authenticator_1.doAuthentication)(plain, this._log);
244
+ this._log.debug("Generated new auth_key successfully");
245
+ await this.authKey.setKey(res.authKey);
246
+ this._state.timeOffset = res.timeOffset;
247
+ if (this._authKeyCallback) {
248
+ await this._authKeyCallback(this.authKey, this._dcId);
249
+ }
250
+ }
251
+ else {
252
+ this._authenticated = true;
253
+ this._log.debug("Already have an auth key ...");
254
+ }
255
+ this._userConnected = true;
256
+ this.isReconnecting = false;
257
+ if (!this._sendLoopHandle) {
258
+ this._log.debug("Starting send loop");
259
+ this._sendLoopHandle = this._sendLoop();
260
+ }
261
+ if (!this._recvLoopHandle) {
262
+ this._log.debug("Starting receive loop");
263
+ this._recvLoopHandle = this._recvLoop();
264
+ }
265
+ // _disconnected only completes after manual disconnection
266
+ // or errors after which the sender cannot continue such
267
+ // as failing to reconnect or any unexpected error.
268
+ this._log.info("Connection to %s complete!".replace("%s", connection.toString()));
269
+ }
270
+ async _disconnect() {
271
+ const connection = this._connection;
272
+ if (this._updateCallback) {
273
+ this._updateCallback(this._client, new _1.UpdateConnectionState(_1.UpdateConnectionState.disconnected));
274
+ }
275
+ if (connection === undefined) {
276
+ this._log.info("Not disconnecting (already have no connection)");
277
+ return;
278
+ }
279
+ this._log.info("Disconnecting from %s...".replace("%s", connection.toString()));
280
+ this._userConnected = false;
281
+ this._log.debug("Closing current connection...");
282
+ await connection.disconnect();
283
+ }
284
+ _cancelLoops() {
285
+ this._cancelSend = true;
286
+ this.cancellableRecvLoopPromise.cancel();
287
+ }
288
+ /**
289
+ * This loop is responsible for popping items off the send
290
+ * queue, encrypting them, and sending them over the network.
291
+ * Besides `connect`, only this method ever sends data.
292
+ * @returns {Promise<void>}
293
+ * @private
294
+ */
295
+ async _sendLoop() {
296
+ // Retry previous pending requests
297
+ this._sendQueue.prepend(this._pendingState.values());
298
+ this._pendingState.clear();
299
+ while (this._userConnected && !this.isReconnecting) {
300
+ const appendAcks = () => {
301
+ if (this._pendingAck.size) {
302
+ const ack = new RequestState_1.RequestState(new MsgsAck({ msgIds: Array(...this._pendingAck) }));
303
+ this._sendQueue.append(ack);
304
+ this._lastAcks.push(ack);
305
+ if (this._lastAcks.length >= 10) {
306
+ this._lastAcks.shift();
307
+ }
308
+ this._pendingAck.clear();
309
+ }
310
+ };
311
+ appendAcks();
312
+ this._log.debug(`Waiting for messages to send... ${this.isReconnecting}`);
313
+ // TODO Wait for the connection send queue to be empty?
314
+ // This means that while it's not empty we can wait for
315
+ // more messages to be added to the send queue.
316
+ await this._sendQueue.wait();
317
+ // If we've had new ACKs appended while waiting for messages to send, add them to queue
318
+ appendAcks();
319
+ const res = await this._sendQueue.get();
320
+ this._log.debug(`Got ${res === null || res === void 0 ? void 0 : res.batch.length} message(s) to send`);
321
+ if (this.isReconnecting) {
322
+ this._log.debug("Reconnecting");
323
+ this._sendLoopHandle = undefined;
324
+ return;
325
+ }
326
+ if (!res) {
327
+ continue;
328
+ }
329
+ let { data } = res;
330
+ const { batch } = res;
331
+ this._log.debug(`Encrypting ${batch.length} message(s) in ${data.length} bytes for sending`);
332
+ this._log.debug(`Sending ${batch.map((m) => m.request.className)}`);
333
+ data = await this._state.encryptMessageData(data);
334
+ for (const state of batch) {
335
+ if (!Array.isArray(state)) {
336
+ if (state.request.classType === "request") {
337
+ this._pendingState.set(state.msgId, state);
338
+ }
339
+ }
340
+ else {
341
+ for (const s of state) {
342
+ if (s.request.classType === "request") {
343
+ this._pendingState.set(s.msgId, s);
344
+ }
345
+ }
346
+ }
347
+ }
348
+ try {
349
+ await this._connection.send(data);
350
+ }
351
+ catch (e) {
352
+ /** when the server disconnects us we want to reconnect */
353
+ if (!this.userDisconnected) {
354
+ this._log.debug(`Connection closed while sending data ${e}`);
355
+ if (this._log.canSend(Logger_1.LogLevel.DEBUG)) {
356
+ console.error(e);
357
+ }
358
+ this.reconnect();
359
+ }
360
+ this._sendLoopHandle = undefined;
361
+ return;
362
+ }
363
+ this._log.debug("Encrypted messages put in a queue to be sent");
364
+ }
365
+ this._sendLoopHandle = undefined;
366
+ }
367
+ async _recvLoop() {
368
+ let body;
369
+ let message;
370
+ while (this._userConnected && !this.isReconnecting) {
371
+ this._log.debug("Receiving items from the network...");
372
+ try {
373
+ body = await this._connection.recv();
374
+ }
375
+ catch (e) {
376
+ if (this._currentRetries > this._reconnectRetries) {
377
+ for (const state of this._pendingState.values()) {
378
+ state.reject("Maximum reconnection retries reached. Aborting!");
379
+ }
380
+ this.userDisconnected = true;
381
+ return;
382
+ }
383
+ /** when the server disconnects us we want to reconnect */
384
+ if (!this.userDisconnected) {
385
+ this._log.warn("Connection closed while receiving data");
386
+ if (this._log.canSend(Logger_1.LogLevel.WARN)) {
387
+ console.error(e);
388
+ }
389
+ this.reconnect();
390
+ }
391
+ this._recvLoopHandle = undefined;
392
+ return;
393
+ }
394
+ try {
395
+ message = await this._state.decryptMessageData(body);
396
+ }
397
+ catch (e) {
398
+ this._log.debug(`Error while receiving items from the network ${e}`);
399
+ if (e instanceof errors_1.TypeNotFoundError) {
400
+ // Received object which we don't know how to deserialize
401
+ this._log.info(`Type ${e.invalidConstructorId} not found, remaining data ${e.remaining}`);
402
+ continue;
403
+ }
404
+ else if (e instanceof errors_1.SecurityError) {
405
+ // A step while decoding had the incorrect data. This message
406
+ // should not be considered safe and it should be ignored.
407
+ this._log.warn(`Security error while unpacking a received message: ${e}`);
408
+ continue;
409
+ }
410
+ else if (e instanceof errors_1.InvalidBufferError) {
411
+ // 404 means that the server has "forgotten" our auth key and we need to create a new one.
412
+ if (e.code === 404) {
413
+ this._handleBadAuthKey();
414
+ }
415
+ else {
416
+ // this happens sometimes when telegram is having some internal issues.
417
+ // reconnecting should be enough usually
418
+ // since the data we sent and received is probably wrong now.
419
+ this._log.warn(`Invalid buffer ${e.code} for dc ${this._dcId}`);
420
+ this.reconnect();
421
+ }
422
+ this._recvLoopHandle = undefined;
423
+ return;
424
+ }
425
+ else {
426
+ this._log.error("Unhandled error while receiving data");
427
+ if (this._client._errorHandler) {
428
+ await this._client._errorHandler(e);
429
+ }
430
+ if (this._log.canSend(Logger_1.LogLevel.ERROR)) {
431
+ console.log(e);
432
+ }
433
+ this.reconnect();
434
+ this._recvLoopHandle = undefined;
435
+ return;
436
+ }
437
+ }
438
+ try {
439
+ await this._processMessage(message);
440
+ }
441
+ catch (e) {
442
+ // `RPCError` errors except for 'AUTH_KEY_UNREGISTERED' should be handled by the client
443
+ if (e instanceof errors_1.RPCError) {
444
+ if (e.message === "AUTH_KEY_UNREGISTERED" ||
445
+ e.message === "SESSION_REVOKED") {
446
+ // 'AUTH_KEY_UNREGISTERED' for the main sender is thrown when unauthorized and should be ignored
447
+ this._handleBadAuthKey(true);
448
+ }
449
+ }
450
+ else {
451
+ this._log.error("Unhandled error while receiving data");
452
+ if (this._client._errorHandler) {
453
+ await this._client._errorHandler(e);
454
+ }
455
+ if (this._log.canSend(Logger_1.LogLevel.ERROR)) {
456
+ console.log(e);
457
+ }
458
+ }
459
+ }
460
+ this._currentRetries = 0;
461
+ }
462
+ this._recvLoopHandle = undefined;
463
+ }
464
+ // Response Handlers
465
+ _handleBadAuthKey(shouldSkipForMain = false) {
466
+ if (shouldSkipForMain && this._isMainSender) {
467
+ return;
468
+ }
469
+ this._log.warn(`Broken authorization key for dc ${this._dcId}, resetting...`);
470
+ if (this._isMainSender && this._updateCallback) {
471
+ this._updateCallback(this._client, new _1.UpdateConnectionState(_1.UpdateConnectionState.broken));
472
+ }
473
+ else if (!this._isMainSender && this._onConnectionBreak) {
474
+ this._onConnectionBreak(this._dcId);
475
+ }
476
+ }
477
+ /**
478
+ * Adds the given message to the list of messages that must be
479
+ * acknowledged and dispatches control to different ``_handle_*``
480
+ * method based on its type.
481
+ * @param message
482
+ * @returns {Promise<void>}
483
+ * @private
484
+ */
485
+ async _processMessage(message) {
486
+ this._pendingAck.add(message.msgId);
487
+ message.obj = await message.obj;
488
+ let handler = this._handlers[message.obj.CONSTRUCTOR_ID.toString()];
489
+ if (!handler) {
490
+ handler = this._handleUpdate.bind(this);
491
+ }
492
+ await handler(message);
493
+ }
494
+ /**
495
+ * Pops the states known to match the given ID from pending messages.
496
+ * This method should be used when the response isn't specific.
497
+ * @param msgId
498
+ * @returns {*[]}
499
+ * @private
500
+ */
501
+ _popStates(msgId) {
502
+ var _a;
503
+ const state = this._pendingState.getAndDelete(msgId);
504
+ if (state) {
505
+ return [state];
506
+ }
507
+ const toPop = [];
508
+ for (const pendingState of this._pendingState.values()) {
509
+ if ((_a = pendingState.containerId) === null || _a === void 0 ? void 0 : _a.equals(msgId)) {
510
+ toPop.push(pendingState.msgId);
511
+ }
512
+ }
513
+ if (toPop.length) {
514
+ const temp = [];
515
+ for (const x of toPop) {
516
+ temp.push(this._pendingState.getAndDelete(x));
517
+ }
518
+ return temp;
519
+ }
520
+ for (const ack of this._lastAcks) {
521
+ if (ack.msgId === msgId) {
522
+ return [ack];
523
+ }
524
+ }
525
+ return [];
526
+ }
527
+ /**
528
+ * Handles the result for Remote Procedure Calls:
529
+ * rpc_result#f35c6d01 req_msg_id:long result:bytes = RpcResult;
530
+ * This is where the future results for sent requests are set.
531
+ * @param message
532
+ * @returns {Promise<void>}
533
+ * @private
534
+ */
535
+ _handleRPCResult(message) {
536
+ const result = message.obj;
537
+ const state = this._pendingState.getAndDelete(result.reqMsgId);
538
+ this._log.debug(`Handling RPC result for message ${result.reqMsgId}`);
539
+ if (!state) {
540
+ // TODO We should not get responses to things we never sent
541
+ // However receiving a File() with empty bytes is "common".
542
+ // See #658, #759 and #958. They seem to happen in a container
543
+ // which contain the real response right after.
544
+ try {
545
+ const reader = new extensions_1.BinaryReader(result.body);
546
+ if (!(reader.tgReadObject() instanceof tl_1.Api.upload.File)) {
547
+ throw new errors_1.TypeNotFoundError(0, Buffer.alloc(0));
548
+ }
549
+ }
550
+ catch (e) {
551
+ if (e instanceof errors_1.TypeNotFoundError) {
552
+ this._log.info(`Received response without parent request: ${result.body}`);
553
+ return;
554
+ }
555
+ throw e;
556
+ }
557
+ return;
558
+ }
559
+ if (result.error) {
560
+ // eslint-disable-next-line new-cap
561
+ const error = (0, errors_1.RPCMessageToError)(result.error, state.request);
562
+ this._sendQueue.append(new RequestState_1.RequestState(new MsgsAck({ msgIds: [state.msgId] })));
563
+ state.reject(error);
564
+ throw error;
565
+ }
566
+ else {
567
+ try {
568
+ const reader = new extensions_1.BinaryReader(result.body);
569
+ const read = state.request.readResult(reader);
570
+ this._log.debug(`Handling RPC result ${read === null || read === void 0 ? void 0 : read.className}`);
571
+ state.resolve(read);
572
+ }
573
+ catch (err) {
574
+ state.reject(err);
575
+ throw err;
576
+ }
577
+ }
578
+ }
579
+ /**
580
+ * Processes the inner messages of a container with many of them:
581
+ * msg_container#73f1f8dc messages:vector<%Message> = MessageContainer;
582
+ * @param message
583
+ * @returns {Promise<void>}
584
+ * @private
585
+ */
586
+ async _handleContainer(message) {
587
+ this._log.debug("Handling container");
588
+ for (const innerMessage of message.obj.messages) {
589
+ await this._processMessage(innerMessage);
590
+ }
591
+ }
592
+ /**
593
+ * Unpacks the data from a gzipped object and processes it:
594
+ * gzip_packed#3072cfa1 packed_data:bytes = Object;
595
+ * @param message
596
+ * @returns {Promise<void>}
597
+ * @private
598
+ */
599
+ async _handleGzipPacked(message) {
600
+ this._log.debug("Handling gzipped data");
601
+ const reader = new extensions_1.BinaryReader(message.obj.data);
602
+ message.obj = reader.tgReadObject();
603
+ await this._processMessage(message);
604
+ }
605
+ async _handleUpdate(message) {
606
+ if (message.obj.SUBCLASS_OF_ID !== 0x8af52aac) {
607
+ // crc32(b'Updates')
608
+ this._log.warn(`Note: ${message.obj.className} is not an update, not dispatching it`);
609
+ return;
610
+ }
611
+ this._log.debug("Handling update " + message.obj.className);
612
+ if (this._updateCallback) {
613
+ this._updateCallback(this._client, message.obj);
614
+ }
615
+ }
616
+ /**
617
+ * Handles pong results, which don't come inside a ``RPCResult``
618
+ * but are still sent through a request:
619
+ * pong#347773c5 msg_id:long ping_id:long = Pong;
620
+ * @param message
621
+ * @returns {Promise<void>}
622
+ * @private
623
+ */
624
+ async _handlePong(message) {
625
+ const pong = message.obj;
626
+ this._log.debug(`Handling pong for message ${pong.msgId}`);
627
+ const state = this._pendingState.get(pong.msgId.toString());
628
+ this._pendingState.delete(pong.msgId.toString());
629
+ // Todo Check result
630
+ if (state) {
631
+ state.resolve(pong);
632
+ }
633
+ }
634
+ /**
635
+ * Corrects the currently used server salt to use the right value
636
+ * before enqueuing the rejected message to be re-sent:
637
+ * bad_server_salt#edab447b bad_msg_id:long bad_msg_seqno:int
638
+ * error_code:int new_server_salt:long = BadMsgNotification;
639
+ * @param message
640
+ * @returns {Promise<void>}
641
+ * @private
642
+ */
643
+ async _handleBadServerSalt(message) {
644
+ const badSalt = message.obj;
645
+ this._log.debug(`Handling bad salt for message ${badSalt.badMsgId}`);
646
+ this._state.salt = badSalt.newServerSalt;
647
+ const states = this._popStates(badSalt.badMsgId);
648
+ this._sendQueue.extend(states);
649
+ this._log.debug(`${states.length} message(s) will be resent`);
650
+ }
651
+ /**
652
+ * Adjusts the current state to be correct based on the
653
+ * received bad message notification whenever possible:
654
+ * bad_msg_notification#a7eff811 bad_msg_id:long bad_msg_seqno:int
655
+ * error_code:int = BadMsgNotification;
656
+ * @param message
657
+ * @returns {Promise<void>}
658
+ * @private
659
+ */
660
+ async _handleBadNotification(message) {
661
+ const badMsg = message.obj;
662
+ const states = this._popStates(badMsg.badMsgId);
663
+ this._log.debug(`Handling bad msg ${JSON.stringify(badMsg)}`);
664
+ if ([16, 17].includes(badMsg.errorCode)) {
665
+ // Sent msg_id too low or too high (respectively).
666
+ // Use the current msg_id to determine the right time offset.
667
+ const to = this._state.updateTimeOffset((0, big_integer_1.default)(message.msgId));
668
+ this._log.info(`System clock is wrong, set time offset to ${to}s`);
669
+ }
670
+ else if (badMsg.errorCode === 32) {
671
+ // msg_seqno too low, so just pump it up by some "large" amount
672
+ // TODO A better fix would be to start with a new fresh session ID
673
+ this._state._sequence += 64;
674
+ }
675
+ else if (badMsg.errorCode === 33) {
676
+ // msg_seqno too high never seems to happen but just in case
677
+ this._state._sequence -= 16;
678
+ }
679
+ else {
680
+ for (const state of states) {
681
+ state.reject(new errors_1.BadMessageError(state.request, badMsg.errorCode));
682
+ }
683
+ return;
684
+ }
685
+ // Messages are to be re-sent once we've corrected the issue
686
+ this._sendQueue.extend(states);
687
+ this._log.debug(`${states.length} messages will be resent due to bad msg`);
688
+ }
689
+ /**
690
+ * Updates the current status with the received detailed information:
691
+ * msg_detailed_info#276d3ec6 msg_id:long answer_msg_id:long
692
+ * bytes:int status:int = MsgDetailedInfo;
693
+ * @param message
694
+ * @returns {Promise<void>}
695
+ * @private
696
+ */
697
+ async _handleDetailedInfo(message) {
698
+ // TODO https://goo.gl/VvpCC6
699
+ const msgId = message.obj.answerMsgId;
700
+ this._log.debug(`Handling detailed info for message ${msgId}`);
701
+ this._pendingAck.add(msgId);
702
+ }
703
+ /**
704
+ * Updates the current status with the received detailed information:
705
+ * msg_new_detailed_info#809db6df answer_msg_id:long
706
+ * bytes:int status:int = MsgDetailedInfo;
707
+ * @param message
708
+ * @returns {Promise<void>}
709
+ * @private
710
+ */
711
+ async _handleNewDetailedInfo(message) {
712
+ // TODO https://goo.gl/VvpCC6
713
+ const msgId = message.obj.answerMsgId;
714
+ this._log.debug(`Handling new detailed info for message ${msgId}`);
715
+ this._pendingAck.add(msgId);
716
+ }
717
+ /**
718
+ * Updates the current status with the received session information:
719
+ * new_session_created#9ec20908 first_msg_id:long unique_id:long
720
+ * server_salt:long = NewSession;
721
+ * @param message
722
+ * @returns {Promise<void>}
723
+ * @private
724
+ */
725
+ async _handleNewSessionCreated(message) {
726
+ // TODO https://goo.gl/LMyN7A
727
+ this._log.debug("Handling new session created");
728
+ this._state.salt = message.obj.serverSalt;
729
+ }
730
+ /**
731
+ * Handles a server acknowledge about our messages. Normally these can be ignored
732
+ */
733
+ _handleAck() { }
734
+ /**
735
+ * Handles future salt results, which don't come inside a
736
+ * ``rpc_result`` but are still sent through a request:
737
+ * future_salts#ae500895 req_msg_id:long now:int
738
+ * salts:vector<future_salt> = FutureSalts;
739
+ * @param message
740
+ * @returns {Promise<void>}
741
+ * @private
742
+ */
743
+ async _handleFutureSalts(message) {
744
+ this._log.debug(`Handling future salts for message ${message.msgId}`);
745
+ const state = this._pendingState.getAndDelete(message.msgId);
746
+ if (state) {
747
+ state.resolve(message.obj);
748
+ }
749
+ }
750
+ /**
751
+ * Handles both :tl:`MsgsStateReq` and :tl:`MsgResendReq` by
752
+ * enqueuing a :tl:`MsgsStateInfo` to be sent at a later point.
753
+ * @param message
754
+ * @returns {Promise<void>}
755
+ * @private
756
+ */
757
+ async _handleStateForgotten(message) {
758
+ this._sendQueue.append(new RequestState_1.RequestState(new tl_1.Api.MsgsStateInfo({
759
+ reqMsgId: message.msgId,
760
+ info: String.fromCharCode(1).repeat(message.obj.msgIds),
761
+ })));
762
+ }
763
+ /**
764
+ * Handles :tl:`MsgsAllInfo` by doing nothing (yet).
765
+ * @param message
766
+ * @returns {Promise<void>}
767
+ * @private
768
+ */
769
+ async _handleMsgAll(message) { }
770
+ reconnect() {
771
+ if (this._userConnected && !this.isReconnecting) {
772
+ this.isReconnecting = true;
773
+ this._currentRetries++;
774
+ if (this._isMainSender) {
775
+ this._log.debug("Reconnecting all senders");
776
+ for (const promise of this._exportedSenderPromises.values()) {
777
+ promise
778
+ .then((sender) => {
779
+ if (sender && !sender._isMainSender) {
780
+ sender.reconnect();
781
+ }
782
+ })
783
+ .catch((error) => {
784
+ this._log.warn("Error getting sender to reconnect to");
785
+ });
786
+ }
787
+ }
788
+ // we want to wait a second between each reconnect try to not flood the server with reconnects
789
+ // in case of internal server issues.
790
+ (0, Helpers_1.sleep)(1000).then(() => {
791
+ this._log.info("Started reconnecting");
792
+ this._reconnect();
793
+ });
794
+ }
795
+ }
796
+ async _reconnect() {
797
+ try {
798
+ this._log.warn("[Reconnect] Closing current connection...");
799
+ await this._disconnect();
800
+ }
801
+ catch (err) {
802
+ this._log.warn("Error happened while disconnecting");
803
+ if (this._client._errorHandler) {
804
+ await this._client._errorHandler(err);
805
+ }
806
+ if (this._log.canSend(Logger_1.LogLevel.ERROR)) {
807
+ console.error(err);
808
+ }
809
+ }
810
+ this._log.debug(`Adding ${this._sendQueue._pendingStates.length} old request to resend`);
811
+ for (let i = 0; i < this._sendQueue._pendingStates.length; i++) {
812
+ if (this._sendQueue._pendingStates[i].msgId != undefined) {
813
+ this._pendingState.set(this._sendQueue._pendingStates[i].msgId, this._sendQueue._pendingStates[i]);
814
+ }
815
+ }
816
+ this._sendQueue.clear();
817
+ this._state.reset();
818
+ const connection = this._connection;
819
+ // For some reason reusing existing connection caused stuck requests
820
+ // @ts-ignore
821
+ const newConnection = new connection.constructor({
822
+ ip: connection._ip,
823
+ port: connection._port,
824
+ dcId: connection._dcId,
825
+ loggers: connection._log,
826
+ proxy: connection._proxy,
827
+ testServers: connection._testServers,
828
+ socket: this._client.networkSocket,
829
+ });
830
+ await this.connect(newConnection, true);
831
+ this.isReconnecting = false;
832
+ this._sendQueue.prepend(this._pendingState.values());
833
+ this._pendingState.clear();
834
+ if (this._autoReconnectCallback) {
835
+ await this._autoReconnectCallback();
836
+ }
837
+ }
838
+ }
839
+ exports.MTProtoSender = MTProtoSender;
840
+ MTProtoSender.DEFAULT_OPTIONS = {
841
+ logger: null,
842
+ reconnectRetries: Infinity,
843
+ retries: Infinity,
844
+ delay: 2000,
845
+ autoReconnect: true,
846
+ connectTimeout: null,
847
+ authKeyCallback: null,
848
+ updateCallback: null,
849
+ autoReconnectCallback: null,
850
+ isMainSender: null,
851
+ senderCallback: null,
852
+ onConnectionBreak: undefined,
853
+ securityChecks: true,
854
+ };