GramJs: Auto-fixes by ESLint

This commit is contained in:
Alexander Zinchuk 2021-05-08 22:41:28 +03:00
parent 5f4a210d7b
commit 146a0db3c2
46 changed files with 232 additions and 221 deletions

View File

@ -1,5 +1,5 @@
const crypto = require('./crypto/crypto');
const BigInt = require('big-integer');
const crypto = require('./crypto/crypto');
/**
* converts a buffer to big int
@ -143,7 +143,7 @@ function generateRandomBytes(count) {
* @returns {{iv: Buffer, key: Buffer}}
*/
/*CONTEST
/* CONTEST
this is mtproto 1 (mostly used for secret chats)
async function calcKey(sharedKey, msgKey, client) {
const x = client === true ? 0 : 8
@ -335,7 +335,7 @@ module.exports = {
mod,
crc32,
generateRandomBytes,
//calcKey,
// calcKey,
generateKeyDataFromNonce,
sha1,
sha256,
@ -344,7 +344,7 @@ module.exports = {
getRandomInt,
sleep,
getByteArray,
//isArrayLike,
// isArrayLike,
toSignedLittleBuffer,
convertToLittle,

View File

@ -10,6 +10,7 @@ const {
generateRandomBytes,
} = require('./Helpers');
const crypto = require('./crypto/crypto');
const SIZE_FOR_HASH = 256;
/**
@ -94,7 +95,7 @@ function checkPrimeAndGood(primeBytes, g) {
}
}
throw new Error('Changing passwords unsupported');
//checkPrimeAndGoodCheck(readBigIntFromBuffer(primeBytes, false), g)
// checkPrimeAndGoodCheck(readBigIntFromBuffer(primeBytes, false), g)
}
/**
@ -138,9 +139,9 @@ function isGoodModExpFirst(modexp, prime) {
const minDiffBitsCount = 2048 - 64;
const maxModExpSize = 256;
return !(diff.lesser(BigInt(0)) || diff.bitLength() < minDiffBitsCount ||
modexp.bitLength() < minDiffBitsCount ||
Math.floor((modexp.bitLength() + 7) / 8) > maxModExpSize);
return !(diff.lesser(BigInt(0)) || diff.bitLength() < minDiffBitsCount
|| modexp.bitLength() < minDiffBitsCount
|| Math.floor((modexp.bitLength() + 7) / 8) > maxModExpSize);
}
function xor(a, b) {
@ -209,7 +210,7 @@ async function computeCheck(request, password) {
const pwHash = await computeHash(algo, password);
const p = readBigIntFromBuffer(algo.p, false);
const g = algo.g;
const { g } = algo;
const B = readBigIntFromBuffer(request.srp_B, false);
try {
checkPrimeAndGood(algo.p, g);
@ -271,7 +272,7 @@ async function computeCheck(request, password) {
return new constructors.InputCheckPasswordSRP({
srpId: request.srpId,
A: Buffer.from(aForHash),
M1: M1,
M1,
});
}
@ -280,4 +281,3 @@ module.exports = {
computeCheck,
computeDigest,
};

View File

@ -1,15 +1,15 @@
const { constructors } = require('./tl');
const USERNAME_RE = new RegExp('@|(?:https?:\\/\\/)?(?:www\\.)?' +
'(?:telegram\\.(?:me|dog)|t\\.me)\\/(@|joinchat\\/)?');
const USERNAME_RE = new RegExp('@|(?:https?:\\/\\/)?(?:www\\.)?'
+ '(?:telegram\\.(?:me|dog)|t\\.me)\\/(@|joinchat\\/)?');
const JPEG_HEADER = Buffer.from('ffd8ffe000104a46494600010100000100010000ffdb004300281c1e231e19282321232d2b28303c64413c37373c7b585d4964918099968f808c8aa0b4e6c3a0aadaad8a8cc8ffcbdaeef5ffffff9bc1fffffffaffe6fdfff8ffdb0043012b2d2d3c353c76414176f8a58ca5f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8ffc00011080000000003012200021101031101ffc4001f0000010501010101010100000000000000000102030405060708090a0bffc400b5100002010303020403050504040000017d01020300041105122131410613516107227114328191a1082342b1c11552d1f02433627282090a161718191a25262728292a3435363738393a434445464748494a535455565758595a636465666768696a737475767778797a838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae1e2e3e4e5e6e7e8e9eaf1f2f3f4f5f6f7f8f9faffc4001f0100030101010101010101010000000000000102030405060708090a0bffc400b51100020102040403040705040400010277000102031104052131061241510761711322328108144291a1b1c109233352f0156272d10a162434e125f11718191a262728292a35363738393a434445464748494a535455565758595a636465666768696a737475767778797a82838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae2e3e4e5e6e7e8e9eaf2f3f4f5f6f7f8f9faffda000c03010002110311003f00', 'hex');
const JPEG_FOOTER = Buffer.from('ffd9', 'hex');
const TG_JOIN_RE = new RegExp('tg:\\/\\/(join)\\?invite=');
const VALID_USERNAME_RE = new RegExp('^([a-z]((?!__)[\\w\\d]){3,30}[a-z\\d]|gif|vid|' +
'pic|bing|wiki|imdb|bold|vote|like|coub)$');
const VALID_USERNAME_RE = new RegExp('^([a-z]((?!__)[\\w\\d]){3,30}[a-z\\d]|gif|vid|'
+ 'pic|bing|wiki|imdb|bold|vote|like|coub)$');
function _raiseCastFail(entity, target) {
throw new Error(`Cannot cast ${entity.className} to any kind of ${target}`);
@ -60,8 +60,8 @@ function getInputPeer(entity, allowSelf = true, checkHash = true) {
throw new Error('User without accessHash or min info cannot be input');
}
}
if (entity instanceof constructors.Chat || entity instanceof constructors.ChatEmpty ||
entity instanceof constructors.ChatForbidden) {
if (entity instanceof constructors.Chat || entity instanceof constructors.ChatEmpty
|| entity instanceof constructors.ChatForbidden) {
return new constructors.InputPeerChat({ chatId: entity.id });
}
if (entity instanceof constructors.Channel) {
@ -125,7 +125,7 @@ function getInputPeer(entity, allowSelf = true, checkHash = true) {
* @param entity
* @returns {InputChannel|*}
*/
/*CONTEST
/* CONTEST
function getInputChannel(entity) {
if (entity.SUBCLASS_OF_ID === undefined) {
_raiseCastFail(entity, 'InputChannel')
@ -162,7 +162,7 @@ function getInputChannel(entity) {
* @param entity
*/
/*CONTEST
/* CONTEST
function getInputUser(entity) {
if (entity.SUBCLASS_OF_ID === undefined) {
_raiseCastFail(entity, 'InputUser')
@ -206,7 +206,7 @@ function getInputUser(entity) {
Similar to :meth:`get_input_peer`, but for dialogs
* @param dialog
*/
/*CONTEST
/* CONTEST
function getInputDialog(dialog) {
try {
if (dialog.SUBCLASS_OF_ID === 0xa21c9795) { // crc32(b'InputDialogPeer')
@ -229,7 +229,7 @@ function getInputDialog(dialog) {
}
*/
/*CONTEST
/* CONTEST
function getInputMessage(message) {
try {
@ -268,7 +268,7 @@ function strippedPhotoToJpg(stripped) {
return Buffer.concat([header, stripped.slice(3), JPEG_FOOTER]);
}
/*CONTEST
/* CONTEST
function getInputLocation(location) {
try {
if (!location.SUBCLASS_OF_ID) {
@ -342,7 +342,7 @@ function getAppropriatedPartSize(fileSize) {
throw new Error('File size too large');
}
/*CONTEST
/* CONTEST
function getPeer(peer) {
try {
if (typeof peer === 'number') {
@ -405,7 +405,7 @@ function getPeer(peer) {
* @param peer
* @param addMark
*/
/*CONTEST
/* CONTEST
function getPeerId(peer, addMark = true) {
// First we assert it's a Peer TLObject, or early return for integers
if (typeof peer == 'number') {
@ -453,7 +453,7 @@ function getPeerId(peer, addMark = true) {
* Given a marked ID, returns the original ID and its :tl:`Peer` type.
* @param markedId
*/
/*CONTEST
/* CONTEST
function resolveId(markedId) {
if (markedId >= 0) {
return [markedId, constructors.PeerUser]
@ -482,7 +482,7 @@ function resolveId(markedId) {
* @private
*/
/*CONTEST
/* CONTEST
function _getEntityPair(entityId, entities, cache, getInputPeer = getInputPeer) {
const entity = entities.get(entityId)
@ -505,7 +505,7 @@ function getMessageId(message) {
if (message === null || message === undefined) {
return null;
}
if (typeof message == 'number') {
if (typeof message === 'number') {
return message;
}
if (message.SUBCLASS_OF_ID === 0x790009e3) { // crc32(b'Message')
@ -535,7 +535,7 @@ function parsePhone(phone) {
* @param username {string}
*/
/*CONTEST
/* CONTEST
function parseUsername(username) {
username = username.trim()
@ -601,7 +601,7 @@ function getDisplayName(entity) {
* @returns {boolean}
*/
/*CONTEST
/* CONTEST
Duplicate ?
function isListLike(item) {
return (
@ -667,26 +667,26 @@ function getDC(dcId, cdn = false) {
if (DC.id === dcId && Boolean(DC.ipv6) === this._useIPV6 && Boolean(DC.cdn) === cdn) {
return DC
}
}*/
} */
}
module.exports = {
getMessageId,
//_getEntityPair,
//getInputMessage,
//getInputDialog,
//getInputUser,
//getInputChannel,
// _getEntityPair,
// getInputMessage,
// getInputDialog,
// getInputUser,
// getInputChannel,
getInputPeer,
//parsePhone,
//parseUsername,
//getPeer,
//getPeerId,
// parsePhone,
// parseUsername,
// getPeer,
// getPeerId,
getDisplayName,
//resolveId,
//isListLike,
// resolveId,
// isListLike,
getAppropriatedPartSize,
//getInputLocation,
// getInputLocation,
strippedPhotoToJpg,
getDC,
};

View File

@ -88,7 +88,7 @@ export async function updateTwoFaSettings(
try {
await client.invoke(new Api.account.UpdatePasswordSettings({
password: password,
password,
newSettings: new Api.account.PasswordInputSettings({
newAlgo: pwd.newAlgo,
newPasswordHash: newPassword ? await computeDigest(pwd.newAlgo, newPassword) : Buffer.alloc(0),

View File

@ -1,3 +1,4 @@
const os = require('os');
const Logger = require('../extensions/Logger');
const { sleep } = require('../Helpers');
const errors = require('../errors');
@ -6,7 +7,6 @@ const Helpers = require('../Helpers');
const { BinaryWriter } = require('../extensions');
const utils = require('../Utils');
const Session = require('../sessions/Abstract');
const os = require('os');
const { LAYER } = require('../tl/AllTLObjects');
const {
constructors,
@ -69,7 +69,7 @@ class TelegramClient {
this.apiHash = apiHash;
this._useIPV6 = args.useIPV6;
// this._entityCache = new Set()
if (typeof args.baseLogger == 'string') {
if (typeof args.baseLogger === 'string') {
this._log = new Logger();
} else {
this._log = args.baseLogger;
@ -294,7 +294,7 @@ class TelegramClient {
const sender = new MTProtoSender(this.session.getAuthKey(dcId),
{
logger: this._log,
dcId: dcId,
dcId,
retries: this._connectionRetries,
delay: this._retryDelay,
autoReconnect: this._autoReconnect,
@ -313,12 +313,11 @@ class TelegramClient {
));
if (this.session.dcId !== dcId) {
this._log.info(`Exporting authorization for data center ${dc.ipAddress}`);
const auth = await this.invoke(new requests.auth.ExportAuthorization({ dcId: dcId }));
const auth = await this.invoke(new requests.auth.ExportAuthorization({ dcId }));
const req = this._initWith(new requests.auth.ImportAuthorization({
id: auth.id,
bytes: auth.bytes,
},
));
id: auth.id,
bytes: auth.bytes,
}));
await sender.send(req);
}
sender.dcId = dcId;
@ -360,7 +359,7 @@ class TelegramClient {
date = new Date().getTime();
media = messageOrMedia;
}
if (typeof media == 'string') {
if (typeof media === 'string') {
throw new Error('not implemented');
}
@ -424,12 +423,12 @@ class TelegramClient {
}
try {
return this.downloadFile(loc, {
dcId: dcId,
dcId,
});
} catch (e) {
// TODO this should never raise
throw e;
/*if (e.message === 'LOCATION_INVALID') {
/* if (e.message === 'LOCATION_INVALID') {
const ie = await this.getInputEntity(entity)
if (ie instanceof constructors.InputPeerChannel) {
const full = await this.invoke(new requests.channels.GetFullChannel({
@ -441,7 +440,7 @@ class TelegramClient {
}
} else {
throw e
}*/
} */
}
}
@ -588,12 +587,12 @@ class TelegramClient {
try {
const promise = this._sender.send(request);
const result = await promise;
//this.session.processEntities(result)
// this.session.processEntities(result)
// this._entityCache.add(result)
return result;
} catch (e) {
if (e instanceof errors.ServerError || e.message === 'RPC_CALL_FAIL' ||
e.message === 'RPC_MCGET_FAIL') {
if (e instanceof errors.ServerError || e.message === 'RPC_CALL_FAIL'
|| e.message === 'RPC_MCGET_FAIL') {
this._log.warn(`Telegram is having internal issues ${e.constructor.name}`);
await sleep(2000);
} else if (e instanceof errors.FloodWaitError || e instanceof errors.FloodTestPhoneWaitError) {
@ -603,8 +602,8 @@ class TelegramClient {
} else {
throw e;
}
} else if (e instanceof errors.PhoneMigrateError || e instanceof errors.NetworkMigrateError ||
e instanceof errors.UserMigrateError) {
} else if (e instanceof errors.PhoneMigrateError || e instanceof errors.NetworkMigrateError
|| e instanceof errors.UserMigrateError) {
this._log.info(`Phone migrated to ${e.newDc}`);
const shouldRaise = e instanceof errors.PhoneMigrateError || e instanceof errors.NetworkMigrateError;
if (shouldRaise && await checkAuthorization(this)) {
@ -658,7 +657,7 @@ class TelegramClient {
}
_handleUpdate(update) {
//this.session.processEntities(update)
// this.session.processEntities(update)
// this._entityCache.add(update)
if (update instanceof constructors.Updates || update instanceof constructors.UpdatesCombined) {
@ -682,8 +681,8 @@ class TelegramClient {
_processUpdate(update, others, entities) {
update._entities = entities || [];
const args = {
update: update,
others: others,
update,
others,
};
this._dispatchUpdate(args);
}
@ -707,7 +706,7 @@ class TelegramClient {
* @returns {Promise<void>}
* @private
*/
/*CONTEST
/* CONTEST
async _getEntityFromString(string) {
const phone = utils.parsePhone(string)
if (phone) {
@ -838,7 +837,7 @@ class TelegramClient {
* @returns {Promise<>}
*/
/*CONTEST
/* CONTEST
async getInputEntity(peer) {
// Short-circuit if the input parameter directly maps to an InputPeer
try {

View File

@ -9,7 +9,7 @@ export interface UserAuthParams {
phoneCode: (isCodeViaApp?: boolean) => Promise<string>;
password: (hint?: string) => Promise<string>;
firstAndLastNames: () => Promise<[string, string?]>;
qrCode: (qrCode: { token: Buffer, expires: number }) => Promise<void>;
qrCode: (qrCode: { token: Buffer; expires: number }) => Promise<void>;
onError: (err: Error) => void;
forceSMS?: boolean;
}
@ -19,8 +19,8 @@ export interface BotAuthParams {
}
interface ApiCredentials {
apiId: number,
apiHash: string,
apiId: number;
apiHash: string;
}
const QR_CODE_TIMEOUT = 30000;
@ -247,9 +247,9 @@ async function signInUserWithQrCode(
async function sendCode(
client: TelegramClient, apiCredentials: ApiCredentials, phoneNumber: string, forceSMS = false,
): Promise<{
phoneCodeHash: string;
isCodeViaApp: boolean;
}> {
phoneCodeHash: string;
isCodeViaApp: boolean;
}> {
try {
const { apiId, apiHash } = apiCredentials;
const sendResult = await client.invoke(new Api.auth.SendCode({

View File

@ -39,7 +39,9 @@ export async function downloadFile(
inputLocation: Api.InputFileLocation,
fileParams: DownloadFileParams,
) {
let { partSizeKb, fileSize, workers = 1, end } = fileParams;
let {
partSizeKb, fileSize, workers = 1, end,
} = fileParams;
const { dcId, progressCallback, start = 0 } = fileParams;
end = end && end < fileSize ? end : fileSize - 1;
@ -151,6 +153,7 @@ export async function downloadFile(
class Foreman {
private deferred: Deferred | undefined;
private activeWorkers = 0;
constructor(private maxWorkers: number) {

View File

@ -52,7 +52,7 @@ export async function uploadFile(
}
for (let i = 0; i < partCount; i += workers) {
let sendingParts = [];
const sendingParts = [];
let end = i + workers;
if (end > partCount) {
end = partCount;
@ -86,7 +86,6 @@ export async function uploadFile(
onProgress(progress);
}
})());
}
try {
await Promise.race([

View File

@ -8,7 +8,6 @@ const BinaryReader = require('../extensions/BinaryReader');
const { sleep } = require('../Helpers');
class AuthKey {
constructor(value, hash) {
if (!hash || !value) {
return;

View File

@ -10,7 +10,7 @@ class Factorizator {
*/
static gcd(a, b) {
while (b.neq(BigInt.zero)) {
let temp = b;
const temp = b;
b = a.remainder(b);
a = temp;
}
@ -51,9 +51,8 @@ class Factorizator {
k = BigInt.zero;
while (k.lesser(r) && g.eq(BigInt.one)) {
ys = y;
let condition = BigInt.min(m, r.minus(k));
const condition = BigInt.min(m, r.minus(k));
for (let i = 0; BigInt(i)
.lesser(condition); i++) {
y = (modExp(y, BigInt(2), pq)).add(c)
@ -85,8 +84,8 @@ class Factorizator {
const p = g;
q = pq.divide(g);
return p < q ? {
p: p,
q: q,
p,
q,
} : {
p: q,
q: p,

View File

@ -1,6 +1,6 @@
const { IGE: aes_ige } = require('@cryptography/aes');
const Helpers = require('../Helpers');
const { IGE: aes_ige } = require('@cryptography/aes');
class IGENEW {
constructor(key, iv) {
@ -28,10 +28,7 @@ class IGENEW {
}
return Helpers.convertToLittle(this.ige.encrypt(plainText));
}
}
module.exports = IGENEW;

View File

@ -9,21 +9,21 @@ const {
} = require('../Helpers');
const PUBLIC_KEYS = [{
'fingerprint': [40, 85, 94, 156, 117, 240, 61, 22, 65, 244, 169, 2, 33, 107, 232, 108, 2, 43, 180, 195],
'n': BigInt('24403446649145068056824081744112065346446136066297307473868293895086332508101251964919587745984311372853053253457835208829824428441874946556659953519213382748319518214765985662663680818277989736779506318868003755216402538945900388706898101286548187286716959100102939636333452457308619454821845196109544157601096359148241435922125602449263164512290854366930013825808102403072317738266383237191313714482187326643144603633877219028262697593882410403273959074350849923041765639673335775605842311578109726403165298875058941765362622936097839775380070572921007586266115476975819175319995527916042178582540628652481530373407'),
'e': 65537,
fingerprint: [40, 85, 94, 156, 117, 240, 61, 22, 65, 244, 169, 2, 33, 107, 232, 108, 2, 43, 180, 195],
n: BigInt('24403446649145068056824081744112065346446136066297307473868293895086332508101251964919587745984311372853053253457835208829824428441874946556659953519213382748319518214765985662663680818277989736779506318868003755216402538945900388706898101286548187286716959100102939636333452457308619454821845196109544157601096359148241435922125602449263164512290854366930013825808102403072317738266383237191313714482187326643144603633877219028262697593882410403273959074350849923041765639673335775605842311578109726403165298875058941765362622936097839775380070572921007586266115476975819175319995527916042178582540628652481530373407'),
e: 65537,
}, {
'fingerprint': [140, 171, 9, 34, 146, 246, 166, 50, 10, 170, 229, 247, 155, 114, 28, 177, 29, 106, 153, 154],
'n': BigInt('25081407810410225030931722734886059247598515157516470397242545867550116598436968553551465554653745201634977779380884774534457386795922003815072071558370597290368737862981871277312823942822144802509055492512145589734772907225259038113414940384446493111736999668652848440655603157665903721517224934142301456312994547591626081517162758808439979745328030376796953660042629868902013177751703385501412640560275067171555763725421377065095231095517201241069856888933358280729674273422117201596511978645878544308102076746465468955910659145532699238576978901011112475698963666091510778777356966351191806495199073754705289253783'),
'e': 65537,
fingerprint: [140, 171, 9, 34, 146, 246, 166, 50, 10, 170, 229, 247, 155, 114, 28, 177, 29, 106, 153, 154],
n: BigInt('25081407810410225030931722734886059247598515157516470397242545867550116598436968553551465554653745201634977779380884774534457386795922003815072071558370597290368737862981871277312823942822144802509055492512145589734772907225259038113414940384446493111736999668652848440655603157665903721517224934142301456312994547591626081517162758808439979745328030376796953660042629868902013177751703385501412640560275067171555763725421377065095231095517201241069856888933358280729674273422117201596511978645878544308102076746465468955910659145532699238576978901011112475698963666091510778777356966351191806495199073754705289253783'),
e: 65537,
}, {
'fingerprint': [243, 218, 109, 239, 16, 202, 176, 78, 167, 8, 255, 209, 120, 234, 205, 112, 111, 42, 91, 176],
'n': BigInt('22347337644621997830323797217583448833849627595286505527328214795712874535417149457567295215523199212899872122674023936713124024124676488204889357563104452250187725437815819680799441376434162907889288526863223004380906766451781702435861040049293189979755757428366240570457372226323943522935844086838355728767565415115131238950994049041950699006558441163206523696546297006014416576123345545601004508537089192869558480948139679182328810531942418921113328804749485349441503927570568778905918696883174575510385552845625481490900659718413892216221539684717773483326240872061786759868040623935592404144262688161923519030977'),
'e': 65537,
fingerprint: [243, 218, 109, 239, 16, 202, 176, 78, 167, 8, 255, 209, 120, 234, 205, 112, 111, 42, 91, 176],
n: BigInt('22347337644621997830323797217583448833849627595286505527328214795712874535417149457567295215523199212899872122674023936713124024124676488204889357563104452250187725437815819680799441376434162907889288526863223004380906766451781702435861040049293189979755757428366240570457372226323943522935844086838355728767565415115131238950994049041950699006558441163206523696546297006014416576123345545601004508537089192869558480948139679182328810531942418921113328804749485349441503927570568778905918696883174575510385552845625481490900659718413892216221539684717773483326240872061786759868040623935592404144262688161923519030977'),
e: 65537,
}, {
'fingerprint': [128, 80, 214, 72, 77, 244, 98, 7, 201, 250, 37, 244, 227, 51, 96, 199, 182, 37, 224, 113],
'n': BigInt('24573455207957565047870011785254215390918912369814947541785386299516827003508659346069416840622922416779652050319196701077275060353178142796963682024347858398319926119639265555410256455471016400261630917813337515247954638555325280392998950756512879748873422896798579889820248358636937659872379948616822902110696986481638776226860777480684653756042166610633513404129518040549077551227082262066602286208338952016035637334787564972991208252928951876463555456715923743181359826124083963758009484867346318483872552977652588089928761806897223231500970500186019991032176060579816348322451864584743414550721639495547636008351'),
'e': 65537,
fingerprint: [128, 80, 214, 72, 77, 244, 98, 7, 201, 250, 37, 244, 227, 51, 96, 199, 182, 37, 224, 113],
n: BigInt('24573455207957565047870011785254215390918912369814947541785386299516827003508659346069416840622922416779652050319196701077275060353178142796963682024347858398319926119639265555410256455471016400261630917813337515247954638555325280392998950756512879748873422896798579889820248358636937659872379948616822902110696986481638776226860777480684653756042166610633513404129518040549077551227082262066602286208338952016035637334787564972991208252928951876463555456715923743181359826124083963758009484867346318483872552977652588089928761806897223231500970500186019991032176060579816348322451864584743414550721639495547636008351'),
e: 65537,
}];
const _serverKeys = {};

View File

@ -29,7 +29,6 @@ class Counter {
class CTR {
constructor(key, counter) {
if (!(counter instanceof Counter)) {
counter = new Counter(counter);
}
@ -91,8 +90,8 @@ class Hash {
}
update(data) {
//We shouldn't be needing new Uint8Array but it doesn't
//work without it
// We shouldn't be needing new Uint8Array but it doesn't
// work without it
this.data = new Uint8Array(data);
}

View File

@ -87,47 +87,47 @@ class CdnFileTamperedError extends SecurityError {
class BadMessageError extends Error {
static ErrorMessages = {
16:
'msg_id too low (most likely, client time is wrong it would be worthwhile to ' +
'synchronize it using msg_id notifications and re-send the original message ' +
'with the “correct” msg_id or wrap it in a container with a new msg_id if the ' +
'original message had waited too long on the client to be transmitted).',
'msg_id too low (most likely, client time is wrong it would be worthwhile to '
+ 'synchronize it using msg_id notifications and re-send the original message '
+ 'with the “correct” msg_id or wrap it in a container with a new msg_id if the '
+ 'original message had waited too long on the client to be transmitted).',
17:
'msg_id too high (similar to the previous case, the client time has to be ' +
'synchronized, and the message re-sent with the correct msg_id).',
'msg_id too high (similar to the previous case, the client time has to be '
+ 'synchronized, and the message re-sent with the correct msg_id).',
18:
'Incorrect two lower order msg_id bits (the server expects client message msg_id ' +
'to be divisible by 4).',
'Incorrect two lower order msg_id bits (the server expects client message msg_id '
+ 'to be divisible by 4).',
19: 'Container msg_id is the same as msg_id of a previously received message ' + '(this must never happen).',
20:
'Message too old, and it cannot be verified whether the server has received a ' +
'message with this msg_id or not.',
'Message too old, and it cannot be verified whether the server has received a '
+ 'message with this msg_id or not.',
32:
'msg_seqno too low (the server has already received a message with a lower ' +
'msg_id but with either a higher or an equal and odd seqno).',
'msg_seqno too low (the server has already received a message with a lower '
+ 'msg_id but with either a higher or an equal and odd seqno).',
33:
'msg_seqno too high (similarly, there is a message with a higher msg_id but with ' +
'either a lower or an equal and odd seqno).',
'msg_seqno too high (similarly, there is a message with a higher msg_id but with '
+ 'either a lower or an equal and odd seqno).',
34: 'An even msg_seqno expected (irrelevant message), but odd received.',
35: 'Odd msg_seqno expected (relevant message), but even received.',
48:
'Incorrect server salt (in this case, the bad_server_salt response is received with ' +
'the correct salt, and the message is to be re-sent with it).',
'Incorrect server salt (in this case, the bad_server_salt response is received with '
+ 'the correct salt, and the message is to be re-sent with it).',
64: 'Invalid container.',
};
constructor(request, code) {
let errorMessage = BadMessageError.ErrorMessages[code] ||
`Unknown error code (this should not happen): ${code}.`;
let errorMessage = BadMessageError.ErrorMessages[code]
|| `Unknown error code (this should not happen): ${code}.`;
errorMessage += ` Caused by ${request.className}`;
super(errorMessage);
this.message = errorMessage;

View File

@ -41,6 +41,7 @@ class InvalidDCError extends RPCError {
*/
class BadRequestError extends RPCError {
code = 400;
message = 'BAD_REQUEST';
}
@ -50,6 +51,7 @@ class BadRequestError extends RPCError {
*/
class UnauthorizedError extends RPCError {
code = 401;
message = 'UNAUTHORIZED';
}
@ -59,6 +61,7 @@ class UnauthorizedError extends RPCError {
*/
class ForbiddenError extends RPCError {
code = 403;
message = 'FORBIDDEN';
}
@ -67,6 +70,7 @@ class ForbiddenError extends RPCError {
*/
class NotFoundError extends RPCError {
code = 404;
message = 'NOT_FOUND';
}
@ -76,6 +80,7 @@ class NotFoundError extends RPCError {
*/
class AuthKeyError extends RPCError {
code = 406;
message = 'AUTH_KEY';
}
@ -87,6 +92,7 @@ class AuthKeyError extends RPCError {
*/
class FloodError extends RPCError {
code = 420;
message = 'FLOOD';
}
@ -97,6 +103,7 @@ class FloodError extends RPCError {
*/
class ServerError extends RPCError {
code = 500; // Also witnessed as -500
message = 'INTERNAL';
}
@ -106,6 +113,7 @@ class ServerError extends RPCError {
*/
class TimedOutError extends RPCError {
code = 503; // Only witnessed as -503
message = 'Timeout';
}

View File

@ -9,8 +9,8 @@ const {
class UserMigrateError extends InvalidDCError {
constructor(args) {
const newDc = Number(args.capture || 0);
super(`The user whose identity is being used to execute queries is associated with DC ${newDc}` + RPCError._fmtRequest(args.request));
this.message = `The user whose identity is being used to execute queries is associated with DC ${newDc}` + RPCError._fmtRequest(args.request);
super(`The user whose identity is being used to execute queries is associated with DC ${newDc}${RPCError._fmtRequest(args.request)}`);
this.message = `The user whose identity is being used to execute queries is associated with DC ${newDc}${RPCError._fmtRequest(args.request)}`;
this.newDc = newDc;
}
}
@ -19,8 +19,8 @@ class UserMigrateError extends InvalidDCError {
class PhoneMigrateError extends InvalidDCError {
constructor(args) {
const newDc = Number(args.capture || 0);
super(`The phone number a user is trying to use for authorization is associated with DC ${newDc}` + RPCError._fmtRequest(args.request));
this.message = `The phone number a user is trying to use for authorization is associated with DC ${newDc}` + RPCError._fmtRequest(args.request);
super(`The phone number a user is trying to use for authorization is associated with DC ${newDc}${RPCError._fmtRequest(args.request)}`);
this.message = `The phone number a user is trying to use for authorization is associated with DC ${newDc}${RPCError._fmtRequest(args.request)}`;
this.newDc = newDc;
}
}
@ -28,8 +28,8 @@ class PhoneMigrateError extends InvalidDCError {
class SlowModeWaitError extends FloodError {
constructor(args) {
const seconds = Number(args.capture || 0);
super(`A wait of ${seconds} seconds is required before sending another message in this chat` + RPCError._fmtRequest(args.request));
this.message = `A wait of ${seconds} seconds is required before sending another message in this chat` + RPCError._fmtRequest(args.request);
super(`A wait of ${seconds} seconds is required before sending another message in this chat${RPCError._fmtRequest(args.request)}`);
this.message = `A wait of ${seconds} seconds is required before sending another message in this chat${RPCError._fmtRequest(args.request)}`;
this.seconds = seconds;
}
}
@ -37,8 +37,8 @@ class SlowModeWaitError extends FloodError {
class FloodWaitError extends FloodError {
constructor(args) {
const seconds = Number(args.capture || 0);
super(`A wait of ${seconds} seconds is required` + RPCError._fmtRequest(args.request));
this.message = `A wait of ${seconds} seconds is required` + RPCError._fmtRequest(args.request);
super(`A wait of ${seconds} seconds is required${RPCError._fmtRequest(args.request)}`);
this.message = `A wait of ${seconds} seconds is required${RPCError._fmtRequest(args.request)}`;
this.seconds = seconds;
}
}
@ -46,8 +46,8 @@ class FloodWaitError extends FloodError {
class FloodTestPhoneWaitError extends FloodError {
constructor(args) {
const seconds = Number(args.capture || 0);
super(`A wait of ${seconds} seconds is required in the test servers` + RPCError._fmtRequest(args.request));
this.message = `A wait of ${seconds} seconds is required in the test servers` + RPCError._fmtRequest(args.request);
super(`A wait of ${seconds} seconds is required in the test servers${RPCError._fmtRequest(args.request)}`);
this.message = `A wait of ${seconds} seconds is required in the test servers${RPCError._fmtRequest(args.request)}`;
this.seconds = seconds;
}
}
@ -55,8 +55,8 @@ class FloodTestPhoneWaitError extends FloodError {
class FileMigrateError extends InvalidDCError {
constructor(args) {
const newDc = Number(args.capture || 0);
super(`The file to be accessed is currently stored in DC ${newDc}` + RPCError._fmtRequest(args.request));
this.message = `The file to be accessed is currently stored in DC ${newDc}` + RPCError._fmtRequest(args.request);
super(`The file to be accessed is currently stored in DC ${newDc}${RPCError._fmtRequest(args.request)}`);
this.message = `The file to be accessed is currently stored in DC ${newDc}${RPCError._fmtRequest(args.request)}`;
this.newDc = newDc;
}
}
@ -64,8 +64,8 @@ class FileMigrateError extends InvalidDCError {
class NetworkMigrateError extends InvalidDCError {
constructor(args) {
const newDc = Number(args.capture || 0);
super(`The source IP address is associated with DC ${newDc}` + RPCError._fmtRequest(args.request));
this.message = `The source IP address is associated with DC ${newDc}` + RPCError._fmtRequest(args.request);
super(`The source IP address is associated with DC ${newDc}${RPCError._fmtRequest(args.request)}`);
this.message = `The source IP address is associated with DC ${newDc}${RPCError._fmtRequest(args.request)}`;
this.newDc = newDc;
}
}
@ -73,8 +73,8 @@ class NetworkMigrateError extends InvalidDCError {
class EmailUnconfirmedError extends BadRequestError {
constructor(args) {
const codeLength = Number(args.capture || 0);
super(`Email unconfirmed, the length of the code must be ${codeLength}` + RPCError._fmtRequest(args.request));
this.message = `Email unconfirmed, the length of the code must be ${codeLength}` + RPCError._fmtRequest(args.request);
super(`Email unconfirmed, the length of the code must be ${codeLength}${RPCError._fmtRequest(args.request)}`);
this.message = `Email unconfirmed, the length of the code must be ${codeLength}${RPCError._fmtRequest(args.request)}`;
this.codeLength = codeLength;
}
}

View File

@ -13,8 +13,8 @@ function RPCMessageToError(rpcError, request) {
if (m) {
const capture = m.length === 2 ? parseInt(m[1]) : null;
return new Cls({
request: request,
capture: capture,
request,
capture,
});
}
}

View File

@ -1,4 +1,4 @@
/*CONTEST
/* CONTEST
const { EventBuilder, EventCommon } = require('./common')
const { constructors } = require('../tl')

View File

@ -1,10 +1,9 @@
class EventBuilder {
constructor(args = {
chats: null,
blacklistChats: null,
func: null,
},
) {
chats: null,
blacklistChats: null,
func: null,
}) {
this.chats = args.chats;
this.blacklistChats = Boolean(args.blacklistChats);
this.resolved = false;

View File

@ -8,10 +8,10 @@ class Logger {
_level = level || 'debug';
}
this.isBrowser = typeof process === 'undefined' ||
process.type === 'renderer' ||
process.browser === true ||
process.__nwjs;
this.isBrowser = typeof process === 'undefined'
|| process.type === 'renderer'
|| process.browser === true
|| process.__nwjs;
if (!this.isBrowser) {
this.colors = {
start: '\x1b[2m',

View File

@ -80,7 +80,6 @@ class MessagePacker {
this._log.warn(`Message payload for ${state.request.className || state.request.constructor.name} is too long ${state.data.length} and cannot be sent`);
state.reject('Request Payload is too big');
size = 0;
}
if (!batch.length) {
return null;

View File

@ -1,4 +1,5 @@
const Mutex = require('async-mutex').Mutex;
const { Mutex } = require('async-mutex');
const mutex = new Mutex();
const WebSocketClient = require('websocket').w3cwebsocket;
@ -7,7 +8,7 @@ const closeError = new Error('WebSocket was closed');
class PromisedWebSockets {
constructor() {
/*CONTEST
/* CONTEST
this.isBrowser = typeof process === 'undefined' ||
process.type === 'renderer' ||
process.browser === true ||
@ -23,7 +24,7 @@ class PromisedWebSockets {
while (true) {
const thisTime = await this.read(number);
readData = Buffer.concat([readData, thisTime]);
number = number - thisTime.length;
number -= thisTime.length;
if (!number) {
return readData;
}
@ -90,7 +91,7 @@ class PromisedWebSockets {
this.resolveRead(false);
this.closed = true;
};
//CONTEST
// CONTEST
// Seems to not be working, at least in a web worker
self.addEventListener('offline', async () => {
await this.close();

View File

@ -4,6 +4,7 @@ const BinaryReader = require('./BinaryReader');
const PromisedWebSockets = require('./PromisedWebSockets');
const MessagePacker = require('./MessagePacker');
const AsyncQueue = require('./AsyncQueue');
module.exports = {
BinaryWriter,
BinaryReader,

View File

@ -23,7 +23,7 @@ async function doAuthentication(sender, log) {
const nonce = Helpers.readBigIntFromBuffer(bytes, false, true);
const resPQ = await sender.send(new requests.ReqPqMulti({ nonce: nonce }));
const resPQ = await sender.send(new requests.ReqPqMulti({ nonce }));
log.debug('Starting authKey generation step 1');
if (!(resPQ instanceof constructors.ResPQ)) {
@ -50,11 +50,11 @@ async function doAuthentication(sender, log) {
const pqInnerData = new constructors.PQInnerData({
pq: Helpers.getByteArray(pq), // unsigned
p: p,
q: q,
p,
q,
nonce: resPQ.nonce,
serverNonce: resPQ.serverNonce,
newNonce: newNonce,
newNonce,
});
// sha_digest + data + random_bytes
@ -75,8 +75,8 @@ async function doAuthentication(sender, log) {
new requests.ReqDHParams({
nonce: resPQ.nonce,
serverNonce: resPQ.serverNonce,
p: p,
q: q,
p,
q,
publicKeyFingerprint: targetFingerprint,
encryptedData: cipherText,
}),

View File

@ -2,11 +2,11 @@
* This module contains the class used to communicate with Telegram's servers
* in plain text, when no authorization key has been created yet.
*/
const BigInt = require('big-integer');
const Helpers = require('../Helpers');
const MTProtoState = require('./MTProtoState');
const BinaryReader = require('../extensions/BinaryReader');
const { InvalidBufferError } = require('../errors/Common');
const BigInt = require('big-integer');
const { toSignedLittleBuffer } = require('../Helpers');
/**
@ -29,7 +29,6 @@ class MTProtoPlainSender {
* @param request
*/
async send(request) {
let body = request.getBytes();
let msgId = this._state._getNewMsgId();
const m = toSignedLittleBuffer(msgId, 8);
@ -69,7 +68,6 @@ class MTProtoPlainSender {
*/
return reader.tgReadObject();
}
}
module.exports = MTProtoPlainSender;

View File

@ -176,7 +176,7 @@ class MTProtoSender {
if (this._updateCallback && attempt === 0) {
this._updateCallback(new UpdateConnectionState(UpdateConnectionState.disconnected));
}
this._log.error('WebSocket connection failed attempt: ' + (attempt + 1));
this._log.error(`WebSocket connection failed attempt: ${attempt + 1}`);
await Helpers.sleep(this._delay);
}
}
@ -223,7 +223,7 @@ class MTProtoSender {
if (!this._user_connected) {
throw new Error('Cannot send requests while disconnected');
}
//CONTEST
// CONTEST
const state = new RequestState(request);
this._send_queue.append(state);
return state.promise;
@ -234,7 +234,7 @@ class MTProtoSender {
return state.promise
} else {
throw new Error('not supported')
}*/
} */
}
/**
@ -248,7 +248,7 @@ class MTProtoSender {
this._log.info('Connecting to {0}...'.replace('{0}', this._connection));
await this._connection.connect();
this._log.debug('Connection success!');
//process.exit(0)
// process.exit(0)
if (!this.authKey.getKey()) {
const plain = new MtProtoPlainSender(this._connection, this._log);
this._log.debug('New auth_key attempt ...');
@ -319,7 +319,7 @@ class MTProtoSender {
this._last_acks.push(ack);
this._pending_ack.clear();
}
this._log.debug('Waiting for messages to send...' + this._reconnecting);
this._log.debug(`Waiting for messages to send...${this._reconnecting}`);
// TODO Wait for the connection send queue to be empty?
// This means that while it's not empty we can wait for
// more messages to be added to the send queue.
@ -332,8 +332,8 @@ class MTProtoSender {
if (!res) {
continue;
}
let data = res.data;
const batch = res.batch;
let { data } = res;
const { batch } = res;
this._log.debug(`Encrypting ${batch.length} message(s) in ${data.length} bytes for sending`);
data = await this._state.encryptMessageData(data);
@ -399,11 +399,11 @@ class MTProtoSender {
}
// We don't really need to do this if we're going to sign in again
/*await this.authKey.setKey(null)
/* await this.authKey.setKey(null)
if (this._authKeyCallback) {
await this._authKeyCallback(null)
}*/
} */
// We can disconnect at sign in
/* await this.disconnect()
*/
@ -568,7 +568,7 @@ class MTProtoSender {
this._log.warn(`Note: ${message.obj.className} is not an update, not dispatching it`);
return;
}
this._log.debug('Handling update ' + message.obj.className);
this._log.debug(`Handling update ${message.obj.className}`);
if (this._updateCallback) {
this._updateCallback(message.obj);
}
@ -638,7 +638,6 @@ class MTProtoSender {
// msg_seqno too high never seems to happen but just in case
this._state._sequence -= 16;
} else {
for (const state of states) {
state.reject(new BadMessageError(state.request, badMsg.errorCode));
}
@ -793,7 +792,7 @@ class MTProtoSender {
this._reconnecting = false;
// uncomment this if you want to resend
//this._send_queue.extend(Object.values(this._pending_state))
// this._send_queue.extend(Object.values(this._pending_state))
this._pending_state = {};
if (this._autoReconnectCallback) {
await this._autoReconnectCallback();

View File

@ -27,7 +27,7 @@ class Connection {
this._obfuscation = null; // TcpObfuscated and MTProxy
this._sendArray = new AsyncQueue();
this._recvArray = new AsyncQueue();
//this.socket = new PromiseSocket(new Socket())
// this.socket = new PromiseSocket(new Socket())
this.socket = new PromisedWebSockets();
}
@ -101,7 +101,7 @@ class Connection {
}
} catch (e) {
this._log.info('connection closed');
//await this._recvArray.push()
// await this._recvArray.push()
this.disconnect();
return;

View File

@ -1,12 +1,13 @@
const BigInt = require('big-integer');
const { readBufferFromBigInt } = require('../../Helpers');
const {
Connection,
PacketCodec,
} = require('./Connection');
const BigInt = require('big-integer');
class AbridgedPacketCodec extends PacketCodec {
static tag = Buffer.from('ef', 'hex');
static obfuscateTag = Buffer.from('efefefef', 'hex');
constructor(props) {

View File

@ -1,4 +1,4 @@
//CONTEST
// CONTEST
// const { Connection, PacketCodec } = require('./Connection')
// const { crc32 } = require('../../Helpers')
// const { InvalidChecksumError } = require('../../errors/Common')

View File

@ -76,10 +76,10 @@ class ObfuscatedIO {
class ConnectionTCPObfuscated extends ObfuscatedConnection {
ObfuscatedIO = ObfuscatedIO;
PacketCodecClass = AbridgedPacketCodec;
}
module.exports = {
ConnectionTCPObfuscated,
};

View File

@ -4,7 +4,9 @@ const MTProtoSender = require('./MTProtoSender');
class UpdateConnectionState {
static disconnected = -1;
static connected = 1;
static broken = 0;
constructor(state) {
@ -18,6 +20,7 @@ const {
ConnectionTCPAbridged,
ConnectionTCPObfuscated,
} = require('./connection');
module.exports = {
Connection,
ConnectionTCPFull,

View File

@ -12,7 +12,7 @@ class Session {
/* CONTEST
clone(toInstance = null) {
return toInstance || new this.constructor()
}*/
} */
/**
* Returns the currently-used data center ID.
@ -67,7 +67,7 @@ class Session {
* Returns an ID of the takeout process initialized for this session,
* or `None` if there's no were any unfinished takeout requests.
*/
/*CONTEST
/* CONTEST
get takeoutId() {
throw new Error('Not Implemented')
}
@ -76,7 +76,7 @@ class Session {
* Sets the ID of the unfinished takeout process for this session.
* @param value
*/
/*CONTEST
/* CONTEST
set takeoutId(value) {
throw new Error('Not Implemented')
}
@ -88,7 +88,7 @@ class Session {
* it should ``return None``.
* @param entityId
*/
/*CONTEST
/* CONTEST
getUpdateState(entityId) {
throw new Error('Not Implemented')
}
@ -102,7 +102,7 @@ class Session {
* @param entityId
* @param state
*/
/*CONTEST
/* CONTEST
setUpdateState(entityId, state) {
throw new Error('Not Implemented')
}
@ -114,7 +114,7 @@ class Session {
* free any used resources. Can be left empty if none.
*/
/*CONTEST
/* CONTEST
close() {
}
@ -141,7 +141,7 @@ class Session {
/**
* Lists available sessions. Not used by the library itself.
*/
/*CONTEST
/* CONTEST
listSessions() {
throw new Error('Not Implemented')
}
@ -153,7 +153,7 @@ class Session {
* whatever information is relevant (e.g., ID or access hash).
* @param tlo
*/
/*CONTEST
/* CONTEST
processEntities(tlo) {
throw new Error('Not Implemented')
}
@ -166,7 +166,7 @@ class Session {
* to suit several purposes (e.g. user only provided its ID or wishes
* to use a cached username to avoid extra RPC).
*/
/*CONTEST
/* CONTEST
getInputEntity(key) {
throw new Error('Not Implemented')
}

View File

@ -1,5 +1,5 @@
const StorageSession = require('./StorageSession');
const idb = require('idb-keyval');
const StorageSession = require('./StorageSession');
const CACHE_NAME = 'GramJs';

View File

@ -251,7 +251,7 @@ class MemorySession extends Session {
} else {
throw new Error('Could not find input entity with key ' + key)
}
}*/
} */
}
module.exports = MemorySession;

View File

@ -1,6 +1,7 @@
const MemorySession = require('./Memory');
const AuthKey = require('../crypto/AuthKey');
const BinaryReader = require('../extensions/BinaryReader');
const CURRENT_VERSION = '1';

View File

@ -1,4 +1,5 @@
const api = require('./api');
const LAYER = 121;
const tlobjects = {};

View File

@ -31,7 +31,7 @@ class MTProtoRequest {
// These should be overrode
onSend() {
throw Error('Not overload ' + this.constructor.name);
throw Error(`Not overload ${this.constructor.name}`);
}
onResponse(buffer) {

View File

@ -11,7 +11,7 @@ const {
const tlContent = require('./apiTl.js');
const schemeContent = require('./schemaTl.js');
/*CONTEST
/* CONTEST
const NAMED_AUTO_CASTS = new Set([
'chatId,int'
])
@ -223,13 +223,19 @@ function createClasses(classesType, params) {
class VirtualClass {
static CONSTRUCTOR_ID = constructorId;
static SUBCLASS_OF_ID = subclassOfId;
static className = fullName;
static classType = classesType;
CONSTRUCTOR_ID = constructorId;
SUBCLASS_OF_ID = subclassOfId;
className = fullName;
classType = classesType;
constructor(args) {
@ -241,7 +247,6 @@ function createClasses(classesType, params) {
}
static fromReader(reader) {
const args = {};
for (const argName in argsConfig) {
@ -249,10 +254,10 @@ function createClasses(classesType, params) {
const arg = argsConfig[argName];
if (arg.isFlag) {
if (arg.type === 'true') {
args[argName] = Boolean(args['flags'] & 1 << arg.flagIndex);
args[argName] = Boolean(args.flags & 1 << arg.flagIndex);
continue;
}
if (args['flags'] & 1 << arg.flagIndex) {
if (args.flags & 1 << arg.flagIndex) {
args[argName] = getArgFromReader(reader, arg);
} else {
args[argName] = null;
@ -287,7 +292,7 @@ function createClasses(classesType, params) {
}
const l = Buffer.alloc(4);
l.writeInt32LE(this[arg].length, 0);
buffers.push(l, Buffer.concat(this[arg].map(x => argToBytes(x, argsConfig[arg].type))));
buffers.push(l, Buffer.concat(this[arg].map((x) => argToBytes(x, argsConfig[arg].type))));
} else if (argsConfig[arg].flagIndicator) {
if (!Object.values(argsConfig)
.some((f) => f.isFlag)) {
@ -319,7 +324,6 @@ function createClasses(classesType, params) {
}
}
}
}
return Buffer.concat(buffers);
}
@ -332,8 +336,8 @@ function createClasses(classesType, params) {
const m = result.match(/Vector<(int|long)>/);
if (m) {
reader.readInt();
let temp = [];
let len = reader.readInt();
const temp = [];
const len = reader.readInt();
if (m[1] === 'int') {
for (let i = 0; i < len; i++) {
temp.push(reader.readInt());
@ -349,7 +353,7 @@ function createClasses(classesType, params) {
}
}
/*CONTEST
/* CONTEST
async resolve(client, utils) {
if (classesType !== 'request') {
@ -379,7 +383,7 @@ function createClasses(classesType, params) {
}
}
}
}*/
} */
}
if (namespace) {
@ -387,7 +391,6 @@ function createClasses(classesType, params) {
classes[namespace] = {};
}
classes[namespace][name] = VirtualClass;
} else {
classes[name] = VirtualClass;
}

View File

@ -1,10 +1,11 @@
const { serializeBytes } = require('../index');
const { inflate } = require('pako/dist/pako_inflate');
const { serializeBytes } = require('../index');
//CONTEST const { deflate } = require('pako/dist/pako_deflate')
// CONTEST const { deflate } = require('pako/dist/pako_deflate')
class GZIPPacked {
static CONSTRUCTOR_ID = 0x3072cfa1;
static classType = 'constructor';
constructor(data) {
@ -26,7 +27,7 @@ class GZIPPacked {
static gzip(input) {
return Buffer.from(input);
// TODO this usually makes it faster for large requests
//return Buffer.from(deflate(input, { level: 9, gzip: true }))
// return Buffer.from(deflate(input, { level: 9, gzip: true }))
}
static ungzip(input) {

View File

@ -2,7 +2,9 @@ const TLMessage = require('./TLMessage');
class MessageContainer {
static CONSTRUCTOR_ID = 0x73f1f8dc;
static classType = 'constructor';
// Maximum size in bytes for the inner payload of the container.
// Telegram will close the connection if the payload is bigger.
// The overhead of the container itself is subtracted.
@ -19,7 +21,6 @@ class MessageContainer {
static MAXIMUM_LENGTH = 100;
constructor(messages) {
this.CONSTRUCTOR_ID = 0x73f1f8dc;
this.messages = messages;
this.classType = 'constructor';

View File

@ -3,6 +3,7 @@ const GZIPPacked = require('./GZIPPacked');
class RPCResult {
static CONSTRUCTOR_ID = 0xf35c6d01;
static classType = 'constructor';
constructor(reqMsgId, body, error) {

View File

@ -1,5 +1,6 @@
class TLMessage {
static SIZE_OVERHEAD = 12;
static classType = 'constructor';
constructor(msgId, seqNo, obj) {

View File

@ -2,6 +2,7 @@ const TLMessage = require('./TLMessage');
const RPCResult = require('./RPCResult');
const MessageContainer = require('./MessageContainer');
const GZIPPacked = require('./GZIPPacked');
const coreObjects = {
[RPCResult.CONSTRUCTOR_ID]: RPCResult,
[GZIPPacked.CONSTRUCTOR_ID]: GZIPPacked,

View File

@ -76,12 +76,11 @@ const fromLine = (line, isFunction) => {
argsConfig: {},
subclassOfId: crc32(match[3]),
result: match[3],
isFunction: isFunction,
isFunction,
namespace: null,
};
if (!currentConfig.constructorId) {
let hexId = '';
const hexId = '';
let args;
if (Object.values(currentConfig.argsConfig).length) {
@ -122,7 +121,7 @@ const fromLine = (line, isFunction) => {
delete currentConfig.argsConfig[arg]
}
}
}*/
} */
return currentConfig;
};
@ -143,7 +142,7 @@ function buildArgConfig(name, argType) {
// less annoying to type. Currently the only type that can
// be inferred is if the name is 'random_id', to which a
// random ID will be assigned if left as None (the default)
let canBeInferred = name === 'random_id';
const canBeInferred = name === 'random_id';
// The type can be an indicator that other arguments will be flags
if (argType !== '#') {
@ -186,8 +185,7 @@ function buildArgConfig(name, argType) {
// @ts-ignore
if (/^[a-z]$/.test(currentConfig.type.split('.')
.pop()
.charAt(0),
)
.charAt(0))
) {
currentConfig.skipConstructorId = true;
}
@ -270,7 +268,7 @@ const parseTl = function* (content, layer, methods = [], ignoreIds = CORE_TYPES)
// Once all objects have been parsed, replace the
// string type from the arguments with references
for (const obj of objAll) {
//console.log(obj)
// console.log(obj)
if (AUTH_KEY_TYPES.has(obj.constructorId)) {
for (const arg in obj.argsConfig) {
if (obj.argsConfig[arg].type === 'string') {
@ -283,12 +281,11 @@ const parseTl = function* (content, layer, methods = [], ignoreIds = CORE_TYPES)
for (const obj of objAll) {
yield obj;
}
};
const findAll = (regex, str, matches = []) => {
if (!regex.flags.includes(`g`)) {
regex = new RegExp(regex.source, `g`);
if (!regex.flags.includes('g')) {
regex = new RegExp(regex.source, 'g');
}
const res = regex.exec(str);
@ -303,7 +300,7 @@ const findAll = (regex, str, matches = []) => {
function serializeBytes(data) {
if (!(data instanceof Buffer)) {
if (typeof data == 'string') {
if (typeof data === 'string') {
data = Buffer.from(data);
} else {
throw Error(`Bytes or str expected, not ${data.constructor.name}`);
@ -330,7 +327,6 @@ function serializeBytes(data) {
.fill(0));
return Buffer.concat(r);
}
function serializeDate(dt) {
@ -341,7 +337,7 @@ function serializeDate(dt) {
if (dt instanceof Date) {
dt = Math.floor((Date.now() - dt.getTime()) / 1000);
}
if (typeof dt == 'number') {
if (typeof dt === 'number') {
const t = Buffer.alloc(4);
t.writeInt32LE(dt, 0);
return t;

View File

@ -3,6 +3,7 @@ const {
serializeBytes,
serializeDate,
} = require('./generationHelpers');
const patched = null;
module.exports = {

View File

@ -18,9 +18,9 @@ function main() {
const functions = [...apiConfig.functions, ...schemeConfig.functions];
const constructors = [...apiConfig.constructors, ...schemeConfig.constructors];
const generated = templateFn({
types: types,
functions: functions,
constructors: constructors,
types,
functions,
constructors,
});
fs.writeFileSync(OUTPUT_FILE, generated);
@ -37,7 +37,7 @@ function extractParams(fileContent) {
functions.push(def);
} else {
if (!types[def.result]) {
let [namespace, name] = def.result.includes('.') ? def.result.split('.') : [undefined, def.result];
const [namespace, name] = def.result.includes('.') ? def.result.split('.') : [undefined, def.result];
types[def.result] = {
namespace,