@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,118 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.handleDownload = handleDownload;
4
+ exports.downloadStream = downloadStream;
5
+ const File_js_1 = require("./File.js");
6
+ const index_js_1 = require("../raw/index.js");
7
+ const index_js_2 = require("../session/index.js");
8
+ const helpers_js_1 = require("../helpers.js");
9
+ const index_js_3 = require("../errors/index.js");
10
+ const index_js_4 = require("../crypto/index.js");
11
+ const platform_node_js_1 = require("../platform.node.js");
12
+ async function handleDownload(client, file, location, dcId, limit, offset) {
13
+ const release = await client._getFileSemaphore.acquire();
14
+ let current = 0;
15
+ const total = Math.abs(limit) || (1 << 31) - 1;
16
+ const chunkSize = 1024 * 1024;
17
+ let offsetBytes = helpers_js_1.bigMath.abs(offset) * BigInt(1024);
18
+ const session = new index_js_2.Session(client, dcId, dcId !== client._storage.dcId
19
+ ? await new index_js_2.Auth(dcId, client._storage.testMode, client._ipv6).create()
20
+ : client._storage.authKey, client._storage.testMode, client._proxy, true);
21
+ try {
22
+ await session.start();
23
+ if (dcId !== client._storage.dcId) {
24
+ const exportedAuth = await client.invoke(new index_js_1.Raw.auth.ExportAuthorization({ dcId: dcId }));
25
+ await session.invoke(new index_js_1.Raw.auth.ImportAuthorization({
26
+ id: exportedAuth.id,
27
+ bytes: exportedAuth.bytes,
28
+ }));
29
+ }
30
+ let r = await session.invoke(new index_js_1.Raw.upload.GetFile({
31
+ location: location,
32
+ offset: offsetBytes,
33
+ limit: chunkSize,
34
+ }), session.MAX_RETRIES, session.WAIT_TIMEOUT, 30000);
35
+ if (r instanceof index_js_1.Raw.upload.File) {
36
+ while (true) {
37
+ const chunk = r.bytes;
38
+ file.push(chunk);
39
+ current++;
40
+ offsetBytes += BigInt(chunkSize);
41
+ if (platform_node_js_1.Buffer.byteLength(chunk) < chunkSize || current >= total) {
42
+ break;
43
+ }
44
+ r = await session.invoke(new index_js_1.Raw.upload.GetFile({
45
+ location: location,
46
+ offset: offsetBytes,
47
+ limit: chunkSize,
48
+ }), session.MAX_RETRIES, session.WAIT_TIMEOUT, 30000);
49
+ }
50
+ }
51
+ else if (r instanceof index_js_1.Raw.upload.FileCdnRedirect) {
52
+ const cdnSession = new index_js_2.Session(client, dcId, dcId !== client._storage.dcId
53
+ ? await new index_js_2.Auth(dcId, client._storage.testMode, client._ipv6).create()
54
+ : client._storage.authKey, client._storage.testMode, client._proxy, true, true);
55
+ try {
56
+ while (true) {
57
+ const r2 = (await cdnSession.invoke(new index_js_1.Raw.upload.GetCdnFile({
58
+ fileToken: r.fileToken,
59
+ offset: offsetBytes,
60
+ limit: chunkSize,
61
+ }), session.MAX_RETRIES, session.WAIT_TIMEOUT, 30000));
62
+ if (r2 instanceof index_js_1.Raw.upload.CdnFileReuploadNeeded) {
63
+ try {
64
+ await session.invoke(new index_js_1.Raw.upload.ReuploadCdnFile({
65
+ fileToken: r.fileToken,
66
+ requestToken: r2.requestToken,
67
+ }));
68
+ }
69
+ catch (error) {
70
+ if (error instanceof index_js_3.Exceptions.BadRequest.VolumeLocNotFound) {
71
+ break;
72
+ }
73
+ }
74
+ }
75
+ const chunk = r2.bytes;
76
+ const decryptedChunk = await index_js_4.AES.ctr256Cipher(r.encryptionKey, platform_node_js_1.Buffer.concat([
77
+ r.encryptionIv.subarray(0, -4),
78
+ (0, helpers_js_1.bigintToBuffer)(offsetBytes / BigInt(16), 4, false),
79
+ ]))(chunk);
80
+ const hashes = (await session.invoke(new index_js_1.Raw.upload.GetCdnFileHashes({
81
+ fileToken: r.fileToken,
82
+ offset: offsetBytes,
83
+ })));
84
+ for (let i = 0; i < hashes.length; i++) {
85
+ const hash = hashes[i];
86
+ const hashChunk = decryptedChunk.subarray(hash.limit * i, hash.limit * (i + 1));
87
+ const chash = platform_node_js_1.crypto.createHash('sha256');
88
+ chash.update(hashChunk);
89
+ index_js_3.CDNFileHashMismatch.check(chash.digest('hex') === hash.hash.toString('hex'), `CDN file hash mismatch when downloading cdn file`);
90
+ }
91
+ current++;
92
+ offsetBytes += BigInt(chunkSize);
93
+ if (platform_node_js_1.Buffer.byteLength(chunk) < chunkSize || current >= total) {
94
+ break;
95
+ }
96
+ }
97
+ }
98
+ finally {
99
+ await cdnSession.stop();
100
+ }
101
+ }
102
+ }
103
+ finally {
104
+ await session.stop();
105
+ file.push(null);
106
+ if (platform_node_js_1.isDeno) {
107
+ release();
108
+ }
109
+ else {
110
+ release[1]();
111
+ }
112
+ }
113
+ }
114
+ function downloadStream(client, location, dcId, limit = 0, offset = BigInt(0)) {
115
+ const file = new File_js_1.File();
116
+ handleDownload(client, file, location, dcId, limit, offset);
117
+ return file;
118
+ }
@@ -0,0 +1,20 @@
1
+ import { Duplex, Buffer, type BufferEncoding } from '../platform.node.js';
2
+ import { BytesIO } from '../raw/index.js';
3
+ export type TypeFileChunk = Buffer | ArrayBufferView | DataView | string | null | any;
4
+ export type TypeFileCallback = (error?: any) => void;
5
+ export declare class File extends Duplex {
6
+ protected _bytes: BytesIO;
7
+ constructor();
8
+ _write(chunk: TypeFileChunk, encoding: BufferEncoding, next: TypeFileCallback): void;
9
+ _read(length?: number): Buffer | null;
10
+ push(chunk: TypeFileChunk, encoding?: BufferEncoding): boolean;
11
+ on(event: string, callback: TypeFileCallback): this;
12
+ pipe(destination: any, options?: {
13
+ end?: boolean;
14
+ }): any;
15
+ get bytes(): BytesIO;
16
+ toJSON(): {
17
+ [key: string]: any;
18
+ };
19
+ toString(): string;
20
+ }
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.File = void 0;
4
+ const platform_node_js_1 = require("../platform.node.js");
5
+ const index_js_1 = require("../raw/index.js");
6
+ class File extends platform_node_js_1.Duplex {
7
+ _bytes;
8
+ constructor() {
9
+ super({
10
+ readableHighWaterMark: 512 * 1024,
11
+ writableHighWaterMark: 512 * 1024,
12
+ });
13
+ this._bytes = new index_js_1.BytesIO();
14
+ }
15
+ _write(chunk, encoding, next) {
16
+ this._bytes.write(platform_node_js_1.Buffer.from(chunk, encoding));
17
+ return next();
18
+ }
19
+ _read(length) {
20
+ if (length) {
21
+ if (this._bytes.length > 0) {
22
+ const bytes = this._bytes.read(length);
23
+ if (platform_node_js_1.Buffer.byteLength(bytes) > 0) {
24
+ return bytes;
25
+ }
26
+ }
27
+ }
28
+ else {
29
+ if (this._bytes.length > 0) {
30
+ return this._bytes.buffer;
31
+ }
32
+ }
33
+ return null;
34
+ }
35
+ push(chunk, encoding) {
36
+ return super.push(chunk, encoding);
37
+ }
38
+ on(event, callback) {
39
+ return super.on(event, callback);
40
+ }
41
+ pipe(destination, options) {
42
+ return super.pipe(destination, options);
43
+ }
44
+ get bytes() {
45
+ return this._bytes;
46
+ }
47
+ [Symbol.for('nodejs.util.inspect.custom')]() {
48
+ const toPrint = {
49
+ _: this.constructor.name,
50
+ };
51
+ for (const key in this) {
52
+ if (Object.prototype.hasOwnProperty.call(this, key)) {
53
+ const value = this[key];
54
+ if (!key.startsWith('_') && value !== undefined && value !== null) {
55
+ toPrint[key] = value;
56
+ }
57
+ }
58
+ }
59
+ return toPrint;
60
+ }
61
+ [Symbol.for('Deno.customInspect')]() {
62
+ return String((0, platform_node_js_1.inspect)(this[Symbol.for('nodejs.util.inspect.custom')](), { colors: true }));
63
+ }
64
+ toJSON() {
65
+ const toPrint = {
66
+ _: this.constructor.name,
67
+ };
68
+ for (const key in this) {
69
+ if (Object.prototype.hasOwnProperty.call(this, key)) {
70
+ const value = this[key];
71
+ if (!key.startsWith('_') && value !== undefined && value !== null) {
72
+ toPrint[key] = typeof value === 'bigint' ? String(value) : value;
73
+ }
74
+ }
75
+ }
76
+ return toPrint;
77
+ }
78
+ toString() {
79
+ return `[constructor of ${this.constructor.name}] ${JSON.stringify(this, null, 2)}`;
80
+ }
81
+ }
82
+ exports.File = File;
@@ -0,0 +1,19 @@
1
+ import { type Readable, Buffer } from '../platform.node.js';
2
+ import { type Client } from '../client/Client.js';
3
+ import { File } from './File.js';
4
+ import { Raw } from '../raw/index.js';
5
+ export type Progress = (current: number, total: number) => any;
6
+ export interface SaveFileParams {
7
+ source: Buffer;
8
+ fileName?: string;
9
+ fileId?: bigint;
10
+ filePart?: number;
11
+ progress?: Progress;
12
+ }
13
+ export interface SaveFileStreamParams {
14
+ source: Readable | File;
15
+ fileName?: string;
16
+ progress?: Progress;
17
+ }
18
+ export declare function upload(client: Client, source: Buffer, fileName?: string, fileId?: bigint, filePart?: number, progress?: Progress): Promise<Raw.InputFile | Raw.InputFileBig | undefined>;
19
+ export declare function uploadStream(client: Client, source: Readable | File, fileName?: string, progress?: Progress): Promise<Raw.InputFileBig | undefined>;
@@ -0,0 +1,250 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.upload = upload;
4
+ exports.uploadStream = uploadStream;
5
+ const platform_node_js_1 = require("../platform.node.js");
6
+ const Queue_js_1 = require("../Queue.js");
7
+ const index_js_1 = require("../errors/index.js");
8
+ const index_js_2 = require("../session/index.js");
9
+ const index_js_3 = require("../raw/index.js");
10
+ const Logger_js_1 = require("../Logger.js");
11
+ async function upload(client, source, fileName, fileId, filePart = 0, progress) {
12
+ const release = await client._saveFileSemaphore.acquire();
13
+ try {
14
+ const queue = new Queue_js_1.Queue(1);
15
+ const partSize = 512 * 1024;
16
+ const user = client._me?.users.find((user) => user.id === client._me?.fullUser.id);
17
+ const premium = user && 'premium' in user ? user.premium : false;
18
+ const fileSizeLimitMiB = premium ? 4000 : 2000;
19
+ const fileSize = platform_node_js_1.Buffer.byteLength(source);
20
+ if (fileSize === 0) {
21
+ throw new index_js_1.FileErrors.FileUploadZero();
22
+ }
23
+ if (fileSize > fileSizeLimitMiB * 1024 * 1024) {
24
+ throw new index_js_1.FileErrors.FileUploadBigger(fileSizeLimitMiB * 1024 * 1024, fileSize);
25
+ }
26
+ const worker = async (session, index) => {
27
+ Logger_js_1.Logger.debug(`[142] Worker ${index} running`);
28
+ while (true) {
29
+ Logger_js_1.Logger.debug(`[143] Worker ${index} getting the queue`);
30
+ const data = await queue.get();
31
+ Logger_js_1.Logger.debug(`[144] Worker ${index} successfully getting the queue`);
32
+ if (data === null) {
33
+ Logger_js_1.Logger.debug(`[145] Worker ${index} finished`);
34
+ return;
35
+ }
36
+ if (data) {
37
+ try {
38
+ Logger_js_1.Logger.debug(`[146] Worker ${index} sending data from queue`);
39
+ await session.invoke(data);
40
+ }
41
+ catch (error) {
42
+ Logger_js_1.Logger.error(`[147] Error when uploading file:`, error);
43
+ }
44
+ }
45
+ }
46
+ };
47
+ const fileTotalParts = Math.ceil(fileSize / partSize);
48
+ const isBig = fileSize > 10 * 1024 * 1024;
49
+ const workersAmount = isBig ? 4 : 1;
50
+ const isMissingPart = fileId !== undefined;
51
+ fileId = fileId || platform_node_js_1.Buffer.from(platform_node_js_1.crypto.randomBytes(8)).readBigInt64LE();
52
+ const file = new index_js_3.BytesIO(source);
53
+ const md5 = !isBig && !isMissingPart ? platform_node_js_1.crypto.createHash('md5').update(source).digest('hex') : '';
54
+ const session = new index_js_2.Session(client, client._storage.dcId, client._storage.authKey, client._storage.testMode, client._proxy, true);
55
+ const workers = Array(workersAmount)
56
+ .fill(null)
57
+ .map((_, i) => (() => worker(session, i + 1))());
58
+ try {
59
+ await session.start();
60
+ file.seek(partSize * filePart);
61
+ while (true) {
62
+ const chunk = file.read(partSize);
63
+ if (!platform_node_js_1.Buffer.byteLength(chunk)) {
64
+ break;
65
+ }
66
+ if (isBig) {
67
+ await queue.put(new index_js_3.Raw.upload.SaveBigFilePart({
68
+ fileId: fileId,
69
+ filePart: filePart,
70
+ fileTotalParts: fileTotalParts,
71
+ bytes: chunk,
72
+ }));
73
+ }
74
+ else {
75
+ await queue.put(new index_js_3.Raw.upload.SaveFilePart({
76
+ fileId: fileId,
77
+ filePart: filePart,
78
+ bytes: chunk,
79
+ }));
80
+ }
81
+ if (isMissingPart) {
82
+ return;
83
+ }
84
+ filePart += 1;
85
+ if (progress) {
86
+ progress(Math.min(filePart * partSize, fileSize), fileSize);
87
+ }
88
+ }
89
+ if (isBig) {
90
+ return new index_js_3.Raw.InputFileBig({
91
+ id: fileId,
92
+ parts: fileTotalParts,
93
+ name: fileName ?? 'file.unknown',
94
+ });
95
+ }
96
+ else {
97
+ return new index_js_3.Raw.InputFile({
98
+ id: fileId,
99
+ parts: fileTotalParts,
100
+ name: fileName ?? 'file.unknown',
101
+ md5Checksum: md5,
102
+ });
103
+ }
104
+ }
105
+ catch (error) {
106
+ Logger_js_1.Logger.error('[141] Got error when trying to put rpc to queue', error);
107
+ }
108
+ finally {
109
+ for (let _ of workers) {
110
+ await queue.put(null);
111
+ }
112
+ await queue.put(null);
113
+ await queue.get();
114
+ await session.stop();
115
+ }
116
+ }
117
+ finally {
118
+ if (platform_node_js_1.isDeno) {
119
+ release();
120
+ }
121
+ else {
122
+ release[1]();
123
+ }
124
+ }
125
+ }
126
+ async function uploadStream(client, source, fileName, progress) {
127
+ if (!source.readable || !source._readableState) {
128
+ throw new index_js_1.FileErrors.FileIsNotReadable();
129
+ }
130
+ if (source.readableHighWaterMark !== 512 * 1024) {
131
+ source._readableState.highWaterMark = 512 * 1024;
132
+ }
133
+ const release = await client._saveFileSemaphore.acquire();
134
+ Logger_js_1.Logger.debug(`[148] Upload stream started.`);
135
+ try {
136
+ let resolve;
137
+ const partSize = 512 * 1024;
138
+ let filePart = 0;
139
+ let totalStreamSize = 0;
140
+ const fileId = platform_node_js_1.Buffer.from(platform_node_js_1.crypto.randomBytes(8)).readBigInt64LE();
141
+ let hasEndedBefore = false;
142
+ const queue = new Queue_js_1.Queue(1);
143
+ const waitUpload = new Promise((res) => {
144
+ resolve = res;
145
+ });
146
+ const user = client._me?.users.find((user) => user.id === client._me?.fullUser.id);
147
+ const premium = user && 'premium' in user ? true : false;
148
+ const fileSizeLimitMiB = premium ? 4000 : 2000;
149
+ const worker = async (session, index) => {
150
+ Logger_js_1.Logger.debug(`[149] Worker ${index} running`);
151
+ while (true) {
152
+ Logger_js_1.Logger.debug(`[150] Worker ${index} getting the queue`);
153
+ const data = await queue.get();
154
+ Logger_js_1.Logger.debug(`[151] Worker ${index} successfully getting the queue`);
155
+ if (data === null) {
156
+ Logger_js_1.Logger.debug(`[152] Worker ${index} finished`);
157
+ return;
158
+ }
159
+ if (data) {
160
+ try {
161
+ Logger_js_1.Logger.debug(`[153] Worker ${index} sending data from queue`);
162
+ await session.invoke(data);
163
+ }
164
+ catch (error) {
165
+ Logger_js_1.Logger.error(`[154] Error when uploading file:`, error);
166
+ }
167
+ }
168
+ }
169
+ };
170
+ const session = new index_js_2.Session(client, client._storage.dcId, client._storage.authKey, client._storage.testMode, client._proxy, true);
171
+ const workers = Array(4)
172
+ .fill(null)
173
+ .map((_, i) => (() => worker(session, i + 1))());
174
+ try {
175
+ await session.start();
176
+ const uploader = new platform_node_js_1.Writable({
177
+ highWaterMark: 512 * 1024,
178
+ async write(chunk, encoding, callback) {
179
+ totalStreamSize += platform_node_js_1.Buffer.byteLength(chunk);
180
+ if (totalStreamSize > fileSizeLimitMiB * 1024 * 1024) {
181
+ throw new index_js_1.FileErrors.FileUploadBigger(fileSizeLimitMiB * 1024 * 1024, totalStreamSize);
182
+ }
183
+ if (platform_node_js_1.Buffer.byteLength(chunk) < 512 * 1024) {
184
+ hasEndedBefore = true;
185
+ await queue.put(new index_js_3.Raw.upload.SaveBigFilePart({
186
+ fileId: fileId,
187
+ filePart: filePart,
188
+ fileTotalParts: Math.ceil(totalStreamSize / partSize),
189
+ bytes: platform_node_js_1.Buffer.from(chunk, encoding),
190
+ }));
191
+ }
192
+ else {
193
+ await queue.put(new index_js_3.Raw.upload.SaveBigFilePart({
194
+ fileId: fileId,
195
+ filePart: filePart,
196
+ fileTotalParts: -1,
197
+ bytes: platform_node_js_1.Buffer.from(chunk, encoding),
198
+ }));
199
+ }
200
+ filePart += 1;
201
+ if (progress) {
202
+ progress(filePart * partSize, -1);
203
+ }
204
+ return callback();
205
+ },
206
+ });
207
+ uploader.on('finish', async () => {
208
+ if (!hasEndedBefore) {
209
+ hasEndedBefore = true;
210
+ await queue.put(new index_js_3.Raw.upload.SaveBigFilePart({
211
+ fileId: fileId,
212
+ filePart: filePart,
213
+ fileTotalParts: Math.ceil(totalStreamSize / partSize),
214
+ bytes: platform_node_js_1.Buffer.alloc(0),
215
+ }));
216
+ }
217
+ if (progress) {
218
+ progress(filePart * partSize, totalStreamSize);
219
+ }
220
+ resolve(true);
221
+ });
222
+ source.pipe(uploader);
223
+ await waitUpload;
224
+ return new index_js_3.Raw.InputFileBig({
225
+ id: fileId,
226
+ parts: Math.ceil(totalStreamSize / partSize),
227
+ name: fileName ?? 'file.unknown',
228
+ });
229
+ }
230
+ catch (error) {
231
+ Logger_js_1.Logger.error('[155] Got error when trying to put rpc to queue', error);
232
+ }
233
+ finally {
234
+ for (let _ of workers) {
235
+ await queue.put(null);
236
+ }
237
+ await queue.put(null);
238
+ await queue.get();
239
+ await session.stop();
240
+ }
241
+ }
242
+ finally {
243
+ if (platform_node_js_1.isDeno) {
244
+ release();
245
+ }
246
+ else {
247
+ release[1]();
248
+ }
249
+ }
250
+ }
@@ -0,0 +1,3 @@
1
+ export { File } from './File.js';
2
+ export { upload, uploadStream, type Progress, type SaveFileParams, type SaveFileStreamParams, } from './Upload.js';
3
+ export { handleDownload, downloadStream, type DownloadParam } from './Download.js';
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.downloadStream = exports.handleDownload = exports.uploadStream = exports.upload = exports.File = void 0;
4
+ var File_js_1 = require("./File.js");
5
+ Object.defineProperty(exports, "File", { enumerable: true, get: function () { return File_js_1.File; } });
6
+ var Upload_js_1 = require("./Upload.js");
7
+ Object.defineProperty(exports, "upload", { enumerable: true, get: function () { return Upload_js_1.upload; } });
8
+ Object.defineProperty(exports, "uploadStream", { enumerable: true, get: function () { return Upload_js_1.uploadStream; } });
9
+ var Download_js_1 = require("./Download.js");
10
+ Object.defineProperty(exports, "handleDownload", { enumerable: true, get: function () { return Download_js_1.handleDownload; } });
11
+ Object.defineProperty(exports, "downloadStream", { enumerable: true, get: function () { return Download_js_1.downloadStream; } });
@@ -0,0 +1,34 @@
1
+ import { Buffer } from './platform.node.js';
2
+ export declare function bigintToBuffer(int: bigint, padding: number, litte?: boolean, signed?: boolean): Buffer<ArrayBuffer>;
3
+ export declare function includesBuffer(array: Array<Buffer>, buffer: Buffer): boolean;
4
+ export declare function sliceBuffer(buffer: Buffer, start: number, stop: number, step?: number): Buffer<ArrayBufferLike>;
5
+ export declare function makeCRCTable(): any[];
6
+ export declare function crc32(str: Buffer | string): number;
7
+ export declare function sleep(ms: number): Promise<unknown>;
8
+ export declare function bufferToBigint(buffer: Buffer, little?: boolean, signed?: boolean): bigint;
9
+ export declare function mod(n: number, m: number): number;
10
+ export declare function bigIntMod(n: bigint, m: bigint): bigint;
11
+ export declare function range(start: number, stop: number, step?: number): Array<number>;
12
+ export declare function rangeBigint(start: bigint, stop: bigint, step?: number): Array<bigint>;
13
+ export declare function randint(min: number, max: number): number;
14
+ export declare function randBigint(min: bigint, max: bigint): any;
15
+ export declare function pow(x: number, y: number, z?: number): number;
16
+ export declare function bigIntPow(x: bigint, y: bigint, z?: bigint): bigint;
17
+ declare const bigMath: {
18
+ abs(x: bigint): bigint;
19
+ sign(x: bigint): bigint;
20
+ pow(base: bigint, exponent: bigint): bigint;
21
+ min(value: bigint, ...values: Array<bigint>): bigint;
22
+ max(value: bigint, ...values: Array<bigint>): bigint;
23
+ };
24
+ export { bigMath };
25
+ export declare const MIN_CHANNEL_ID: bigint;
26
+ export declare const MAX_CHANNEL_ID: bigint;
27
+ export declare const MIN_CHAT_ID: bigint;
28
+ export declare const MAX_USER_ID_OLD: bigint;
29
+ export declare const MAX_USER_ID: bigint;
30
+ export declare function getChannelId(id: bigint): bigint;
31
+ export declare function getPeerType(id: bigint): "chat" | "channel" | "user" | undefined;
32
+ export declare function base64urlTobase64(text: string): string;
33
+ export declare function generateRandomBigInt(lowBigInt: bigint, highBigInt: bigint): bigint;
34
+ export declare function normalizeSecretString(secret: string): Buffer<ArrayBuffer>;