evogram-gramjs 1.1.0 → 1.1.2

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 (62) hide show
  1. package/lib/EvogramGramJS.d.ts +51 -0
  2. package/lib/EvogramGramJS.js +99 -0
  3. package/lib/commands/Accounts.command.d.ts +6 -0
  4. package/lib/commands/Accounts.command.js +95 -0
  5. package/lib/commands/AddAccount.command.d.ts +19 -0
  6. package/lib/commands/AddAccount.command.js +461 -0
  7. package/lib/commands/index.d.ts +2 -0
  8. package/lib/commands/index.js +5 -0
  9. package/lib/commands/managment/DeleteAccount.command.d.ts +0 -0
  10. package/{src/commands/managment/DeleteAccount.command.ts → lib/commands/managment/DeleteAccount.command.js} +1 -2
  11. package/lib/config/database.config.d.ts +26 -0
  12. package/lib/config/database.config.js +31 -0
  13. package/lib/entities/Session.entity.d.ts +28 -0
  14. package/lib/entities/Session.entity.js +71 -0
  15. package/lib/entities/SessionEventLog.entity.d.ts +22 -0
  16. package/lib/entities/SessionEventLog.entity.js +50 -0
  17. package/lib/examples/auth.example.d.ts +10 -0
  18. package/lib/examples/auth.example.js +126 -0
  19. package/lib/examples/database.example.d.ts +13 -0
  20. package/lib/examples/database.example.js +109 -0
  21. package/lib/examples/usage.example.d.ts +13 -0
  22. package/lib/examples/usage.example.js +127 -0
  23. package/lib/index.d.ts +7 -0
  24. package/lib/index.js +10 -0
  25. package/lib/services/DatabaseService.d.ts +31 -0
  26. package/lib/services/DatabaseService.js +100 -0
  27. package/lib/services/ImageUploadService.d.ts +15 -0
  28. package/lib/services/ImageUploadService.js +56 -0
  29. package/lib/sessions/Session.d.ts +13 -0
  30. package/lib/sessions/Session.js +25 -0
  31. package/lib/sessions/SessionAuth.d.ts +72 -0
  32. package/lib/sessions/SessionAuth.js +327 -0
  33. package/lib/sessions/SessionLogger.d.ts +84 -0
  34. package/lib/sessions/SessionLogger.js +196 -0
  35. package/lib/sessions/SessionManager.d.ts +84 -0
  36. package/lib/sessions/SessionManager.js +198 -0
  37. package/lib/test.d.ts +1 -0
  38. package/lib/test.js +144 -0
  39. package/lib/types/auth.types.d.ts +90 -0
  40. package/lib/types/auth.types.js +19 -0
  41. package/lib/types/session.types.d.ts +87 -0
  42. package/lib/types/session.types.js +21 -0
  43. package/lib/utils/Deferrer.d.ts +6 -0
  44. package/lib/utils/Deferrer.js +14 -0
  45. package/package.json +1 -2
  46. package/src/EvogramGramJS.ts +0 -98
  47. package/src/commands/Accounts.command.ts +0 -89
  48. package/src/commands/AddAccount.command.ts +0 -449
  49. package/src/commands/index.ts +0 -2
  50. package/src/config/database.config.ts +0 -75
  51. package/src/entities/Session.entity.ts +0 -58
  52. package/src/entities/SessionEventLog.entity.ts +0 -41
  53. package/src/index.ts +0 -7
  54. package/src/services/DatabaseService.ts +0 -82
  55. package/src/services/ImageUploadService.ts +0 -49
  56. package/src/sessions/Session.ts +0 -21
  57. package/src/sessions/SessionAuth.ts +0 -356
  58. package/src/sessions/SessionLogger.ts +0 -208
  59. package/src/sessions/SessionManager.ts +0 -211
  60. package/src/types/auth.types.ts +0 -94
  61. package/src/types/session.types.ts +0 -96
  62. package/src/utils/Deferrer.ts +0 -12
@@ -0,0 +1,461 @@
1
+ "use strict";
2
+ var AddAccountByCodeCommand_1, AddAccountByQRCodeCommand_1, AddAccountByStringSessionCommand_1;
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.AddAccountByStringSessionCommand = exports.AddAccountByQRCodeCommand = exports.AddAccountByCodeCommand = exports.AddAccountCommand = void 0;
5
+ const tslib_1 = require("tslib");
6
+ const evogram_1 = require("evogram");
7
+ const QRCode = tslib_1.__importStar(require("qrcode"));
8
+ const EvogramGramJS_1 = require("../EvogramGramJS");
9
+ const auth_types_1 = require("../types/auth.types");
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 {
38
+ execute(context, phone, code, password) {
39
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
40
+ const session = EvogramGramJS_1.EvogramGramJS.sessionManager.getSession(yield context.storage.get('session'));
41
+ context.send(`Вы успешно добавили аккаунт ${yield session.client
42
+ .getMe()
43
+ .then((user) => user.username)
44
+ .catch(() => 'unknown')}`);
45
+ yield context.storage.clearAll();
46
+ });
47
+ }
48
+ handleMessage(context, message) {
49
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
50
+ if (!(message === null || message === void 0 ? void 0 : message.text))
51
+ return;
52
+ console.log({ session: yield context.storage.get('session'), phone: yield context.storage.get('phone'), code: yield context.storage.get('code'), password: yield context.storage.get('password'), command: context.state.command, stage: yield context.storage.get('stage') });
53
+ yield context.edit('⏳').catch(() => { });
54
+ yield message.delete().catch(() => { });
55
+ if (!(yield context.storage.get('phone')))
56
+ context.redirect(AddAccountByCodeCommand_1, { phone: message.text });
57
+ else if ((yield context.storage.get('stage')) === 'code')
58
+ context.redirect(AddAccountByCodeCommand_1, { code: message.text });
59
+ else if ((yield context.storage.get('stage')) === 'password')
60
+ context.redirect(AddAccountByCodeCommand_1, { password: message.text });
61
+ });
62
+ }
63
+ onError(context, error) {
64
+ var _a;
65
+ //@ts-ignore
66
+ (_a = context[context.callbackQuery ? 'edit' : 'send']) === null || _a === void 0 ? void 0 : _a.call(context, {
67
+ // prettier-ignore
68
+ text: '<blockquote><b>❗️Произошла ошибка при добавлении аккаунта</b></blockquote>\n\n' +
69
+ error.message,
70
+ parse_mode: 'HTML',
71
+ });
72
+ }
73
+ };
74
+ exports.AddAccountByCodeCommand = AddAccountByCodeCommand;
75
+ tslib_1.__decorate([
76
+ tslib_1.__param(1, (0, evogram_1.CommandStorageArgument)('phone', (_a) => tslib_1.__awaiter(void 0, [_a], void 0, function* ({ context, value }) {
77
+ var _b, _c;
78
+ if (value) {
79
+ console.log({ value });
80
+ if (!(yield context.storage.get('session'))) {
81
+ const session = yield EvogramGramJS_1.EvogramGramJS.sessionManager.addSession({
82
+ sessionId: value,
83
+ logging: {
84
+ enabled: true,
85
+ logsDirectory: './logs',
86
+ },
87
+ });
88
+ const result = yield session.auth.start(value);
89
+ if (result.success) {
90
+ yield context.storage.set('stage', 'code');
91
+ yield context.storage.set('session', session.sessionId);
92
+ return value;
93
+ }
94
+ else {
95
+ context.state.command = undefined;
96
+ yield context.storage.clearAll();
97
+ //@ts-ignore
98
+ (_b = context[context.callbackQuery ? 'edit' : 'send']) === null || _b === void 0 ? void 0 : _b.call(context, {
99
+ // prettier-ignore
100
+ text: '<blockquote><b>❗️Произошла ошибка при добавлении аккаунта</b></blockquote>\n\n' +
101
+ result.error,
102
+ parse_mode: 'HTML',
103
+ });
104
+ }
105
+ }
106
+ else
107
+ return value;
108
+ }
109
+ else {
110
+ //@ts-ignore
111
+ (_c = context[context.callbackQuery ? 'edit' : 'send']) === null || _c === void 0 ? void 0 : _c.call(context, {
112
+ // prettier-ignore
113
+ text: '<blockquote><b>➕ Добавление аккаунта</b></blockquote>\n\n' +
114
+ '<i>Отправьте номер телефона в следующем сообщении</i>',
115
+ parse_mode: 'HTML',
116
+ });
117
+ }
118
+ }))),
119
+ tslib_1.__param(2, (0, evogram_1.CommandStorageArgument)('code', (_a) => tslib_1.__awaiter(void 0, [_a], void 0, function* ({ context, value }) {
120
+ var _b, _c, _d;
121
+ if (value) {
122
+ const session = EvogramGramJS_1.EvogramGramJS.sessionManager.getSession(yield context.storage.get('session'));
123
+ if (((_b = session.auth.state) === null || _b === void 0 ? void 0 : _b.stage) !== auth_types_1.AuthState.WAITING_CODE)
124
+ return value;
125
+ const result = yield session.auth.setCode(value);
126
+ if (result.success) {
127
+ yield context.storage.set('stage', 'password');
128
+ return value;
129
+ }
130
+ else {
131
+ //@ts-ignore
132
+ (_c = context[context.callbackQuery ? 'edit' : 'send']) === null || _c === void 0 ? void 0 : _c.call(context, {
133
+ // prettier-ignore
134
+ text: '<blockquote><b>➕ Добавление аккаунта</b></blockquote>\n\n' +
135
+ '<i>Отправьте код подтверждения, отправленный на аккаунт, в следующем сообщении</i>\n\n' +
136
+ `<blockquote><b>❗️Произошла ошибка</b></blockquote>\n\n` +
137
+ result.error,
138
+ parse_mode: 'HTML',
139
+ });
140
+ return null;
141
+ }
142
+ }
143
+ else {
144
+ //@ts-ignore
145
+ (_d = context[context.callbackQuery ? 'edit' : 'send']) === null || _d === void 0 ? void 0 : _d.call(context, {
146
+ // prettier-ignore
147
+ text: '<blockquote><b>➕ Добавление аккаунта</b></blockquote>\n\n' +
148
+ '<i>Отправьте код подтверждения, отправленный на аккаунт, в следующем сообщении</i>',
149
+ parse_mode: 'HTML',
150
+ });
151
+ }
152
+ }))),
153
+ tslib_1.__param(3, (0, evogram_1.CommandStorageArgument)('password', (_a) => tslib_1.__awaiter(void 0, [_a], void 0, function* ({ context, value }) {
154
+ var _b, _c;
155
+ const session = EvogramGramJS_1.EvogramGramJS.sessionManager.getSession(yield context.storage.get('session'));
156
+ const isRequired = yield session.auth.isRequiredPassword();
157
+ if (!isRequired || value === 'none')
158
+ return 'none';
159
+ if (value) {
160
+ const session = EvogramGramJS_1.EvogramGramJS.sessionManager.getSession(yield context.storage.get('session'));
161
+ const result = yield session.auth.setPassword(value);
162
+ if (result.success) {
163
+ return value;
164
+ }
165
+ else {
166
+ //@ts-ignore
167
+ (_b = context[context.callbackQuery ? 'edit' : 'send']) === null || _b === void 0 ? void 0 : _b.call(context, {
168
+ // prettier-ignore
169
+ text: '<blockquote><b>➕ Добавление аккаунта</b></blockquote>\n\n' +
170
+ '<i>На аккаунте включен 2FA. Отправьте пароль для 2FA в следующем сообщении</i>\n\n' +
171
+ `<blockquote><b>❗️Произошла ошибка</b></blockquote>\n\n` +
172
+ result.error,
173
+ parse_mode: 'HTML',
174
+ });
175
+ }
176
+ }
177
+ else {
178
+ //@ts-ignore
179
+ (_c = context[context.callbackQuery ? 'edit' : 'send']) === null || _c === void 0 ? void 0 : _c.call(context, {
180
+ // prettier-ignore
181
+ text: '<blockquote><b>➕ Добавление аккаунта</b></blockquote>\n\n' +
182
+ '<i>На аккаунте включен 2FA. Отправьте пароль для 2FA в следующем сообщении</i>',
183
+ parse_mode: 'HTML',
184
+ });
185
+ }
186
+ }))),
187
+ tslib_1.__metadata("design:type", Function),
188
+ tslib_1.__metadata("design:paramtypes", [evogram_1.CommandContext, String, String, String]),
189
+ tslib_1.__metadata("design:returntype", Promise)
190
+ ], AddAccountByCodeCommand.prototype, "execute", null);
191
+ tslib_1.__decorate([
192
+ (0, evogram_1.CommandUpdate)('message'),
193
+ tslib_1.__metadata("design:type", Function),
194
+ tslib_1.__metadata("design:paramtypes", [evogram_1.CommandContext, evogram_1.MessageContext]),
195
+ tslib_1.__metadata("design:returntype", Promise)
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);
@@ -0,0 +1,2 @@
1
+ export * from './Accounts.command';
2
+ export * from './AddAccount.command';
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const tslib_1 = require("tslib");
4
+ tslib_1.__exportStar(require("./Accounts.command"), exports);
5
+ tslib_1.__exportStar(require("./AddAccount.command"), exports);
@@ -1,12 +1,11 @@
1
+ "use strict";
1
2
  // import { Command, CommandArgument, CommandContext, CommandD } from 'evogram'
2
3
  // import { EvogramGramJS } from '../../EvogramGramJS'
3
-
4
4
  // @CommandD({ name: 'deleteaccount', argsMethod: 'parameterized' })
5
5
  // export class DeleteAccountCommand extends Command {
6
6
  // public async execute(context: CommandContext, @CommandArgument('sessionId') sessionId: string) {
7
7
  // const session = EvogramGramJS.sessionManager.getSession(sessionId)
8
8
  // if (!session) return context.send('Сессия не найдена')
9
-
10
9
  // await EvogramGramJS.databaseService.deleteSession(sessionId)
11
10
  // return context.send('Сессия успешно удалена')
12
11
  // }
@@ -0,0 +1,26 @@
1
+ import { DataSourceOptions } from 'typeorm';
2
+ /**
3
+ * Конфигурация базы данных
4
+ */
5
+ export interface DatabaseConfig {
6
+ /** Тип базы данных */
7
+ type?: 'sqlite' | 'postgres' | 'mysql' | 'mariadb';
8
+ /** Путь к файлу БД (для SQLite) или строка подключения */
9
+ database?: string;
10
+ /** Хост БД (для PostgreSQL/MySQL) */
11
+ host?: string;
12
+ /** Порт БД (для PostgreSQL/MySQL) */
13
+ port?: number;
14
+ /** Имя пользователя БД */
15
+ username?: string;
16
+ /** Пароль БД */
17
+ password?: string;
18
+ /** Включить синхронизацию схемы (только для разработки) */
19
+ synchronize?: boolean;
20
+ /** Включить логирование SQL запросов */
21
+ logging?: boolean;
22
+ }
23
+ /**
24
+ * Создает конфигурацию DataSource для TypeORM
25
+ */
26
+ export declare function createDataSourceOptions(config?: DatabaseConfig): DataSourceOptions;
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createDataSourceOptions = createDataSourceOptions;
4
+ const Session_entity_1 = require("../entities/Session.entity");
5
+ const SessionEventLog_entity_1 = require("../entities/SessionEventLog.entity");
6
+ /**
7
+ * Создает конфигурацию DataSource для TypeORM
8
+ */
9
+ function createDataSourceOptions(config = {}) {
10
+ const { type = 'sqlite', database = './data/evogram.db', host, port, username, password, synchronize = false, logging = false } = config;
11
+ const baseOptions = {
12
+ type: type,
13
+ entities: [Session_entity_1.Session, SessionEventLog_entity_1.SessionEventLog],
14
+ synchronize,
15
+ logging,
16
+ };
17
+ if (type === 'sqlite') {
18
+ // Для SQLite используем специальную конфигурацию
19
+ const sqliteOptions = Object.assign(Object.assign({}, baseOptions), { type: 'better-sqlite3', database });
20
+ return sqliteOptions;
21
+ }
22
+ if (type === 'postgres') {
23
+ return Object.assign(Object.assign({}, baseOptions), { type: 'postgres', host: host || 'localhost', port: port || 5432, username,
24
+ password, database: database || 'evogram' });
25
+ }
26
+ if (type === 'mysql' || type === 'mariadb') {
27
+ return Object.assign(Object.assign({}, baseOptions), { type: type === 'mariadb' ? 'mariadb' : 'mysql', host: host || 'localhost', port: port || 3306, username,
28
+ password, database: database || 'evogram' });
29
+ }
30
+ return baseOptions;
31
+ }
@@ -0,0 +1,28 @@
1
+ import { SessionEventLog } from './SessionEventLog.entity';
2
+ /**
3
+ * Сущность сессии Telegram в базе данных
4
+ */
5
+ export declare class Session {
6
+ /** Уникальный идентификатор сессии */
7
+ sessionId: string;
8
+ /** API ID из Telegram */
9
+ apiId?: number;
10
+ /** API Hash из Telegram */
11
+ apiHash?: string;
12
+ userId: number;
13
+ username?: string;
14
+ firstName?: string;
15
+ lastName?: string;
16
+ phoneNumber?: string;
17
+ error?: string;
18
+ /** Строка сессии (зашифрованная) */
19
+ sessionString?: string;
20
+ /** Дополнительные опции клиента (JSON) */
21
+ clientOptions?: string;
22
+ /** URL аватарки пользователя */
23
+ avatarUrl?: string;
24
+ /** Связанные события сессии */
25
+ eventLogs: SessionEventLog[];
26
+ /** Время создания сессии */
27
+ createdAt: Date;
28
+ }
@@ -0,0 +1,71 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Session = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const typeorm_1 = require("typeorm");
6
+ const SessionEventLog_entity_1 = require("./SessionEventLog.entity");
7
+ /**
8
+ * Сущность сессии Telegram в базе данных
9
+ */
10
+ let Session = class Session {
11
+ };
12
+ exports.Session = Session;
13
+ tslib_1.__decorate([
14
+ (0, typeorm_1.PrimaryColumn)({ type: 'varchar', length: 255 }),
15
+ tslib_1.__metadata("design:type", String)
16
+ ], Session.prototype, "sessionId", void 0);
17
+ tslib_1.__decorate([
18
+ (0, typeorm_1.Column)({ type: 'integer', nullable: true }),
19
+ tslib_1.__metadata("design:type", Number)
20
+ ], Session.prototype, "apiId", void 0);
21
+ tslib_1.__decorate([
22
+ (0, typeorm_1.Column)({ type: 'varchar', length: 255, nullable: true }),
23
+ tslib_1.__metadata("design:type", String)
24
+ ], Session.prototype, "apiHash", void 0);
25
+ tslib_1.__decorate([
26
+ (0, typeorm_1.Column)({ type: 'bigint' }),
27
+ tslib_1.__metadata("design:type", Number)
28
+ ], Session.prototype, "userId", void 0);
29
+ tslib_1.__decorate([
30
+ (0, typeorm_1.Column)({ type: 'varchar', length: 255, nullable: true }),
31
+ tslib_1.__metadata("design:type", String)
32
+ ], Session.prototype, "username", void 0);
33
+ tslib_1.__decorate([
34
+ (0, typeorm_1.Column)({ type: 'varchar', length: 255, nullable: true }),
35
+ tslib_1.__metadata("design:type", String)
36
+ ], Session.prototype, "firstName", void 0);
37
+ tslib_1.__decorate([
38
+ (0, typeorm_1.Column)({ type: 'varchar', length: 255, nullable: true }),
39
+ tslib_1.__metadata("design:type", String)
40
+ ], Session.prototype, "lastName", void 0);
41
+ tslib_1.__decorate([
42
+ (0, typeorm_1.Column)({ type: 'varchar', length: 255, nullable: true }),
43
+ tslib_1.__metadata("design:type", String)
44
+ ], Session.prototype, "phoneNumber", void 0);
45
+ tslib_1.__decorate([
46
+ (0, typeorm_1.Column)({ type: 'text', nullable: true }),
47
+ tslib_1.__metadata("design:type", String)
48
+ ], Session.prototype, "error", void 0);
49
+ tslib_1.__decorate([
50
+ (0, typeorm_1.Column)({ type: 'text', nullable: true }),
51
+ tslib_1.__metadata("design:type", String)
52
+ ], Session.prototype, "sessionString", void 0);
53
+ tslib_1.__decorate([
54
+ (0, typeorm_1.Column)({ type: 'text', nullable: true }),
55
+ tslib_1.__metadata("design:type", String)
56
+ ], Session.prototype, "clientOptions", void 0);
57
+ tslib_1.__decorate([
58
+ (0, typeorm_1.Column)({ type: 'varchar', length: 500, nullable: true }),
59
+ tslib_1.__metadata("design:type", String)
60
+ ], Session.prototype, "avatarUrl", void 0);
61
+ tslib_1.__decorate([
62
+ (0, typeorm_1.OneToMany)(() => SessionEventLog_entity_1.SessionEventLog, (eventLog) => eventLog.session, { cascade: true }),
63
+ tslib_1.__metadata("design:type", Array)
64
+ ], Session.prototype, "eventLogs", void 0);
65
+ tslib_1.__decorate([
66
+ (0, typeorm_1.CreateDateColumn)(),
67
+ tslib_1.__metadata("design:type", Date)
68
+ ], Session.prototype, "createdAt", void 0);
69
+ exports.Session = Session = tslib_1.__decorate([
70
+ (0, typeorm_1.Entity)('sessions')
71
+ ], Session);