@armatofik/tgsnake-core 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 (171) hide show
  1. package/COPYING +674 -0
  2. package/COPYING.lesser +165 -0
  3. package/README.md +88 -0
  4. package/lib/package.json +46 -0
  5. package/lib/src/Logger.d.ts +3 -0
  6. package/lib/src/Logger.js +9 -0
  7. package/lib/src/Queue.d.ts +19 -0
  8. package/lib/src/Queue.js +52 -0
  9. package/lib/src/Timeout.d.ts +9 -0
  10. package/lib/src/Timeout.js +44 -0
  11. package/lib/src/Version.node.d.ts +4 -0
  12. package/lib/src/Version.node.js +26 -0
  13. package/lib/src/client/Auth.d.ts +40 -0
  14. package/lib/src/client/Auth.js +317 -0
  15. package/lib/src/client/Client.d.ts +83 -0
  16. package/lib/src/client/Client.js +461 -0
  17. package/lib/src/client/Session.d.ts +9 -0
  18. package/lib/src/client/Session.js +132 -0
  19. package/lib/src/client/index.d.ts +3 -0
  20. package/lib/src/client/index.js +39 -0
  21. package/lib/src/connection/TCP/TCPAbridged.d.ts +9 -0
  22. package/lib/src/connection/TCP/TCPAbridged.js +47 -0
  23. package/lib/src/connection/TCP/TCPAbridgedO.d.ts +12 -0
  24. package/lib/src/connection/TCP/TCPAbridgedO.js +140 -0
  25. package/lib/src/connection/TCP/TCPFull.d.ts +10 -0
  26. package/lib/src/connection/TCP/TCPFull.js +43 -0
  27. package/lib/src/connection/TCP/TCPIntermediate.d.ts +9 -0
  28. package/lib/src/connection/TCP/TCPIntermediate.js +31 -0
  29. package/lib/src/connection/TCP/TCPIntermediateO.d.ts +12 -0
  30. package/lib/src/connection/TCP/TCPIntermediateO.js +123 -0
  31. package/lib/src/connection/TCP/TCPPaddedIntermediate.d.ts +9 -0
  32. package/lib/src/connection/TCP/TCPPaddedIntermediate.js +38 -0
  33. package/lib/src/connection/TCP/index.d.ts +7 -0
  34. package/lib/src/connection/TCP/index.js +17 -0
  35. package/lib/src/connection/TCP/tcp.d.ts +17 -0
  36. package/lib/src/connection/TCP/tcp.js +98 -0
  37. package/lib/src/connection/WebSocket.d.ts +21 -0
  38. package/lib/src/connection/WebSocket.js +279 -0
  39. package/lib/src/connection/connection.d.ts +53 -0
  40. package/lib/src/connection/connection.js +189 -0
  41. package/lib/src/connection/index.d.ts +4 -0
  42. package/lib/src/connection/index.js +41 -0
  43. package/lib/src/crypto/Aes.d.ts +10 -0
  44. package/lib/src/crypto/Aes.js +135 -0
  45. package/lib/src/crypto/Mtproto.d.ts +5 -0
  46. package/lib/src/crypto/Mtproto.js +123 -0
  47. package/lib/src/crypto/Password.d.ts +5 -0
  48. package/lib/src/crypto/Password.js +92 -0
  49. package/lib/src/crypto/Prime.d.ts +4 -0
  50. package/lib/src/crypto/Prime.js +64 -0
  51. package/lib/src/crypto/RSA.d.ts +7 -0
  52. package/lib/src/crypto/RSA.js +99 -0
  53. package/lib/src/crypto/SecretChat.d.ts +5 -0
  54. package/lib/src/crypto/SecretChat.js +136 -0
  55. package/lib/src/crypto/index.d.ts +6 -0
  56. package/lib/src/crypto/index.js +42 -0
  57. package/lib/src/errors/Base.d.ts +9 -0
  58. package/lib/src/errors/Base.js +50 -0
  59. package/lib/src/errors/Client.d.ts +21 -0
  60. package/lib/src/errors/Client.js +29 -0
  61. package/lib/src/errors/File.d.ts +13 -0
  62. package/lib/src/errors/File.js +30 -0
  63. package/lib/src/errors/RpcError.d.ts +22 -0
  64. package/lib/src/errors/RpcError.js +120 -0
  65. package/lib/src/errors/SecretChat.d.ts +13 -0
  66. package/lib/src/errors/SecretChat.js +30 -0
  67. package/lib/src/errors/WebSocket.d.ts +13 -0
  68. package/lib/src/errors/WebSocket.js +30 -0
  69. package/lib/src/errors/exceptions/All.d.ts +774 -0
  70. package/lib/src/errors/exceptions/All.js +778 -0
  71. package/lib/src/errors/exceptions/BadRequest400.d.ts +2345 -0
  72. package/lib/src/errors/exceptions/BadRequest400.js +2945 -0
  73. package/lib/src/errors/exceptions/Flood420.d.ts +37 -0
  74. package/lib/src/errors/exceptions/Flood420.js +49 -0
  75. package/lib/src/errors/exceptions/Forbidden403.d.ts +205 -0
  76. package/lib/src/errors/exceptions/Forbidden403.js +260 -0
  77. package/lib/src/errors/exceptions/InternalServerError500.d.ts +221 -0
  78. package/lib/src/errors/exceptions/InternalServerError500.js +280 -0
  79. package/lib/src/errors/exceptions/NotAcceptable406.d.ts +117 -0
  80. package/lib/src/errors/exceptions/NotAcceptable406.js +149 -0
  81. package/lib/src/errors/exceptions/NotFound404.d.ts +9 -0
  82. package/lib/src/errors/exceptions/NotFound404.js +14 -0
  83. package/lib/src/errors/exceptions/SeeOther303.d.ts +25 -0
  84. package/lib/src/errors/exceptions/SeeOther303.js +34 -0
  85. package/lib/src/errors/exceptions/ServiceUnavailable503.d.ts +17 -0
  86. package/lib/src/errors/exceptions/ServiceUnavailable503.js +24 -0
  87. package/lib/src/errors/exceptions/Unauthorized401.d.ts +41 -0
  88. package/lib/src/errors/exceptions/Unauthorized401.js +54 -0
  89. package/lib/src/errors/exceptions/index.d.ts +10 -0
  90. package/lib/src/errors/exceptions/index.js +48 -0
  91. package/lib/src/errors/index.d.ts +31 -0
  92. package/lib/src/errors/index.js +111 -0
  93. package/lib/src/file/Download.d.ts +11 -0
  94. package/lib/src/file/Download.js +118 -0
  95. package/lib/src/file/File.d.ts +20 -0
  96. package/lib/src/file/File.js +82 -0
  97. package/lib/src/file/Upload.d.ts +19 -0
  98. package/lib/src/file/Upload.js +250 -0
  99. package/lib/src/file/index.d.ts +3 -0
  100. package/lib/src/file/index.js +11 -0
  101. package/lib/src/helpers.d.ts +34 -0
  102. package/lib/src/helpers.js +358 -0
  103. package/lib/src/index.d.ts +16 -0
  104. package/lib/src/index.js +56 -0
  105. package/lib/src/platform.node.d.ts +36 -0
  106. package/lib/src/platform.node.js +109 -0
  107. package/lib/src/raw/All.d.ts +2400 -0
  108. package/lib/src/raw/All.js +2403 -0
  109. package/lib/src/raw/Raw.d.ts +29195 -0
  110. package/lib/src/raw/Raw.js +97277 -0
  111. package/lib/src/raw/core/BytesIO.d.ts +33 -0
  112. package/lib/src/raw/core/BytesIO.js +145 -0
  113. package/lib/src/raw/core/GzipPacked.d.ts +10 -0
  114. package/lib/src/raw/core/GzipPacked.js +60 -0
  115. package/lib/src/raw/core/Message.d.ts +13 -0
  116. package/lib/src/raw/core/Message.js +81 -0
  117. package/lib/src/raw/core/MsgContainer.d.ts +11 -0
  118. package/lib/src/raw/core/MsgContainer.js +69 -0
  119. package/lib/src/raw/core/TLObject.d.ts +19 -0
  120. package/lib/src/raw/core/TLObject.js +108 -0
  121. package/lib/src/raw/core/UpdateSecretChat.d.ts +40 -0
  122. package/lib/src/raw/core/UpdateSecretChat.js +88 -0
  123. package/lib/src/raw/core/index.d.ts +8 -0
  124. package/lib/src/raw/core/index.js +52 -0
  125. package/lib/src/raw/core/primitive/Bool.d.ts +20 -0
  126. package/lib/src/raw/core/primitive/Bool.js +41 -0
  127. package/lib/src/raw/core/primitive/Bytes.d.ts +7 -0
  128. package/lib/src/raw/core/primitive/Bytes.js +41 -0
  129. package/lib/src/raw/core/primitive/Double.d.ts +7 -0
  130. package/lib/src/raw/core/primitive/Double.js +24 -0
  131. package/lib/src/raw/core/primitive/Float.d.ts +7 -0
  132. package/lib/src/raw/core/primitive/Float.js +24 -0
  133. package/lib/src/raw/core/primitive/Int.d.ts +23 -0
  134. package/lib/src/raw/core/primitive/Int.js +122 -0
  135. package/lib/src/raw/core/primitive/String.d.ts +7 -0
  136. package/lib/src/raw/core/primitive/String.js +15 -0
  137. package/lib/src/raw/core/primitive/Vector.d.ts +9 -0
  138. package/lib/src/raw/core/primitive/Vector.js +50 -0
  139. package/lib/src/raw/core/primitive/index.d.ts +7 -0
  140. package/lib/src/raw/core/primitive/index.js +22 -0
  141. package/lib/src/raw/index.d.ts +3 -0
  142. package/lib/src/raw/index.js +17 -0
  143. package/lib/src/session/Auth.d.ts +15 -0
  144. package/lib/src/session/Auth.js +254 -0
  145. package/lib/src/session/Session.d.ts +58 -0
  146. package/lib/src/session/Session.js +571 -0
  147. package/lib/src/session/index.d.ts +7 -0
  148. package/lib/src/session/index.js +49 -0
  149. package/lib/src/session/internals/DataCenter.d.ts +42 -0
  150. package/lib/src/session/internals/DataCenter.js +80 -0
  151. package/lib/src/session/internals/MsgFactory.d.ts +3 -0
  152. package/lib/src/session/internals/MsgFactory.js +23 -0
  153. package/lib/src/session/internals/MsgId.d.ts +9 -0
  154. package/lib/src/session/internals/MsgId.js +24 -0
  155. package/lib/src/session/internals/SeqNo.d.ts +6 -0
  156. package/lib/src/session/internals/SeqNo.js +18 -0
  157. package/lib/src/session/secretChats/SecretChat.d.ts +29 -0
  158. package/lib/src/session/secretChats/SecretChat.js +527 -0
  159. package/lib/src/session/secretChats/index.d.ts +1 -0
  160. package/lib/src/session/secretChats/index.js +5 -0
  161. package/lib/src/storage/Abstract.d.ts +68 -0
  162. package/lib/src/storage/Abstract.js +6 -0
  163. package/lib/src/storage/SecretChat.d.ts +42 -0
  164. package/lib/src/storage/SecretChat.js +99 -0
  165. package/lib/src/storage/Session.d.ts +63 -0
  166. package/lib/src/storage/Session.js +245 -0
  167. package/lib/src/storage/StringSession.d.ts +4 -0
  168. package/lib/src/storage/StringSession.js +77 -0
  169. package/lib/src/storage/index.d.ts +4 -0
  170. package/lib/src/storage/index.js +12 -0
  171. package/package.json +46 -0
@@ -0,0 +1,571 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.Session = exports.Results = void 0;
37
+ const platform_node_js_1 = require("../platform.node.js");
38
+ const Logger_js_1 = require("../Logger.js");
39
+ const connection_js_1 = require("../connection/connection.js");
40
+ const index_js_1 = require("../raw/index.js");
41
+ const Mtproto = __importStar(require("../crypto/Mtproto.js"));
42
+ const Errors = __importStar(require("../errors/index.js"));
43
+ const MsgId_js_1 = require("./internals/MsgId.js");
44
+ const MsgFactory_js_1 = require("./internals/MsgFactory.js");
45
+ const helpers_js_1 = require("../helpers.js");
46
+ const Timeout_js_1 = require("../Timeout.js");
47
+ const Auth_js_1 = require("./Auth.js");
48
+ class Results {
49
+ value;
50
+ reject;
51
+ resolve;
52
+ constructor() {
53
+ this.value = new Promise((resolve, reject) => {
54
+ this.reject = reject;
55
+ this.resolve = resolve;
56
+ });
57
+ }
58
+ }
59
+ exports.Results = Results;
60
+ class Session {
61
+ START_TIMEOUT = 2000;
62
+ WAIT_TIMEOUT = 15000;
63
+ SLEEP_THRESHOLD = 10000;
64
+ MAX_RETRIES;
65
+ ACKS_THRESHOLD = 8;
66
+ PING_INTERVAL = 5000;
67
+ _dcId;
68
+ _authKey;
69
+ _testMode;
70
+ _proxy;
71
+ _isMedia;
72
+ _isCdn;
73
+ _authKeyId;
74
+ _connection;
75
+ _pingTask;
76
+ _client;
77
+ _sessionId = platform_node_js_1.Buffer.from(platform_node_js_1.crypto.randomBytes(8));
78
+ _msgFactory = (0, MsgFactory_js_1.MsgFactory)();
79
+ _msgId = new MsgId_js_1.MsgId();
80
+ _salt = BigInt(0);
81
+ _storedMsgId = [];
82
+ _results = new Map();
83
+ _isConnected = false;
84
+ _pendingAcks = new Set();
85
+ _task = new Timeout_js_1.Timeout();
86
+ _networkTask = true;
87
+ _mutex = new platform_node_js_1.Mutex();
88
+ constructor(client, dcId, authKey, testMode, proxy, isMedia = false, isCdn = false) {
89
+ this._client = client;
90
+ this._dcId = dcId;
91
+ this._authKey = authKey;
92
+ this._testMode = testMode;
93
+ this._proxy = proxy;
94
+ this._isMedia = isMedia;
95
+ this._isCdn = isCdn;
96
+ this._authKeyId = platform_node_js_1.crypto.createHash('sha1').update(this._authKey).digest().subarray(-8);
97
+ this.MAX_RETRIES = client._maxRetries ?? 5;
98
+ }
99
+ async _handlePacket(packet) {
100
+ Logger_js_1.Logger.debug(`[33] Unpacking ${platform_node_js_1.Buffer.byteLength(packet)} bytes packet.`);
101
+ try {
102
+ const data = await Mtproto.unpack(new index_js_1.BytesIO(packet), this._sessionId, this._authKey, this._authKeyId, this._storedMsgId);
103
+ const message = data.body instanceof index_js_1.MsgContainer ? data.body.messages : [data];
104
+ Logger_js_1.Logger.debug(`[34] Reveive ${message.length} data.`);
105
+ for (const msg of message) {
106
+ if (msg.seqNo % 2 === 0) {
107
+ Logger_js_1.Logger.debug(`[35] Setting server time: ${msg.msgId / BigInt(2 ** 32)}.`);
108
+ this._msgId.setServerTime(msg.msgId / BigInt(2 ** 32));
109
+ }
110
+ else {
111
+ if (this._pendingAcks.has(msg.msgId)) {
112
+ Logger_js_1.Logger.debug(`[36] Skiping pending acks msg id: ${msg.msgId}.`);
113
+ continue;
114
+ }
115
+ else {
116
+ Logger_js_1.Logger.debug(`[37] Add msg id ${msg.msgId} to pending acks.`);
117
+ this._pendingAcks.add(msg.msgId);
118
+ }
119
+ }
120
+ if (msg.body instanceof index_js_1.Raw.MsgDetailedInfo || msg.body instanceof index_js_1.Raw.MsgNewDetailedInfo) {
121
+ Logger_js_1.Logger.debug(`[38] Got ${msg.body.constructor.name} and adding to pending acks: ${msg.body.answerMsgId}.`);
122
+ this._pendingAcks.add(msg.body.answerMsgId);
123
+ continue;
124
+ }
125
+ if (msg.body instanceof index_js_1.Raw.NewSessionCreated) {
126
+ Logger_js_1.Logger.debug(`[39] Got ${msg.body.constructor.name} and skiping.`);
127
+ continue;
128
+ }
129
+ let msgId;
130
+ if (msg.body instanceof index_js_1.Raw.BadMsgNotification || msg.body instanceof index_js_1.Raw.BadServerSalt) {
131
+ Logger_js_1.Logger.debug(`[40] Got ${msg.body.constructor.name} and msg id is: ${msg.body.badMsgId}.`);
132
+ msgId = msg.body.badMsgId;
133
+ if (msg.body instanceof index_js_1.Raw.BadServerSalt) {
134
+ this._salt = msg.body.newServerSalt;
135
+ }
136
+ }
137
+ else if (msg.body instanceof index_js_1.Raw.FutureSalts || msg.body instanceof index_js_1.Raw.RpcResult) {
138
+ Logger_js_1.Logger.debug(`[41] Got ${msg.body.constructor.name} and msg id is: ${msg.body.reqMsgId}.`);
139
+ msgId = msg.body.reqMsgId;
140
+ if (msg.body instanceof index_js_1.Raw.RpcResult) {
141
+ msg.body;
142
+ msg.body = msg.body.result;
143
+ }
144
+ }
145
+ else if (msg.body instanceof index_js_1.Raw.Pong) {
146
+ Logger_js_1.Logger.debug(`[42] Got ${msg.body.constructor.name} and msg id is: ${msg.body.msgId}.`);
147
+ msgId = msg.body.msgId;
148
+ }
149
+ else {
150
+ Logger_js_1.Logger.debug(`[43] Handling update ${msg.body.constructor.name}.`);
151
+ this._client.handleUpdate(msg.body);
152
+ }
153
+ if (msgId !== undefined) {
154
+ const promises = this._results.get(BigInt(msgId));
155
+ if (promises !== undefined) {
156
+ Logger_js_1.Logger.debug(`[44] Setting results of msg id ${msgId} with ${msg.body.constructor.name}.`);
157
+ promises.resolve(msg.body);
158
+ }
159
+ }
160
+ }
161
+ if (this._pendingAcks.size >= this.ACKS_THRESHOLD) {
162
+ Logger_js_1.Logger.debug(`[45] Sending ${this._pendingAcks.size} pending aks.`);
163
+ try {
164
+ await this._send(new index_js_1.Raw.MsgsAck({
165
+ msgIds: Array.from(this._pendingAcks),
166
+ }), false);
167
+ Logger_js_1.Logger.debug(`[46] Clearing all pending acks`);
168
+ this._pendingAcks.clear();
169
+ }
170
+ catch (error) {
171
+ if (!(error instanceof Errors.TimeoutError)) {
172
+ Logger_js_1.Logger.debug(`[47] Clearing all pending acks`);
173
+ this._pendingAcks.clear();
174
+ }
175
+ Logger_js_1.Logger.error(`[48] Got error when sending pending acks:`, error);
176
+ }
177
+ }
178
+ }
179
+ catch (error) {
180
+ if (error instanceof Errors.SecurityCheckMismatch) {
181
+ Logger_js_1.Logger.error(`[49] Invalid to unpack ${platform_node_js_1.Buffer.byteLength(packet)} bytes packet cause: ${error.description ?? error.message}`);
182
+ return await this.stop();
183
+ }
184
+ throw error;
185
+ }
186
+ }
187
+ async _send(data, waitResponse = true, timeout = this.WAIT_TIMEOUT) {
188
+ const msg = await this._msgFactory(data, this._msgId);
189
+ const msgId = msg.msgId;
190
+ if (waitResponse) {
191
+ this._results.set(BigInt(msgId), new Results());
192
+ }
193
+ if (msgId === undefined) {
194
+ Logger_js_1.Logger.error(`[107] Can't send request ${data.className} when msgId is undefined.`);
195
+ return;
196
+ }
197
+ Logger_js_1.Logger.debug(`[50] Sending msg id ${msgId} (${data.className}), has ${platform_node_js_1.Buffer.byteLength(msg.write())} bytes message.`);
198
+ const payload = Mtproto.pack(msg, this._salt, this._sessionId, this._authKey, this._authKeyId);
199
+ try {
200
+ Logger_js_1.Logger.debug(`[51] Sending ${platform_node_js_1.Buffer.byteLength(payload)} bytes payload.`);
201
+ await this._connection.send(payload);
202
+ }
203
+ catch (error) {
204
+ Logger_js_1.Logger.error(`[52] Got error when trying to send ${platform_node_js_1.Buffer.byteLength(payload)} bytes payload:`, error);
205
+ if (error instanceof Errors.WSError.ReadClosed ||
206
+ error instanceof Errors.WSError.Disconnected ||
207
+ error instanceof Errors.ClientError.ClientDisconnected) {
208
+ Logger_js_1.Logger.debug(`[108] Restarting client due to disconnected`);
209
+ if (this._client._maxReconnectRetries) {
210
+ return this.retriesReconnect();
211
+ }
212
+ else {
213
+ this.restart();
214
+ }
215
+ return;
216
+ }
217
+ const promises = this._results.get(BigInt(msgId));
218
+ if (promises) {
219
+ promises.reject(error);
220
+ }
221
+ }
222
+ const promises = this._results.get(BigInt(msgId));
223
+ if (waitResponse && promises !== undefined) {
224
+ let response;
225
+ try {
226
+ response = await this._task.run(promises.value, timeout);
227
+ }
228
+ catch (error) {
229
+ Logger_js_1.Logger.error(`[53] Got error when waiting response:`, error);
230
+ }
231
+ if (response) {
232
+ this._results.delete(BigInt(msgId));
233
+ Logger_js_1.Logger.debug(`[54] Got response from msg id ${msgId}: ${response.constructor.name}`);
234
+ if (response instanceof index_js_1.Raw.RpcError) {
235
+ if (data instanceof index_js_1.Raw.InvokeWithoutUpdates ||
236
+ data instanceof index_js_1.Raw.InvokeWithTakeout ||
237
+ data instanceof index_js_1.Raw.InvokeWithTakeout ||
238
+ data instanceof index_js_1.Raw.InvokeWithBusinessConnection ||
239
+ data instanceof index_js_1.Raw.InvokeWithGooglePlayIntegrity ||
240
+ data instanceof index_js_1.Raw.InvokeWithApnsSecret ||
241
+ data instanceof index_js_1.Raw.InvokeWithMessagesRange) {
242
+ data = data.query;
243
+ }
244
+ await Errors.RPCError.raise(response, data);
245
+ }
246
+ else if (response instanceof index_js_1.Raw.BadMsgNotification) {
247
+ throw new Errors.BadMsgNotification(response.errorCode);
248
+ }
249
+ else if (response instanceof index_js_1.Raw.BadServerSalt) {
250
+ this._salt = response.newServerSalt;
251
+ return await this._send(data, waitResponse, timeout);
252
+ }
253
+ else {
254
+ return response;
255
+ }
256
+ }
257
+ else {
258
+ throw new Errors.TimeoutError(timeout);
259
+ }
260
+ }
261
+ }
262
+ _pingWorker() {
263
+ const ping = async () => {
264
+ try {
265
+ if (!this._isConnected)
266
+ return;
267
+ Logger_js_1.Logger.debug(`[55] Ping to telegram server.`);
268
+ await this._send(new index_js_1.Raw.PingDelayDisconnect({
269
+ pingId: BigInt(0),
270
+ disconnectDelay: this.WAIT_TIMEOUT + 10000,
271
+ }), false);
272
+ }
273
+ catch (error) {
274
+ Logger_js_1.Logger.error(`[56] Get error when trying ping to telegram :`, error);
275
+ }
276
+ return this._pingWorker();
277
+ };
278
+ this._pingTask = setTimeout(ping, this.PING_INTERVAL);
279
+ return this._pingTask;
280
+ }
281
+ async _networkWorker() {
282
+ Logger_js_1.Logger.debug(`[57] Network worker started.`);
283
+ let waiting = false;
284
+ while (true) {
285
+ if (!this._networkTask) {
286
+ Logger_js_1.Logger.debug(`[58] Network worker ended`);
287
+ return;
288
+ }
289
+ if (!waiting) {
290
+ try {
291
+ const packet = await this._connection.recv();
292
+ if (packet !== undefined && platform_node_js_1.Buffer.byteLength(packet) !== 4) {
293
+ waiting = true;
294
+ const release = await this._mutex.acquire();
295
+ try {
296
+ await this._handlePacket(packet);
297
+ }
298
+ finally {
299
+ release();
300
+ }
301
+ waiting = false;
302
+ }
303
+ else {
304
+ if (packet) {
305
+ Logger_js_1.Logger.warning(`[59] Server sent "${packet.readInt32LE(0)}"`);
306
+ }
307
+ if (this._isConnected) {
308
+ return this.restart();
309
+ }
310
+ }
311
+ }
312
+ catch (error) {
313
+ Logger_js_1.Logger.error('[139] Network worker error:', error);
314
+ if (!this._isConnected) {
315
+ break;
316
+ }
317
+ else if ((error instanceof Errors.WSError.ReadClosed ||
318
+ error instanceof Errors.WSError.Disconnected ||
319
+ error instanceof Errors.ClientError.ClientDisconnected) &&
320
+ this._client._maxReconnectRetries) {
321
+ return this.retriesReconnect();
322
+ }
323
+ else {
324
+ throw error;
325
+ }
326
+ }
327
+ }
328
+ }
329
+ }
330
+ async retriesReconnect(retries = this._client._maxReconnectRetries) {
331
+ try {
332
+ Logger_js_1.Logger.info('[136] Reconnecting to Telegram Server.');
333
+ Logger_js_1.Logger.debug('[137] Stop ping task.');
334
+ clearTimeout(this._pingTask);
335
+ this._isConnected = false;
336
+ await this._connection.close().catch(() => { });
337
+ await this._connection.connect();
338
+ this._networkWorker();
339
+ const isInited = await this.initConnection();
340
+ if (isInited) {
341
+ this._isConnected = true;
342
+ this._pingWorker();
343
+ if (!this._client._storage.isBot && this._client._takeout) {
344
+ const takeout = await this.invoke(new index_js_1.Raw.account.InitTakeoutSession({}));
345
+ this._client._takeoutId = takeout.id;
346
+ }
347
+ await this.invoke(new index_js_1.Raw.updates.GetState());
348
+ const me = await this.invoke(new index_js_1.Raw.users.GetFullUser({
349
+ id: new index_js_1.Raw.InputUserSelf(),
350
+ }));
351
+ this._client._me = me;
352
+ return me;
353
+ }
354
+ }
355
+ catch (e) {
356
+ Logger_js_1.Logger.error(`[138] Got error when trying to reconnecting to Telegram Server, retries ${retries}:`, e);
357
+ if (!retries) {
358
+ throw e;
359
+ }
360
+ }
361
+ return this.retriesReconnect(retries - 1);
362
+ }
363
+ async stop() {
364
+ const release = await this._mutex.acquire();
365
+ try {
366
+ this._networkTask = false;
367
+ this._isConnected = false;
368
+ clearTimeout(this._pingTask);
369
+ await this._connection.close().catch(() => { });
370
+ this._results.clear();
371
+ this._task.clear();
372
+ Logger_js_1.Logger.info(`[60] Session stopped.`);
373
+ }
374
+ finally {
375
+ release();
376
+ }
377
+ }
378
+ restart() {
379
+ try {
380
+ Logger_js_1.Logger.debug(`[61] Restarting client`);
381
+ this.stop();
382
+ this.start();
383
+ }
384
+ catch (_error) {
385
+ }
386
+ }
387
+ async invoke(data, retries = this.MAX_RETRIES, timeout = this.WAIT_TIMEOUT, sleepThreshold = this.SLEEP_THRESHOLD) {
388
+ Logger_js_1.Logger.debug(`[62] Invoking ${data.className} with parameters: ${retries} retries, ${timeout}ms timeout, ${sleepThreshold}ms sleep threshold.`);
389
+ if (!this._isConnected) {
390
+ Logger_js_1.Logger.error(`[63] Can't sending request when client is unconnected.`);
391
+ throw new Errors.ClientError.ClientDisconnected();
392
+ }
393
+ if (data.classType !== 'functions') {
394
+ throw new Errors.NotAFunctionClass(data.className);
395
+ }
396
+ let className = data.className;
397
+ if (data instanceof index_js_1.Raw.InvokeWithLayer ||
398
+ data instanceof index_js_1.Raw.InvokeWithoutUpdates ||
399
+ data instanceof index_js_1.Raw.InvokeWithTakeout ||
400
+ data instanceof index_js_1.Raw.InvokeWithBusinessConnection ||
401
+ data instanceof index_js_1.Raw.InvokeWithGooglePlayIntegrity ||
402
+ data instanceof index_js_1.Raw.InvokeWithApnsSecret ||
403
+ data instanceof index_js_1.Raw.InvokeWithMessagesRange) {
404
+ className = data.query.className;
405
+ }
406
+ while (true) {
407
+ if (this._isConnected) {
408
+ try {
409
+ const response = await this._send(data, true, timeout);
410
+ if (response !== undefined) {
411
+ return response;
412
+ }
413
+ await (0, helpers_js_1.sleep)(1000);
414
+ }
415
+ catch (error) {
416
+ Logger_js_1.Logger.error(`[64] Got error when trying invoking ${className}:`, error);
417
+ if (error instanceof Errors.Exceptions.Flood.FloodWait) {
418
+ error;
419
+ const amount = Number(error.value ?? 2000);
420
+ if (amount > sleepThreshold >= 0) {
421
+ throw error;
422
+ }
423
+ Logger_js_1.Logger.info(`[65] Waiting for ${amount} seconds before continuing (caused by ${className})`);
424
+ await (0, helpers_js_1.sleep)(amount);
425
+ }
426
+ else if ((error instanceof Errors.Exceptions.SeeOther.FileMigrate ||
427
+ error instanceof Errors.Exceptions.SeeOther.StatsMigrate ||
428
+ error instanceof Errors.Exceptions.SeeOther.NetworkMigrate) &&
429
+ typeof error.value !== 'undefined') {
430
+ Logger_js_1.Logger.error(`[156] Got error when trying invoking ${className}: ${error.message}. Try to reconnecting.`);
431
+ const exportedAuthKey = (await this.invoke(new index_js_1.Raw.auth.ExportAuthorization({ dcId: error.value })));
432
+ const newAuthKey = await new Auth_js_1.Auth(error.value, this._testMode, this._client._ipv6).create();
433
+ const newSession = new Session(this._client, error.value, newAuthKey, this._testMode, this._proxy, this._isMedia, this._isCdn);
434
+ Logger_js_1.Logger.debug(`[157] Reconnecting to telegram server`);
435
+ await newSession.start();
436
+ Logger_js_1.Logger.debug(`[158] Importing auth key`);
437
+ await newSession.invoke(new index_js_1.Raw.auth.ImportAuthorization({
438
+ id: exportedAuthKey.id,
439
+ bytes: exportedAuthKey.bytes,
440
+ }));
441
+ Logger_js_1.Logger.debug(`[159] Session imported, resend the query`);
442
+ const result = await newSession.invoke(data, retries, timeout, sleepThreshold);
443
+ Logger_js_1.Logger.debug(`[160] Closing session in DC${error.value}`);
444
+ await newSession.stop();
445
+ return result;
446
+ }
447
+ else {
448
+ if (!retries) {
449
+ throw error;
450
+ }
451
+ if (retries < 2) {
452
+ Logger_js_1.Logger.info(`[66] [${this.MAX_RETRIES - retries + 1}] Retrying "${className}" due to ${error.message}`);
453
+ }
454
+ else {
455
+ Logger_js_1.Logger.info(`[67] [${this.MAX_RETRIES - retries + 1}] Retrying "${className}" due to ${error.message}`, error);
456
+ }
457
+ await (0, helpers_js_1.sleep)(500);
458
+ return await this.invoke(data, retries - 1, timeout, sleepThreshold);
459
+ }
460
+ }
461
+ }
462
+ else {
463
+ throw new Errors.ClientError.ClientDisconnected();
464
+ }
465
+ }
466
+ }
467
+ async start() {
468
+ while (true) {
469
+ this._connection = new connection_js_1.Connection(this._dcId, this._testMode, this._client._ipv6, this._proxy, this._isMedia, this._client._connectionMode, this._client._local);
470
+ this._networkTask = true;
471
+ try {
472
+ Logger_js_1.Logger.debug(`[68] Connecting to telegram server`);
473
+ await this._connection.connect();
474
+ this._networkWorker();
475
+ await this.initConnection();
476
+ Logger_js_1.Logger.info(`[69] Session initialized: Layer ${index_js_1.Raw.Layer}`);
477
+ Logger_js_1.Logger.info(`[70] Device: ${this._client._deviceModel} - ${this._client._appVersion}`);
478
+ Logger_js_1.Logger.info(`[71] System: ${this._client._systemVersion} (${this._client._langCode.toUpperCase()})`);
479
+ Logger_js_1.Logger.info(`[135] Getting Update State`);
480
+ this._pingWorker();
481
+ this._isConnected = true;
482
+ Logger_js_1.Logger.info('[72] Session Started');
483
+ break;
484
+ }
485
+ catch (error) {
486
+ if (error instanceof Errors.Exceptions.NotAcceptable.AuthKeyDuplicated) {
487
+ await this.stop();
488
+ throw error;
489
+ }
490
+ else if (error instanceof Errors.TimeoutError || error instanceof Errors.RPCError) {
491
+ await (0, helpers_js_1.sleep)(1000);
492
+ await this.stop();
493
+ }
494
+ else {
495
+ break;
496
+ }
497
+ }
498
+ }
499
+ }
500
+ async initConnection() {
501
+ const ping = await this._send(new index_js_1.Raw.Ping({
502
+ pingId: BigInt(0),
503
+ }), true, this.START_TIMEOUT);
504
+ if (!this._isCdn) {
505
+ const initData = await this._send(new index_js_1.Raw.InvokeWithLayer({
506
+ layer: index_js_1.Raw.Layer,
507
+ query: new index_js_1.Raw.InitConnection({
508
+ apiId: this._client._apiId,
509
+ appVersion: this._client._appVersion,
510
+ deviceModel: this._client._deviceModel,
511
+ systemVersion: this._client._systemVersion,
512
+ systemLangCode: this._client._systemLangCode,
513
+ langCode: this._client._langCode,
514
+ langPack: '',
515
+ query: new index_js_1.Raw.help.GetConfig(),
516
+ proxy: this._proxy &&
517
+ 'secret' in this._proxy &&
518
+ 'port' in this._proxy &&
519
+ 'server' in this._proxy
520
+ ? new index_js_1.Raw.InputClientProxy({ address: this._proxy.server, port: this._proxy.port })
521
+ : undefined,
522
+ }),
523
+ }), true, this.START_TIMEOUT);
524
+ return initData;
525
+ }
526
+ return ping;
527
+ }
528
+ [Symbol.for('nodejs.util.inspect.custom')]() {
529
+ const toPrint = {
530
+ _: this.constructor.name,
531
+ };
532
+ for (const key in this) {
533
+ if (Object.prototype.hasOwnProperty.call(this, key)) {
534
+ const value = this[key];
535
+ if (!key.startsWith('_') && value !== undefined && value !== null) {
536
+ toPrint[key] = value;
537
+ }
538
+ }
539
+ }
540
+ return toPrint;
541
+ }
542
+ [Symbol.for('Deno.customInspect')]() {
543
+ return String((0, platform_node_js_1.inspect)(this[Symbol.for('nodejs.util.inspect.custom')](), { colors: true }));
544
+ }
545
+ toJSON() {
546
+ const toPrint = {
547
+ _: this.constructor.name,
548
+ };
549
+ for (const key in this) {
550
+ if (Object.prototype.hasOwnProperty.call(this, key)) {
551
+ const value = this[key];
552
+ if (!key.startsWith('_') && value !== undefined && value !== null) {
553
+ if (typeof value === 'bigint') {
554
+ toPrint[key] = String(value);
555
+ }
556
+ else if (Array.isArray(value)) {
557
+ toPrint[key] = value.map((v) => (typeof v === 'bigint' ? String(v) : v));
558
+ }
559
+ else {
560
+ toPrint[key] = value;
561
+ }
562
+ }
563
+ }
564
+ }
565
+ return toPrint;
566
+ }
567
+ toString() {
568
+ return `[constructor of ${this.constructor.name}] ${JSON.stringify(this, null, 2)}`;
569
+ }
570
+ }
571
+ exports.Session = Session;
@@ -0,0 +1,7 @@
1
+ import * as DataCenter from './internals/DataCenter.js';
2
+ export { SeqNo } from './internals/SeqNo.js';
3
+ export { DataCenter };
4
+ export { Auth } from './Auth.js';
5
+ export { Session, Results } from './Session.js';
6
+ export { MsgFactory } from './internals/MsgFactory.js';
7
+ export { MsgId } from './internals/MsgId.js';
@@ -0,0 +1,49 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.MsgId = exports.MsgFactory = exports.Results = exports.Session = exports.Auth = exports.DataCenter = exports.SeqNo = void 0;
37
+ const DataCenter = __importStar(require("./internals/DataCenter.js"));
38
+ exports.DataCenter = DataCenter;
39
+ var SeqNo_js_1 = require("./internals/SeqNo.js");
40
+ Object.defineProperty(exports, "SeqNo", { enumerable: true, get: function () { return SeqNo_js_1.SeqNo; } });
41
+ var Auth_js_1 = require("./Auth.js");
42
+ Object.defineProperty(exports, "Auth", { enumerable: true, get: function () { return Auth_js_1.Auth; } });
43
+ var Session_js_1 = require("./Session.js");
44
+ Object.defineProperty(exports, "Session", { enumerable: true, get: function () { return Session_js_1.Session; } });
45
+ Object.defineProperty(exports, "Results", { enumerable: true, get: function () { return Session_js_1.Results; } });
46
+ var MsgFactory_js_1 = require("./internals/MsgFactory.js");
47
+ Object.defineProperty(exports, "MsgFactory", { enumerable: true, get: function () { return MsgFactory_js_1.MsgFactory; } });
48
+ var MsgId_js_1 = require("./internals/MsgId.js");
49
+ Object.defineProperty(exports, "MsgId", { enumerable: true, get: function () { return MsgId_js_1.MsgId; } });
@@ -0,0 +1,42 @@
1
+ export declare const DCTest: {
2
+ 1: string;
3
+ 2: string;
4
+ 3: string;
5
+ };
6
+ export declare const DCProd: {
7
+ 1: string;
8
+ 2: string;
9
+ 3: string;
10
+ 4: string;
11
+ 5: string;
12
+ 203: string;
13
+ };
14
+ export declare const WebDC: {
15
+ 1: string;
16
+ 2: string;
17
+ 3: string;
18
+ 4: string;
19
+ 5: string;
20
+ };
21
+ export declare const DCProdMedia: {
22
+ 2: string;
23
+ 4: string;
24
+ };
25
+ export declare const DCTestIPV6: {
26
+ 1: string;
27
+ 2: string;
28
+ 3: string;
29
+ };
30
+ export declare const DCProdIPV6: {
31
+ 1: string;
32
+ 2: string;
33
+ 3: string;
34
+ 4: string;
35
+ 5: string;
36
+ 203: string;
37
+ };
38
+ export declare const DCProdMediaIPV6: {
39
+ 2: string;
40
+ 4: string;
41
+ };
42
+ export declare function DataCenter(dcId: number, testMode: boolean, ipv6: boolean, media: boolean): [ip: string, port: number];