@tgsnake/core
Version:
Pure Telegram MTProto library for nodejs
99 lines (98 loc) • 3.19 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.TCP = void 0;
const WebSocket_js_1 = require("../WebSocket.js");
const platform_node_js_1 = require("../../platform.node.js");
const Timeout_js_1 = require("../../Timeout.js");
const helpers_js_1 = require("../../helpers.js");
class TCP {
_socks;
_task;
_mutex = new platform_node_js_1.Mutex();
connected;
constructor() {
this._task = new Timeout_js_1.Timeout();
this._socks = new WebSocket_js_1.Socket(10 * 1000);
}
async connect(ip, port, proxy, _dcId) {
const release = await this._mutex.acquire();
try {
await this._socks.connect(ip, port, proxy);
}
finally {
release();
}
}
async close() {
await this._task.clear();
await (0, helpers_js_1.sleep)(1);
if (!this._socks)
return;
return await this._socks.destroy();
}
async send(data) {
const release = await this._mutex.acquire();
try {
await this._socks.send(data);
}
finally {
release();
}
}
async recv(length = 0) {
let data = platform_node_js_1.Buffer.alloc(0);
while (platform_node_js_1.Buffer.byteLength(data) < length) {
const chunk = await this._task.run(this._socks.read(length - platform_node_js_1.Buffer.byteLength(data)), this._socks.timeout, () => { });
if (chunk) {
data = platform_node_js_1.Buffer.concat([data, chunk]);
}
else {
return;
}
}
return data;
}
[Symbol.for('nodejs.util.inspect.custom')]() {
const toPrint = {
_: this.constructor.name,
};
for (const key in this) {
if (this.hasOwnProperty(key)) {
const value = this[key];
if (!key.startsWith('_') && value !== undefined && value !== null) {
toPrint[key] = value;
}
}
}
return toPrint;
}
[Symbol.for('Deno.customInspect')]() {
return String((0, platform_node_js_1.inspect)(this[Symbol.for('nodejs.util.inspect.custom')](), { colors: true }));
}
toJSON() {
const toPrint = {
_: this.constructor.name,
};
for (const key in this) {
if (this.hasOwnProperty(key)) {
const value = this[key];
if (!key.startsWith('_') && value !== undefined && value !== null) {
if (typeof value === 'bigint') {
toPrint[key] = String(value);
}
else if (Array.isArray(value)) {
toPrint[key] = value.map((v) => (typeof v === 'bigint' ? String(v) : v));
}
else {
toPrint[key] = value;
}
}
}
}
return toPrint;
}
toString() {
return `[constructor of ${this.constructor.name}] ${JSON.stringify(this, null, 2)}`;
}
}
exports.TCP = TCP;