evogram-gramjs 1.0.3 → 1.1.1
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.
- package/.evogram/{7878190870 → 8539886557}/database.db +0 -0
- package/evogramjs.sqlite +0 -0
- package/lib/commands/AddAccount.command.d.ts +13 -0
- package/lib/commands/AddAccount.command.js +303 -12
- package/lib/commands/index.d.ts +2 -0
- package/lib/commands/index.js +4 -0
- package/lib/sessions/SessionAuth.d.ts +10 -0
- package/lib/sessions/SessionAuth.js +162 -0
- package/lib/test.d.ts +1 -0
- package/lib/test.js +144 -0
- package/package-lock.json +3938 -4
- package/package.json +4 -3
- package/qr-code-qr-auth-1769097743188.png +0 -0
- package/src/EvogramGramJS.ts +0 -98
- package/src/commands/Accounts.command.ts +0 -89
- package/src/commands/AddAccount.command.ts +0 -171
- package/src/commands/index.ts +0 -0
- package/src/commands/managment/DeleteAccount.command.ts +0 -13
- package/src/config/database.config.ts +0 -75
- package/src/entities/Session.entity.ts +0 -58
- package/src/entities/SessionEventLog.entity.ts +0 -41
- package/src/index.ts +0 -7
- package/src/services/DatabaseService.ts +0 -82
- package/src/services/ImageUploadService.ts +0 -49
- package/src/sessions/Session.ts +0 -21
- package/src/sessions/SessionAuth.ts +0 -173
- package/src/sessions/SessionLogger.ts +0 -208
- package/src/sessions/SessionManager.ts +0 -211
- package/src/types/auth.types.ts +0 -94
- package/src/types/session.types.ts +0 -96
- package/src/utils/Deferrer.ts +0 -12
|
Binary file
|
package/evogramjs.sqlite
ADDED
|
Binary file
|
|
@@ -1,6 +1,19 @@
|
|
|
1
1
|
import { Command, CommandContext, MessageContext } from 'evogram';
|
|
2
2
|
export declare class AddAccountCommand extends Command {
|
|
3
|
+
execute(context: CommandContext): Promise<void>;
|
|
4
|
+
}
|
|
5
|
+
export declare class AddAccountByCodeCommand extends Command {
|
|
3
6
|
execute(context: CommandContext, phone: string, code: string, password: string): Promise<void>;
|
|
4
7
|
handleMessage(context: CommandContext, message: MessageContext): Promise<void>;
|
|
5
8
|
onError(context: CommandContext, error: Error): void;
|
|
6
9
|
}
|
|
10
|
+
export declare class AddAccountByQRCodeCommand extends Command {
|
|
11
|
+
execute(context: CommandContext, qrcode: string, password: string): Promise<void>;
|
|
12
|
+
handleMessage(context: CommandContext, message: MessageContext): Promise<void>;
|
|
13
|
+
onError(context: CommandContext, error: Error): void;
|
|
14
|
+
}
|
|
15
|
+
export declare class AddAccountByStringSessionCommand extends Command {
|
|
16
|
+
execute(context: CommandContext, stringSession: string): Promise<void>;
|
|
17
|
+
handleMessage(context: CommandContext, message: MessageContext): Promise<void>;
|
|
18
|
+
onError(context: CommandContext, error: Error): void;
|
|
19
|
+
}
|
|
@@ -1,12 +1,40 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
var
|
|
2
|
+
var AddAccountByCodeCommand_1, AddAccountByQRCodeCommand_1, AddAccountByStringSessionCommand_1;
|
|
3
3
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
-
exports.AddAccountCommand = void 0;
|
|
4
|
+
exports.AddAccountByStringSessionCommand = exports.AddAccountByQRCodeCommand = exports.AddAccountByCodeCommand = exports.AddAccountCommand = void 0;
|
|
5
5
|
const tslib_1 = require("tslib");
|
|
6
6
|
const evogram_1 = require("evogram");
|
|
7
|
+
const QRCode = tslib_1.__importStar(require("qrcode"));
|
|
7
8
|
const EvogramGramJS_1 = require("../EvogramGramJS");
|
|
8
9
|
const auth_types_1 = require("../types/auth.types");
|
|
9
|
-
let AddAccountCommand =
|
|
10
|
+
let AddAccountCommand = class AddAccountCommand extends evogram_1.Command {
|
|
11
|
+
execute(context) {
|
|
12
|
+
return tslib_1.__awaiter(this, void 0, void 0, function* () {
|
|
13
|
+
var _a;
|
|
14
|
+
//@ts-ignore
|
|
15
|
+
(_a = context[context.callbackQuery ? 'edit' : 'send']) === null || _a === void 0 ? void 0 : _a.call(context, {
|
|
16
|
+
// prettier-ignore
|
|
17
|
+
text: '<blockquote><b>➕ Добавление аккаунта</b></blockquote>\n\n' +
|
|
18
|
+
'<i>Выберите метод добавления аккаунта</i>',
|
|
19
|
+
parse_mode: 'HTML',
|
|
20
|
+
reply_markup: {
|
|
21
|
+
inline_keyboard: [
|
|
22
|
+
[
|
|
23
|
+
{ text: 'SMS-код', command: AddAccountByCodeCommand },
|
|
24
|
+
{ text: 'QR-код', command: AddAccountByQRCodeCommand },
|
|
25
|
+
],
|
|
26
|
+
[{ text: 'StringSession', command: AddAccountByStringSessionCommand }],
|
|
27
|
+
],
|
|
28
|
+
},
|
|
29
|
+
});
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
exports.AddAccountCommand = AddAccountCommand;
|
|
34
|
+
exports.AddAccountCommand = AddAccountCommand = tslib_1.__decorate([
|
|
35
|
+
(0, evogram_1.CommandD)({ name: 'addaccount', argsMethod: 'parameterized' })
|
|
36
|
+
], AddAccountCommand);
|
|
37
|
+
let AddAccountByCodeCommand = AddAccountByCodeCommand_1 = class AddAccountByCodeCommand extends evogram_1.Command {
|
|
10
38
|
execute(context, phone, code, password) {
|
|
11
39
|
return tslib_1.__awaiter(this, void 0, void 0, function* () {
|
|
12
40
|
const session = EvogramGramJS_1.EvogramGramJS.sessionManager.getSession(yield context.storage.get('session'));
|
|
@@ -25,11 +53,11 @@ let AddAccountCommand = AddAccountCommand_1 = class AddAccountCommand extends ev
|
|
|
25
53
|
yield context.edit('⏳').catch(() => { });
|
|
26
54
|
yield message.delete().catch(() => { });
|
|
27
55
|
if (!(yield context.storage.get('phone')))
|
|
28
|
-
context.redirect(
|
|
56
|
+
context.redirect(AddAccountByCodeCommand_1, { phone: message.text });
|
|
29
57
|
else if ((yield context.storage.get('stage')) === 'code')
|
|
30
|
-
context.redirect(
|
|
58
|
+
context.redirect(AddAccountByCodeCommand_1, { code: message.text });
|
|
31
59
|
else if ((yield context.storage.get('stage')) === 'password')
|
|
32
|
-
context.redirect(
|
|
60
|
+
context.redirect(AddAccountByCodeCommand_1, { password: message.text });
|
|
33
61
|
});
|
|
34
62
|
}
|
|
35
63
|
onError(context, error) {
|
|
@@ -43,11 +71,12 @@ let AddAccountCommand = AddAccountCommand_1 = class AddAccountCommand extends ev
|
|
|
43
71
|
});
|
|
44
72
|
}
|
|
45
73
|
};
|
|
46
|
-
exports.
|
|
74
|
+
exports.AddAccountByCodeCommand = AddAccountByCodeCommand;
|
|
47
75
|
tslib_1.__decorate([
|
|
48
76
|
tslib_1.__param(1, (0, evogram_1.CommandStorageArgument)('phone', (_a) => tslib_1.__awaiter(void 0, [_a], void 0, function* ({ context, value }) {
|
|
49
77
|
var _b, _c;
|
|
50
78
|
if (value) {
|
|
79
|
+
console.log({ value });
|
|
51
80
|
if (!(yield context.storage.get('session'))) {
|
|
52
81
|
const session = yield EvogramGramJS_1.EvogramGramJS.sessionManager.addSession({
|
|
53
82
|
sessionId: value,
|
|
@@ -158,13 +187,275 @@ tslib_1.__decorate([
|
|
|
158
187
|
tslib_1.__metadata("design:type", Function),
|
|
159
188
|
tslib_1.__metadata("design:paramtypes", [evogram_1.CommandContext, String, String, String]),
|
|
160
189
|
tslib_1.__metadata("design:returntype", Promise)
|
|
161
|
-
],
|
|
190
|
+
], AddAccountByCodeCommand.prototype, "execute", null);
|
|
162
191
|
tslib_1.__decorate([
|
|
163
192
|
(0, evogram_1.CommandUpdate)('message'),
|
|
164
193
|
tslib_1.__metadata("design:type", Function),
|
|
165
194
|
tslib_1.__metadata("design:paramtypes", [evogram_1.CommandContext, evogram_1.MessageContext]),
|
|
166
195
|
tslib_1.__metadata("design:returntype", Promise)
|
|
167
|
-
],
|
|
168
|
-
exports.
|
|
169
|
-
(0, evogram_1.CommandD)({ name: '
|
|
170
|
-
],
|
|
196
|
+
], AddAccountByCodeCommand.prototype, "handleMessage", null);
|
|
197
|
+
exports.AddAccountByCodeCommand = AddAccountByCodeCommand = AddAccountByCodeCommand_1 = tslib_1.__decorate([
|
|
198
|
+
(0, evogram_1.CommandD)({ name: 'addaccountbycode', argsMethod: 'parameterized' })
|
|
199
|
+
], AddAccountByCodeCommand);
|
|
200
|
+
let AddAccountByQRCodeCommand = AddAccountByQRCodeCommand_1 = class AddAccountByQRCodeCommand extends evogram_1.Command {
|
|
201
|
+
execute(context, qrcode, password) {
|
|
202
|
+
return tslib_1.__awaiter(this, void 0, void 0, function* () {
|
|
203
|
+
const session = EvogramGramJS_1.EvogramGramJS.sessionManager.getSession(yield context.storage.get('session'));
|
|
204
|
+
const user = yield session.client.getMe();
|
|
205
|
+
context.send(`✅ Вы успешно добавили аккаунт @${user.username || user.firstName || 'unknown'}`);
|
|
206
|
+
yield context.storage.clearAll();
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
handleMessage(context, message) {
|
|
210
|
+
return tslib_1.__awaiter(this, void 0, void 0, function* () {
|
|
211
|
+
if (!(message === null || message === void 0 ? void 0 : message.text))
|
|
212
|
+
return;
|
|
213
|
+
yield context.edit('⏳').catch(() => { });
|
|
214
|
+
yield message.delete().catch(() => { });
|
|
215
|
+
if ((yield context.storage.get('stage')) === 'password')
|
|
216
|
+
context.redirect(AddAccountByQRCodeCommand_1, { password: message.text });
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
onError(context, error) {
|
|
220
|
+
var _a;
|
|
221
|
+
//@ts-ignore
|
|
222
|
+
(_a = context[context.callbackQuery ? 'edit' : 'send']) === null || _a === void 0 ? void 0 : _a.call(context, {
|
|
223
|
+
text: '<blockquote><b>❗️Произошла ошибка при добавлении аккаунта</b></blockquote>\n\n' + error.message,
|
|
224
|
+
parse_mode: 'HTML',
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
};
|
|
228
|
+
exports.AddAccountByQRCodeCommand = AddAccountByQRCodeCommand;
|
|
229
|
+
tslib_1.__decorate([
|
|
230
|
+
tslib_1.__param(1, (0, evogram_1.CommandStorageArgument)('qrcode', (_a) => tslib_1.__awaiter(void 0, [_a], void 0, function* ({ context, value }) {
|
|
231
|
+
var _b, _c;
|
|
232
|
+
try {
|
|
233
|
+
if (value)
|
|
234
|
+
return value;
|
|
235
|
+
let qrcodeMsg = null;
|
|
236
|
+
const session = (yield context.storage.get('session'))
|
|
237
|
+
? EvogramGramJS_1.EvogramGramJS.sessionManager.getSession(yield context.storage.get('session'))
|
|
238
|
+
: yield EvogramGramJS_1.EvogramGramJS.sessionManager.addSession({
|
|
239
|
+
sessionId: `qr-auth-${Date.now()}`,
|
|
240
|
+
logging: {
|
|
241
|
+
enabled: true,
|
|
242
|
+
logsDirectory: './logs',
|
|
243
|
+
},
|
|
244
|
+
});
|
|
245
|
+
if (![auth_types_1.AuthState.INITIAL, auth_types_1.AuthState.WAITING_CODE, undefined].includes((_b = session.auth.state) === null || _b === void 0 ? void 0 : _b.stage))
|
|
246
|
+
return true;
|
|
247
|
+
yield context.storage.set('session', session.sessionId);
|
|
248
|
+
//@ts-ignore
|
|
249
|
+
yield ((_c = context[context.callbackQuery ? 'edit' : 'send']) === null || _c === void 0 ? void 0 : _c.call(context, {
|
|
250
|
+
text: '<blockquote><b>➕ Добавление аккаунта через QR-код</b></blockquote>\n\n' + '<i>Генерируем QR-код для входа...</i>\n\n',
|
|
251
|
+
parse_mode: 'HTML',
|
|
252
|
+
}).catch(() => { }));
|
|
253
|
+
// Запускаем авторизацию через QR код
|
|
254
|
+
session.auth.startWithQRCode((qrUrl, qrToken, expires) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
|
|
255
|
+
try {
|
|
256
|
+
// Генерируем QR код как изображение
|
|
257
|
+
const qrCodeBuffer = yield QRCode.toBuffer(qrUrl, {
|
|
258
|
+
type: 'png',
|
|
259
|
+
width: 500,
|
|
260
|
+
margin: 2,
|
|
261
|
+
color: {
|
|
262
|
+
dark: '#000000',
|
|
263
|
+
light: '#FFFFFF',
|
|
264
|
+
},
|
|
265
|
+
});
|
|
266
|
+
const expiresDate = new Date(Date.now() + expires * 1000);
|
|
267
|
+
// prettier-ignore
|
|
268
|
+
const caption = `<blockquote><b>📱 QR-код для входа</b></blockquote>\n\n` +
|
|
269
|
+
'<i>Отсканируйте QR-код в приложении Telegram:</i>\n' +
|
|
270
|
+
'<b>Настройки → Устройства → Подключить устройство</b>\n\n' +
|
|
271
|
+
`⏳ QR-код действителен до: <code>${expiresDate.toLocaleString('ru-RU')}</code>`;
|
|
272
|
+
if (context.source.text) {
|
|
273
|
+
qrcodeMsg = yield context.sendPhoto(qrCodeBuffer, { caption, parse_mode: 'HTML' });
|
|
274
|
+
}
|
|
275
|
+
else {
|
|
276
|
+
yield context.client.api.editMessageMedia({
|
|
277
|
+
chat_id: context.chat.id,
|
|
278
|
+
message_id: context.message.id,
|
|
279
|
+
media: {
|
|
280
|
+
type: 'photo',
|
|
281
|
+
media: qrCodeBuffer,
|
|
282
|
+
caption,
|
|
283
|
+
parse_mode: 'HTML',
|
|
284
|
+
},
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
catch (error) {
|
|
289
|
+
console.error('Ошибка при генерации QR-кода:', error);
|
|
290
|
+
throw error;
|
|
291
|
+
}
|
|
292
|
+
}));
|
|
293
|
+
return new Promise((resolve) => {
|
|
294
|
+
const interval = setInterval(() => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
|
|
295
|
+
var _a;
|
|
296
|
+
if (((_a = session.auth.state) === null || _a === void 0 ? void 0 : _a.stage) !== auth_types_1.AuthState.WAITING_CODE) {
|
|
297
|
+
if (qrcodeMsg)
|
|
298
|
+
yield qrcodeMsg.delete().catch(() => { });
|
|
299
|
+
clearInterval(interval);
|
|
300
|
+
resolve(true);
|
|
301
|
+
}
|
|
302
|
+
}), 1000);
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
catch (error) {
|
|
306
|
+
console.error(error);
|
|
307
|
+
}
|
|
308
|
+
}))),
|
|
309
|
+
tslib_1.__param(2, (0, evogram_1.CommandStorageArgument)('password', (_a) => tslib_1.__awaiter(void 0, [_a], void 0, function* ({ context, value }) {
|
|
310
|
+
var _b, _c;
|
|
311
|
+
const session = EvogramGramJS_1.EvogramGramJS.sessionManager.getSession(yield context.storage.get('session'));
|
|
312
|
+
const isRequired = yield session.auth.isRequiredPassword();
|
|
313
|
+
if (!isRequired || value === 'none')
|
|
314
|
+
return 'none';
|
|
315
|
+
if (value) {
|
|
316
|
+
const result = yield session.auth.setPassword(value);
|
|
317
|
+
if (result.success) {
|
|
318
|
+
return value;
|
|
319
|
+
}
|
|
320
|
+
else {
|
|
321
|
+
//@ts-ignore
|
|
322
|
+
(_b = context[context.callbackQuery ? 'edit' : 'send']) === null || _b === void 0 ? void 0 : _b.call(context, {
|
|
323
|
+
text: '<blockquote><b>➕ Добавление аккаунта через QR-код</b></blockquote>\n\n' + '<i>На аккаунте включен 2FA. Отправьте пароль для 2FA в следующем сообщении</i>\n\n' + `<blockquote><b>❗️Произошла ошибка</b></blockquote>\n\n` + result.error,
|
|
324
|
+
parse_mode: 'HTML',
|
|
325
|
+
});
|
|
326
|
+
return null;
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
else {
|
|
330
|
+
yield context.storage.set('stage', 'password');
|
|
331
|
+
//@ts-ignore
|
|
332
|
+
(_c = context[context.callbackQuery ? 'edit' : 'send']) === null || _c === void 0 ? void 0 : _c.call(context, {
|
|
333
|
+
text: '<blockquote><b>➕ Добавление аккаунта через QR-код</b></blockquote>\n\n' + '<i>На аккаунте включен 2FA. Отправьте пароль для 2FA в следующем сообщении</i>',
|
|
334
|
+
parse_mode: 'HTML',
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
}))),
|
|
338
|
+
tslib_1.__metadata("design:type", Function),
|
|
339
|
+
tslib_1.__metadata("design:paramtypes", [evogram_1.CommandContext, String, String]),
|
|
340
|
+
tslib_1.__metadata("design:returntype", Promise)
|
|
341
|
+
], AddAccountByQRCodeCommand.prototype, "execute", null);
|
|
342
|
+
tslib_1.__decorate([
|
|
343
|
+
(0, evogram_1.CommandUpdate)('message'),
|
|
344
|
+
tslib_1.__metadata("design:type", Function),
|
|
345
|
+
tslib_1.__metadata("design:paramtypes", [evogram_1.CommandContext, evogram_1.MessageContext]),
|
|
346
|
+
tslib_1.__metadata("design:returntype", Promise)
|
|
347
|
+
], AddAccountByQRCodeCommand.prototype, "handleMessage", null);
|
|
348
|
+
exports.AddAccountByQRCodeCommand = AddAccountByQRCodeCommand = AddAccountByQRCodeCommand_1 = tslib_1.__decorate([
|
|
349
|
+
(0, evogram_1.CommandD)({ name: 'addaccountbyqrcode', argsMethod: 'parameterized' })
|
|
350
|
+
], AddAccountByQRCodeCommand);
|
|
351
|
+
let AddAccountByStringSessionCommand = AddAccountByStringSessionCommand_1 = class AddAccountByStringSessionCommand extends evogram_1.Command {
|
|
352
|
+
execute(context, stringSession) {
|
|
353
|
+
return tslib_1.__awaiter(this, void 0, void 0, function* () {
|
|
354
|
+
const session = EvogramGramJS_1.EvogramGramJS.sessionManager.getSession(yield context.storage.get('session'));
|
|
355
|
+
const user = yield session.client.getMe();
|
|
356
|
+
context.send(`✅ Вы успешно добавили аккаунт @${user.username || user.firstName || 'unknown'}`);
|
|
357
|
+
yield context.storage.clearAll();
|
|
358
|
+
});
|
|
359
|
+
}
|
|
360
|
+
handleMessage(context, message) {
|
|
361
|
+
return tslib_1.__awaiter(this, void 0, void 0, function* () {
|
|
362
|
+
if (!(message === null || message === void 0 ? void 0 : message.text))
|
|
363
|
+
return;
|
|
364
|
+
yield context.edit('⏳').catch(() => { });
|
|
365
|
+
yield message.delete().catch(() => { });
|
|
366
|
+
if (!(yield context.storage.get('stringSession'))) {
|
|
367
|
+
context.redirect(AddAccountByStringSessionCommand_1, { stringSession: message.text });
|
|
368
|
+
}
|
|
369
|
+
});
|
|
370
|
+
}
|
|
371
|
+
onError(context, error) {
|
|
372
|
+
var _a;
|
|
373
|
+
//@ts-ignore
|
|
374
|
+
(_a = context[context.callbackQuery ? 'edit' : 'send']) === null || _a === void 0 ? void 0 : _a.call(context, {
|
|
375
|
+
text: '<blockquote><b>❗️Произошла ошибка при добавлении аккаунта</b></blockquote>\n\n' + error.message,
|
|
376
|
+
parse_mode: 'HTML',
|
|
377
|
+
});
|
|
378
|
+
}
|
|
379
|
+
};
|
|
380
|
+
exports.AddAccountByStringSessionCommand = AddAccountByStringSessionCommand;
|
|
381
|
+
tslib_1.__decorate([
|
|
382
|
+
tslib_1.__param(1, (0, evogram_1.CommandStorageArgument)('stringSession', (_a) => tslib_1.__awaiter(void 0, [_a], void 0, function* ({ context, value }) {
|
|
383
|
+
var _b, _c;
|
|
384
|
+
if (value) {
|
|
385
|
+
try {
|
|
386
|
+
// Создаем уникальный ID для сессии
|
|
387
|
+
const sessionId = `string-session-${Date.now()}`;
|
|
388
|
+
// Добавляем сессию через SessionManager с переданной строкой
|
|
389
|
+
const session = yield EvogramGramJS_1.EvogramGramJS.sessionManager.addSession({
|
|
390
|
+
sessionId: sessionId,
|
|
391
|
+
sessionString: value,
|
|
392
|
+
logging: {
|
|
393
|
+
enabled: true,
|
|
394
|
+
logsDirectory: './logs',
|
|
395
|
+
},
|
|
396
|
+
});
|
|
397
|
+
yield context.storage.set('session', session.sessionId);
|
|
398
|
+
// Проверяем, что сессия валидна и авторизована
|
|
399
|
+
const user = yield session.client.getMe();
|
|
400
|
+
if (!user) {
|
|
401
|
+
throw new Error('Не удалось получить данные пользователя. Проверьте StringSession.');
|
|
402
|
+
}
|
|
403
|
+
// Сохраняем сессию в базу данных
|
|
404
|
+
try {
|
|
405
|
+
let avatarBuffer = yield session.client.downloadProfilePhoto('me');
|
|
406
|
+
let avatarUrl;
|
|
407
|
+
if (avatarBuffer) {
|
|
408
|
+
const ImageUploadService = (yield Promise.resolve().then(() => tslib_1.__importStar(require('../services/ImageUploadService')))).ImageUploadService;
|
|
409
|
+
avatarUrl = yield ImageUploadService.uploadToImgbox(Buffer.isBuffer(avatarBuffer) ? avatarBuffer : Buffer.from(avatarBuffer)).catch(() => undefined);
|
|
410
|
+
}
|
|
411
|
+
yield EvogramGramJS_1.EvogramGramJS.databaseService.saveSession({
|
|
412
|
+
sessionId: session.sessionId,
|
|
413
|
+
apiId: session.client.apiId,
|
|
414
|
+
apiHash: session.client.apiHash,
|
|
415
|
+
userId: Number(user.id),
|
|
416
|
+
username: user.username,
|
|
417
|
+
firstName: user.firstName,
|
|
418
|
+
lastName: user.lastName,
|
|
419
|
+
phoneNumber: user.phone,
|
|
420
|
+
sessionString: value,
|
|
421
|
+
avatarUrl,
|
|
422
|
+
});
|
|
423
|
+
}
|
|
424
|
+
catch (saveError) {
|
|
425
|
+
console.error('Ошибка при сохранении сессии в БД:', saveError);
|
|
426
|
+
// Продолжаем выполнение, даже если не удалось сохранить аватар
|
|
427
|
+
}
|
|
428
|
+
return value;
|
|
429
|
+
}
|
|
430
|
+
catch (error) {
|
|
431
|
+
context.state.command = undefined;
|
|
432
|
+
yield context.storage.clearAll();
|
|
433
|
+
//@ts-ignore
|
|
434
|
+
(_b = context[context.callbackQuery ? 'edit' : 'send']) === null || _b === void 0 ? void 0 : _b.call(context, {
|
|
435
|
+
text: '<blockquote><b>❗️Произошла ошибка при добавлении аккаунта</b></blockquote>\n\n' + '<i>Проверьте корректность StringSession. Убедитесь, что строка сессии действительна.</i>\n\n' + `<code>${error.message}</code>`,
|
|
436
|
+
parse_mode: 'HTML',
|
|
437
|
+
});
|
|
438
|
+
return null;
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
else {
|
|
442
|
+
//@ts-ignore
|
|
443
|
+
(_c = context[context.callbackQuery ? 'edit' : 'send']) === null || _c === void 0 ? void 0 : _c.call(context, {
|
|
444
|
+
text: '<blockquote><b>➕ Добавление аккаунта через StringSession</b></blockquote>\n\n' + '<i>Отправьте StringSession в следующем сообщении</i>\n\n' + 'ℹ️ StringSession - это строка, которая содержит данные авторизации вашего аккаунта. ' + 'Вы можете получить её через официальную библиотеку Telegram или сторонние инструменты.',
|
|
445
|
+
parse_mode: 'HTML',
|
|
446
|
+
});
|
|
447
|
+
}
|
|
448
|
+
}))),
|
|
449
|
+
tslib_1.__metadata("design:type", Function),
|
|
450
|
+
tslib_1.__metadata("design:paramtypes", [evogram_1.CommandContext, String]),
|
|
451
|
+
tslib_1.__metadata("design:returntype", Promise)
|
|
452
|
+
], AddAccountByStringSessionCommand.prototype, "execute", null);
|
|
453
|
+
tslib_1.__decorate([
|
|
454
|
+
(0, evogram_1.CommandUpdate)('message'),
|
|
455
|
+
tslib_1.__metadata("design:type", Function),
|
|
456
|
+
tslib_1.__metadata("design:paramtypes", [evogram_1.CommandContext, evogram_1.MessageContext]),
|
|
457
|
+
tslib_1.__metadata("design:returntype", Promise)
|
|
458
|
+
], AddAccountByStringSessionCommand.prototype, "handleMessage", null);
|
|
459
|
+
exports.AddAccountByStringSessionCommand = AddAccountByStringSessionCommand = AddAccountByStringSessionCommand_1 = tslib_1.__decorate([
|
|
460
|
+
(0, evogram_1.CommandD)({ name: 'addaccountbystringsession', argsMethod: 'parameterized' })
|
|
461
|
+
], AddAccountByStringSessionCommand);
|
package/lib/commands/index.d.ts
CHANGED
package/lib/commands/index.js
CHANGED
|
@@ -53,6 +53,16 @@ export declare class SessionAuth extends EventEmitter {
|
|
|
53
53
|
success: boolean;
|
|
54
54
|
error: Error;
|
|
55
55
|
}>;
|
|
56
|
+
/**
|
|
57
|
+
* Начинает авторизацию через QR-код
|
|
58
|
+
*
|
|
59
|
+
* @param onQRCode Callback для обработки QR-кода (получает URL и токен)
|
|
60
|
+
* @returns Promise с результатом авторизации
|
|
61
|
+
*/
|
|
62
|
+
startWithQRCode(onQRCode: (qrUrl: string, qrToken: string, expires: number) => Promise<void>): Promise<{
|
|
63
|
+
success: boolean;
|
|
64
|
+
error?: any;
|
|
65
|
+
}>;
|
|
56
66
|
/**
|
|
57
67
|
* Проверяет, требуется ли пароль для авторизации
|
|
58
68
|
*
|
|
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.SessionAuth = exports.SessionAuthEvent = void 0;
|
|
4
4
|
const tslib_1 = require("tslib");
|
|
5
5
|
const events_1 = require("events");
|
|
6
|
+
const telegram_1 = require("telegram");
|
|
6
7
|
const EvogramGramJS_1 = require("../EvogramGramJS");
|
|
7
8
|
const ImageUploadService_1 = require("../services/ImageUploadService");
|
|
8
9
|
const auth_types_1 = require("../types/auth.types");
|
|
@@ -147,6 +148,167 @@ class SessionAuth extends events_1.EventEmitter {
|
|
|
147
148
|
};
|
|
148
149
|
});
|
|
149
150
|
}
|
|
151
|
+
/**
|
|
152
|
+
* Начинает авторизацию через QR-код
|
|
153
|
+
*
|
|
154
|
+
* @param onQRCode Callback для обработки QR-кода (получает URL и токен)
|
|
155
|
+
* @returns Promise с результатом авторизации
|
|
156
|
+
*/
|
|
157
|
+
startWithQRCode(onQRCode) {
|
|
158
|
+
return tslib_1.__awaiter(this, void 0, void 0, function* () {
|
|
159
|
+
var _a, _b, _c, _d;
|
|
160
|
+
console.log(`[QR-AUTH] Начало метода startWithQRCode для сессии "${this.sessionId}"`);
|
|
161
|
+
console.log(`[QR-AUTH] Текущее состояние state:`, this.state ? 'уже инициализировано' : 'null');
|
|
162
|
+
if (this.state)
|
|
163
|
+
throw new Error(`Авторизация для сессии "${this.sessionId}" уже начата`);
|
|
164
|
+
console.log(`[QR-AUTH] Инициализация state для сессии "${this.sessionId}"`);
|
|
165
|
+
this.state = {
|
|
166
|
+
code: new Deferrer_1.Deferred(),
|
|
167
|
+
password: new Deferrer_1.Deferred(),
|
|
168
|
+
isRequiredPassword: false,
|
|
169
|
+
stage: auth_types_1.AuthState.INITIAL,
|
|
170
|
+
connect: new Deferrer_1.Deferred(),
|
|
171
|
+
};
|
|
172
|
+
console.log(`[QR-AUTH] State успешно инициализирован:`, {
|
|
173
|
+
stage: this.state.stage,
|
|
174
|
+
isRequiredPassword: this.state.isRequiredPassword,
|
|
175
|
+
});
|
|
176
|
+
try {
|
|
177
|
+
console.log(`[QR-AUTH] Получение API credentials для клиента`);
|
|
178
|
+
const apiCredentials = {
|
|
179
|
+
apiId: this.client.apiId,
|
|
180
|
+
apiHash: this.client.apiHash,
|
|
181
|
+
};
|
|
182
|
+
console.log(`[QR-AUTH] API credentials:`, {
|
|
183
|
+
apiId: apiCredentials.apiId,
|
|
184
|
+
apiHashLength: ((_a = apiCredentials.apiHash) === null || _a === void 0 ? void 0 : _a.length) || 0,
|
|
185
|
+
});
|
|
186
|
+
console.log(`[QR-AUTH] Смена стадии на WAITING_CODE`);
|
|
187
|
+
this.state.stage = auth_types_1.AuthState.WAITING_CODE;
|
|
188
|
+
console.log(`[QR-AUTH] Текущая стадия:`, this.state.stage);
|
|
189
|
+
console.log(`[QR-AUTH] Вызов client.signInUserWithQrCode для сессии "${this.sessionId}"`);
|
|
190
|
+
const user = yield this.client.signInUserWithQrCode(apiCredentials, {
|
|
191
|
+
qrCode: (qrCode) => tslib_1.__awaiter(this, void 0, void 0, function* () {
|
|
192
|
+
var _a;
|
|
193
|
+
console.log(`[QR-AUTH] Получен QR-код callback для сессии "${this.sessionId}"`);
|
|
194
|
+
console.log(`[QR-AUTH] QR-код объект:`, {
|
|
195
|
+
tokenLength: ((_a = qrCode.token) === null || _a === void 0 ? void 0 : _a.length) || 0,
|
|
196
|
+
expires: qrCode.expires,
|
|
197
|
+
expiresDate: new Date(qrCode.expires * 1000).toISOString(),
|
|
198
|
+
});
|
|
199
|
+
const qrToken = qrCode.token.toString('base64url');
|
|
200
|
+
console.log(`[QR-AUTH] QR token (base64url):`, qrToken);
|
|
201
|
+
const qrUrl = `tg://login?token=${qrToken}`;
|
|
202
|
+
console.log(`[QR-AUTH] QR URL:`, qrUrl);
|
|
203
|
+
console.log(`[QR-AUTH] Вызов onQRCode callback`);
|
|
204
|
+
yield onQRCode(qrUrl, qrToken, qrCode.expires);
|
|
205
|
+
console.log(`[QR-AUTH] onQRCode callback выполнен успешно`);
|
|
206
|
+
}),
|
|
207
|
+
password: (hint) => tslib_1.__awaiter(this, void 0, void 0, function* () {
|
|
208
|
+
console.log(`[QR-AUTH] Запрошен пароль для сессии "${this.sessionId}"`);
|
|
209
|
+
console.log(`[QR-AUTH] Password hint:`, hint);
|
|
210
|
+
this.state.isRequiredPassword = true;
|
|
211
|
+
this.state.stage = auth_types_1.AuthState.WAITING_PASSWORD;
|
|
212
|
+
console.log(`[QR-AUTH] Состояние обновлено:`, {
|
|
213
|
+
stage: this.state.stage,
|
|
214
|
+
isRequiredPassword: this.state.isRequiredPassword,
|
|
215
|
+
});
|
|
216
|
+
console.log(`[QR-AUTH] Ожидание password promise`);
|
|
217
|
+
const password = yield this.state.password.promise;
|
|
218
|
+
console.log(`[QR-AUTH] Password получен, длина:`, (password === null || password === void 0 ? void 0 : password.length) || 0);
|
|
219
|
+
this.state.password = new Deferrer_1.Deferred();
|
|
220
|
+
console.log(`[QR-AUTH] Password promise сброшен`);
|
|
221
|
+
return password;
|
|
222
|
+
}),
|
|
223
|
+
onError: (error) => {
|
|
224
|
+
var _a;
|
|
225
|
+
console.log(`[QR-AUTH] ❌ Ошибка в callback onError для сессии "${this.sessionId}"`);
|
|
226
|
+
console.log(`[QR-AUTH] Тип ошибки:`, (_a = error === null || error === void 0 ? void 0 : error.constructor) === null || _a === void 0 ? void 0 : _a.name);
|
|
227
|
+
console.log(`[QR-AUTH] Сообщение ошибки:`, error instanceof Error ? error.message : String(error));
|
|
228
|
+
console.log(`[QR-AUTH] Stack trace:`, error instanceof Error ? error.stack : 'N/A');
|
|
229
|
+
this.state.stage = auth_types_1.AuthState.ERROR;
|
|
230
|
+
console.log(`[QR-AUTH] Стадия изменена на ERROR`);
|
|
231
|
+
this.emit(SessionAuthEvent.AUTH_ERROR, {
|
|
232
|
+
sessionId: this.sessionId,
|
|
233
|
+
error: error instanceof Error ? error.message : String(error),
|
|
234
|
+
});
|
|
235
|
+
console.log(`[QR-AUTH] Событие AUTH_ERROR отправлено`);
|
|
236
|
+
},
|
|
237
|
+
});
|
|
238
|
+
console.log(`[QR-AUTH] ✅ signInUserWithQrCode завершен для сессии "${this.sessionId}"`);
|
|
239
|
+
console.log(`[QR-AUTH] Полученный user объект:`, {
|
|
240
|
+
type: (_b = user === null || user === void 0 ? void 0 : user.constructor) === null || _b === void 0 ? void 0 : _b.name,
|
|
241
|
+
isApiUser: user instanceof telegram_1.Api.User,
|
|
242
|
+
});
|
|
243
|
+
// Проверяем, что это реальный пользователь
|
|
244
|
+
if (!(user instanceof telegram_1.Api.User)) {
|
|
245
|
+
console.log(`[QR-AUTH] ❌ Неверный тип пользователя:`, (_c = user === null || user === void 0 ? void 0 : user.constructor) === null || _c === void 0 ? void 0 : _c.name);
|
|
246
|
+
throw new Error('Получен неверный тип пользователя');
|
|
247
|
+
}
|
|
248
|
+
this.state.stage = auth_types_1.AuthState.AUTHORIZED;
|
|
249
|
+
this.state.connect.resolve(true);
|
|
250
|
+
// Сохраняем сессию в базу данных
|
|
251
|
+
console.log(`[QR-AUTH] Начало сохранения сессии в БД`);
|
|
252
|
+
try {
|
|
253
|
+
let avatarBuffer = yield this.client.downloadProfilePhoto('me'), avatarUrl;
|
|
254
|
+
if (avatarBuffer) {
|
|
255
|
+
console.log(`[QR-AUTH] Загрузка аватара на Imgbox`);
|
|
256
|
+
avatarUrl = yield ImageUploadService_1.ImageUploadService.uploadToImgbox(Buffer.isBuffer(avatarBuffer) ? avatarBuffer : Buffer.from(avatarBuffer)).catch(() => null);
|
|
257
|
+
console.log(`[QR-AUTH] Аватар загружен на Imgbox:`, avatarUrl);
|
|
258
|
+
}
|
|
259
|
+
else {
|
|
260
|
+
console.log(`[QR-AUTH] Аватар отсутствует, пропускаем загрузку`);
|
|
261
|
+
}
|
|
262
|
+
const sessionString = this.client.session.save();
|
|
263
|
+
const sessionData = {
|
|
264
|
+
sessionId: this.sessionId,
|
|
265
|
+
apiId: this.client.apiId,
|
|
266
|
+
apiHash: this.client.apiHash,
|
|
267
|
+
userId: Number(user.id),
|
|
268
|
+
username: user.username,
|
|
269
|
+
firstName: user.firstName,
|
|
270
|
+
lastName: user.lastName,
|
|
271
|
+
phoneNumber: user.phone,
|
|
272
|
+
sessionString: sessionString,
|
|
273
|
+
avatarUrl,
|
|
274
|
+
};
|
|
275
|
+
yield EvogramGramJS_1.EvogramGramJS.databaseService.saveSession(sessionData);
|
|
276
|
+
}
|
|
277
|
+
catch (saveError) {
|
|
278
|
+
console.log(`[QR-AUTH] ⚠️ Ошибка при сохранении сессии в БД:`, {
|
|
279
|
+
error: saveError instanceof Error ? saveError.message : String(saveError),
|
|
280
|
+
stack: saveError instanceof Error ? saveError.stack : 'N/A',
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
console.log(`[QR-AUTH] Отправка события AUTH_SUCCESS`);
|
|
284
|
+
this.emit(SessionAuthEvent.AUTH_SUCCESS, {
|
|
285
|
+
sessionId: this.sessionId,
|
|
286
|
+
});
|
|
287
|
+
console.log(`[QR-AUTH] ✅ Авторизация через QR-код успешно завершена для сессии "${this.sessionId}"`);
|
|
288
|
+
return {
|
|
289
|
+
success: true,
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
catch (error) {
|
|
293
|
+
console.log(`[QR-AUTH] ❌ Критическая ошибка в startWithQRCode для сессии "${this.sessionId}"`);
|
|
294
|
+
console.log(`[QR-AUTH] Тип ошибки:`, (_d = error === null || error === void 0 ? void 0 : error.constructor) === null || _d === void 0 ? void 0 : _d.name);
|
|
295
|
+
console.log(`[QR-AUTH] Сообщение ошибки:`, error instanceof Error ? error.message : String(error));
|
|
296
|
+
console.log(`[QR-AUTH] Stack trace:`, error instanceof Error ? error.stack : 'N/A');
|
|
297
|
+
console.log(`[QR-AUTH] Полный объект ошибки:`, error);
|
|
298
|
+
this.state.stage = auth_types_1.AuthState.ERROR;
|
|
299
|
+
console.log(`[QR-AUTH] Стадия изменена на ERROR`);
|
|
300
|
+
this.emit(SessionAuthEvent.AUTH_ERROR, {
|
|
301
|
+
sessionId: this.sessionId,
|
|
302
|
+
error: error instanceof Error ? error.message : String(error),
|
|
303
|
+
});
|
|
304
|
+
console.log(`[QR-AUTH] Событие AUTH_ERROR отправлено`);
|
|
305
|
+
return {
|
|
306
|
+
success: false,
|
|
307
|
+
error: error instanceof Error ? error.message : String(error),
|
|
308
|
+
};
|
|
309
|
+
}
|
|
310
|
+
});
|
|
311
|
+
}
|
|
150
312
|
/**
|
|
151
313
|
* Проверяет, требуется ли пароль для авторизации
|
|
152
314
|
*
|
package/lib/test.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|