evogram-gramjs 1.1.0 → 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.
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 +30 -0
  26. package/lib/services/DatabaseService.js +93 -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
@@ -1,449 +0,0 @@
1
- import { Command, CommandContext, CommandD, CommandStorageArgument, CommandUpdate, MessageContext } from 'evogram'
2
- import * as QRCode from 'qrcode'
3
- import { EvogramGramJS } from '../EvogramGramJS'
4
- import { AuthState } from '../types/auth.types'
5
-
6
- @CommandD({ name: 'addaccount', argsMethod: 'parameterized' })
7
- export class AddAccountCommand extends Command {
8
- public async execute(context: CommandContext) {
9
- //@ts-ignore
10
- context[context.callbackQuery ? 'edit' : 'send']?.({
11
- // prettier-ignore
12
- text:
13
- '<blockquote><b>➕ Добавление аккаунта</b></blockquote>\n\n' +
14
-
15
- '<i>Выберите метод добавления аккаунта</i>',
16
- parse_mode: 'HTML',
17
- reply_markup: {
18
- inline_keyboard: [
19
- [
20
- { text: 'SMS-код', command: AddAccountByCodeCommand },
21
- { text: 'QR-код', command: AddAccountByQRCodeCommand },
22
- ],
23
- [{ text: 'StringSession', command: AddAccountByStringSessionCommand }],
24
- ],
25
- },
26
- })
27
- }
28
- }
29
-
30
- @CommandD({ name: 'addaccountbycode', argsMethod: 'parameterized' })
31
- export class AddAccountByCodeCommand extends Command {
32
- public async execute(
33
- context: CommandContext,
34
- @CommandStorageArgument('phone', async ({ context, value }) => {
35
- if (value) {
36
- console.log({ value })
37
- if (!(await context.storage.get('session'))) {
38
- const session = await EvogramGramJS.sessionManager.addSession({
39
- sessionId: value,
40
- logging: {
41
- enabled: true,
42
- logsDirectory: './logs',
43
- },
44
- })
45
-
46
- const result = await session.auth.start(value)
47
- if (result.success) {
48
- await context.storage.set('stage', 'code')
49
- await context.storage.set('session', session.sessionId)
50
-
51
- return value
52
- } else {
53
- context.state.command = undefined
54
- await context.storage.clearAll()
55
-
56
- //@ts-ignore
57
- context[context.callbackQuery ? 'edit' : 'send']?.({
58
- // prettier-ignore
59
- text:
60
- '<blockquote><b>❗️Произошла ошибка при добавлении аккаунта</b></blockquote>\n\n' +
61
-
62
- result.error,
63
- parse_mode: 'HTML',
64
- })
65
- }
66
- } else return value
67
- } else {
68
- //@ts-ignore
69
- context[context.callbackQuery ? 'edit' : 'send']?.({
70
- // prettier-ignore
71
- text:
72
- '<blockquote><b>➕ Добавление аккаунта</b></blockquote>\n\n' +
73
-
74
- '<i>Отправьте номер телефона в следующем сообщении</i>',
75
- parse_mode: 'HTML',
76
- })
77
- }
78
- })
79
- phone: string,
80
- @CommandStorageArgument('code', async ({ context, value }) => {
81
- if (value) {
82
- const session = EvogramGramJS.sessionManager.getSession(await context.storage.get('session'))!
83
- if (session.auth.state?.stage !== AuthState.WAITING_CODE) return value
84
-
85
- const result = await session.auth.setCode(value)
86
-
87
- if (result.success) {
88
- await context.storage.set('stage', 'password')
89
- return value
90
- } else {
91
- //@ts-ignore
92
- context[context.callbackQuery ? 'edit' : 'send']?.({
93
- // prettier-ignore
94
- text:
95
- '<blockquote><b>➕ Добавление аккаунта</b></blockquote>\n\n' +
96
-
97
- '<i>Отправьте код подтверждения, отправленный на аккаунт, в следующем сообщении</i>\n\n' +
98
-
99
- `<blockquote><b>❗️Произошла ошибка</b></blockquote>\n\n` +
100
-
101
- result.error,
102
- parse_mode: 'HTML',
103
- })
104
-
105
- return null
106
- }
107
- } else {
108
- //@ts-ignore
109
- context[context.callbackQuery ? 'edit' : 'send']?.({
110
- // prettier-ignore
111
- text:
112
- '<blockquote><b>➕ Добавление аккаунта</b></blockquote>\n\n' +
113
-
114
- '<i>Отправьте код подтверждения, отправленный на аккаунт, в следующем сообщении</i>',
115
- parse_mode: 'HTML',
116
- })
117
- }
118
- })
119
- code: string,
120
- @CommandStorageArgument('password', async ({ context, value }) => {
121
- const session = EvogramGramJS.sessionManager.getSession(await context.storage.get('session'))!
122
-
123
- const isRequired = await session.auth.isRequiredPassword()
124
- if (!isRequired || value === 'none') return 'none'
125
-
126
- if (value) {
127
- const session = EvogramGramJS.sessionManager.getSession(await context.storage.get('session'))!
128
- const result = await session.auth.setPassword(value)
129
-
130
- if (result.success) {
131
- return value
132
- } else {
133
- //@ts-ignore
134
- context[context.callbackQuery ? 'edit' : 'send']?.({
135
- // prettier-ignore
136
- text:
137
- '<blockquote><b>➕ Добавление аккаунта</b></blockquote>\n\n' +
138
-
139
- '<i>На аккаунте включен 2FA. Отправьте пароль для 2FA в следующем сообщении</i>\n\n' +
140
-
141
- `<blockquote><b>❗️Произошла ошибка</b></blockquote>\n\n` +
142
-
143
- result.error,
144
- parse_mode: 'HTML',
145
- })
146
- }
147
- } else {
148
- //@ts-ignore
149
- context[context.callbackQuery ? 'edit' : 'send']?.({
150
- // prettier-ignore
151
- text:
152
- '<blockquote><b>➕ Добавление аккаунта</b></blockquote>\n\n' +
153
-
154
- '<i>На аккаунте включен 2FA. Отправьте пароль для 2FA в следующем сообщении</i>',
155
- parse_mode: 'HTML',
156
- })
157
- }
158
- })
159
- password: string,
160
- ) {
161
- const session = EvogramGramJS.sessionManager.getSession(await context.storage.get('session'))!
162
-
163
- context.send(
164
- `Вы успешно добавили аккаунт ${await session.client
165
- .getMe()
166
- .then((user) => user.username)
167
- .catch(() => 'unknown')}`,
168
- )
169
- await context.storage.clearAll()
170
- }
171
-
172
- @CommandUpdate('message')
173
- async handleMessage(context: CommandContext, message: MessageContext) {
174
- if (!message?.text) return
175
-
176
- console.log({ session: await context.storage.get('session'), phone: await context.storage.get('phone'), code: await context.storage.get('code'), password: await context.storage.get('password'), command: context.state.command, stage: await context.storage.get('stage') })
177
-
178
- await context.edit('⏳').catch(() => {})
179
- await message.delete().catch(() => {})
180
-
181
- if (!(await context.storage.get('phone'))) context.redirect(AddAccountByCodeCommand, { phone: message.text })
182
- else if ((await context.storage.get('stage')) === 'code') context.redirect(AddAccountByCodeCommand, { code: message.text })
183
- else if ((await context.storage.get('stage')) === 'password') context.redirect(AddAccountByCodeCommand, { password: message.text })
184
- }
185
-
186
- onError(context: CommandContext, error: Error) {
187
- //@ts-ignore
188
- context[context.callbackQuery ? 'edit' : 'send']?.({
189
- // prettier-ignore
190
- text:
191
- '<blockquote><b>❗️Произошла ошибка при добавлении аккаунта</b></blockquote>\n\n' +
192
-
193
- error.message,
194
- parse_mode: 'HTML',
195
- })
196
- }
197
- }
198
-
199
- @CommandD({ name: 'addaccountbyqrcode', argsMethod: 'parameterized' })
200
- export class AddAccountByQRCodeCommand extends Command {
201
- public async execute(
202
- context: CommandContext,
203
- @CommandStorageArgument('qrcode', async ({ context, value }) => {
204
- try {
205
- if (value) return value
206
-
207
- let qrcodeMsg: any = null
208
- const session = (await context.storage.get('session'))
209
- ? EvogramGramJS.sessionManager.getSession(await context.storage.get('session'))!
210
- : await EvogramGramJS.sessionManager.addSession({
211
- sessionId: `qr-auth-${Date.now()}`,
212
- logging: {
213
- enabled: true,
214
- logsDirectory: './logs',
215
- },
216
- })
217
-
218
- if (![AuthState.INITIAL, AuthState.WAITING_CODE, undefined].includes(session.auth.state?.stage)) return true
219
-
220
- await context.storage.set('session', session.sessionId)
221
-
222
- //@ts-ignore
223
- await context[context.callbackQuery ? 'edit' : 'send']?.({
224
- text: '<blockquote><b>➕ Добавление аккаунта через QR-код</b></blockquote>\n\n' + '<i>Генерируем QR-код для входа...</i>\n\n',
225
- parse_mode: 'HTML',
226
- }).catch(() => {})
227
-
228
- // Запускаем авторизацию через QR код
229
- session.auth.startWithQRCode(async (qrUrl, qrToken, expires) => {
230
- try {
231
- // Генерируем QR код как изображение
232
- const qrCodeBuffer = await QRCode.toBuffer(qrUrl, {
233
- type: 'png',
234
- width: 500,
235
- margin: 2,
236
- color: {
237
- dark: '#000000',
238
- light: '#FFFFFF',
239
- },
240
- })
241
-
242
- const expiresDate = new Date(Date.now() + expires * 1000)
243
- // prettier-ignore
244
- const caption =
245
- `<blockquote><b>📱 QR-код для входа</b></blockquote>\n\n` +
246
-
247
- '<i>Отсканируйте QR-код в приложении Telegram:</i>\n' +
248
- '<b>Настройки → Устройства → Подключить устройство</b>\n\n' +
249
-
250
- `⏳ QR-код действителен до: <code>${expiresDate.toLocaleString('ru-RU')}</code>`;
251
-
252
- if (context.source.text) {
253
- qrcodeMsg = await context.sendPhoto(qrCodeBuffer, { caption, parse_mode: 'HTML' })
254
- } else {
255
- await context.client.api.editMessageMedia({
256
- chat_id: context.chat.id,
257
- message_id: context.message!.id,
258
- media: {
259
- type: 'photo',
260
- media: qrCodeBuffer as any,
261
- caption,
262
- parse_mode: 'HTML',
263
- },
264
- })
265
- }
266
- } catch (error) {
267
- console.error('Ошибка при генерации QR-кода:', error)
268
- throw error
269
- }
270
- })
271
-
272
- return new Promise((resolve) => {
273
- const interval = setInterval(async () => {
274
- if (session.auth.state?.stage !== AuthState.WAITING_CODE) {
275
- if (qrcodeMsg) await qrcodeMsg.delete().catch(() => {})
276
-
277
- clearInterval(interval)
278
- resolve(true)
279
- }
280
- }, 1000)
281
- })
282
- } catch (error) {
283
- console.error(error)
284
- }
285
- })
286
- qrcode: string,
287
- @CommandStorageArgument('password', async ({ context, value }) => {
288
- const session = EvogramGramJS.sessionManager.getSession(await context.storage.get('session'))!
289
-
290
- const isRequired = await session.auth.isRequiredPassword()
291
- if (!isRequired || value === 'none') return 'none'
292
-
293
- if (value) {
294
- const result = await session.auth.setPassword(value)
295
-
296
- if (result.success) {
297
- return value
298
- } else {
299
- //@ts-ignore
300
- context[context.callbackQuery ? 'edit' : 'send']?.({
301
- text: '<blockquote><b>➕ Добавление аккаунта через QR-код</b></blockquote>\n\n' + '<i>На аккаунте включен 2FA. Отправьте пароль для 2FA в следующем сообщении</i>\n\n' + `<blockquote><b>❗️Произошла ошибка</b></blockquote>\n\n` + result.error,
302
- parse_mode: 'HTML',
303
- })
304
-
305
- return null
306
- }
307
- } else {
308
- await context.storage.set('stage', 'password')
309
- //@ts-ignore
310
- context[context.callbackQuery ? 'edit' : 'send']?.({
311
- text: '<blockquote><b>➕ Добавление аккаунта через QR-код</b></blockquote>\n\n' + '<i>На аккаунте включен 2FA. Отправьте пароль для 2FA в следующем сообщении</i>',
312
- parse_mode: 'HTML',
313
- })
314
- }
315
- })
316
- password: string,
317
- ) {
318
- const session = EvogramGramJS.sessionManager.getSession(await context.storage.get('session'))!
319
-
320
- const user = await session.client.getMe()
321
- context.send(`✅ Вы успешно добавили аккаунт @${user.username || user.firstName || 'unknown'}`)
322
- await context.storage.clearAll()
323
- }
324
-
325
- @CommandUpdate('message')
326
- async handleMessage(context: CommandContext, message: MessageContext) {
327
- if (!message?.text) return
328
-
329
- await context.edit('⏳').catch(() => {})
330
- await message.delete().catch(() => {})
331
-
332
- if ((await context.storage.get('stage')) === 'password') context.redirect(AddAccountByQRCodeCommand, { password: message.text })
333
- }
334
-
335
- onError(context: CommandContext, error: Error) {
336
- //@ts-ignore
337
- context[context.callbackQuery ? 'edit' : 'send']?.({
338
- text: '<blockquote><b>❗️Произошла ошибка при добавлении аккаунта</b></blockquote>\n\n' + error.message,
339
- parse_mode: 'HTML',
340
- })
341
- }
342
- }
343
-
344
- @CommandD({ name: 'addaccountbystringsession', argsMethod: 'parameterized' })
345
- export class AddAccountByStringSessionCommand extends Command {
346
- public async execute(
347
- context: CommandContext,
348
- @CommandStorageArgument('stringSession', async ({ context, value }) => {
349
- if (value) {
350
- try {
351
- // Создаем уникальный ID для сессии
352
- const sessionId = `string-session-${Date.now()}`
353
-
354
- // Добавляем сессию через SessionManager с переданной строкой
355
- const session = await EvogramGramJS.sessionManager.addSession({
356
- sessionId: sessionId,
357
- sessionString: value,
358
- logging: {
359
- enabled: true,
360
- logsDirectory: './logs',
361
- },
362
- })
363
-
364
- await context.storage.set('session', session.sessionId)
365
-
366
- // Проверяем, что сессия валидна и авторизована
367
- const user = await session.client.getMe()
368
-
369
- if (!user) {
370
- throw new Error('Не удалось получить данные пользователя. Проверьте StringSession.')
371
- }
372
-
373
- // Сохраняем сессию в базу данных
374
- try {
375
- let avatarBuffer = await session.client.downloadProfilePhoto('me')
376
- let avatarUrl: string | undefined
377
-
378
- if (avatarBuffer) {
379
- const ImageUploadService = (await import('../services/ImageUploadService')).ImageUploadService
380
- avatarUrl = await ImageUploadService.uploadToImgbox(Buffer.isBuffer(avatarBuffer) ? avatarBuffer : Buffer.from(avatarBuffer)).catch(() => undefined)
381
- }
382
-
383
- await EvogramGramJS.databaseService.saveSession({
384
- sessionId: session.sessionId,
385
- apiId: session.client.apiId,
386
- apiHash: session.client.apiHash,
387
- userId: Number(user.id),
388
- username: user.username,
389
- firstName: user.firstName,
390
- lastName: user.lastName,
391
- phoneNumber: user.phone,
392
- sessionString: value,
393
- avatarUrl,
394
- })
395
- } catch (saveError) {
396
- console.error('Ошибка при сохранении сессии в БД:', saveError)
397
- // Продолжаем выполнение, даже если не удалось сохранить аватар
398
- }
399
-
400
- return value
401
- } catch (error: any) {
402
- context.state.command = undefined
403
- await context.storage.clearAll()
404
-
405
- //@ts-ignore
406
- context[context.callbackQuery ? 'edit' : 'send']?.({
407
- text: '<blockquote><b>❗️Произошла ошибка при добавлении аккаунта</b></blockquote>\n\n' + '<i>Проверьте корректность StringSession. Убедитесь, что строка сессии действительна.</i>\n\n' + `<code>${error.message}</code>`,
408
- parse_mode: 'HTML',
409
- })
410
-
411
- return null
412
- }
413
- } else {
414
- //@ts-ignore
415
- context[context.callbackQuery ? 'edit' : 'send']?.({
416
- text: '<blockquote><b>➕ Добавление аккаунта через StringSession</b></blockquote>\n\n' + '<i>Отправьте StringSession в следующем сообщении</i>\n\n' + 'ℹ️ StringSession - это строка, которая содержит данные авторизации вашего аккаунта. ' + 'Вы можете получить её через официальную библиотеку Telegram или сторонние инструменты.',
417
- parse_mode: 'HTML',
418
- })
419
- }
420
- })
421
- stringSession: string,
422
- ) {
423
- const session = EvogramGramJS.sessionManager.getSession(await context.storage.get('session'))!
424
-
425
- const user = await session.client.getMe()
426
- context.send(`✅ Вы успешно добавили аккаунт @${user.username || user.firstName || 'unknown'}`)
427
- await context.storage.clearAll()
428
- }
429
-
430
- @CommandUpdate('message')
431
- async handleMessage(context: CommandContext, message: MessageContext) {
432
- if (!message?.text) return
433
-
434
- await context.edit('⏳').catch(() => {})
435
- await message.delete().catch(() => {})
436
-
437
- if (!(await context.storage.get('stringSession'))) {
438
- context.redirect(AddAccountByStringSessionCommand, { stringSession: message.text })
439
- }
440
- }
441
-
442
- onError(context: CommandContext, error: Error) {
443
- //@ts-ignore
444
- context[context.callbackQuery ? 'edit' : 'send']?.({
445
- text: '<blockquote><b>❗️Произошла ошибка при добавлении аккаунта</b></blockquote>\n\n' + error.message,
446
- parse_mode: 'HTML',
447
- })
448
- }
449
- }
@@ -1,2 +0,0 @@
1
- export * from './Accounts.command'
2
- export * from './AddAccount.command'
@@ -1,75 +0,0 @@
1
- import { DataSourceOptions } from 'typeorm'
2
- import { Session } from '../entities/Session.entity'
3
- import { SessionEventLog } from '../entities/SessionEventLog.entity'
4
-
5
- /**
6
- * Конфигурация базы данных
7
- */
8
- export interface DatabaseConfig {
9
- /** Тип базы данных */
10
- type?: 'sqlite' | 'postgres' | 'mysql' | 'mariadb'
11
- /** Путь к файлу БД (для SQLite) или строка подключения */
12
- database?: string
13
- /** Хост БД (для PostgreSQL/MySQL) */
14
- host?: string
15
- /** Порт БД (для PostgreSQL/MySQL) */
16
- port?: number
17
- /** Имя пользователя БД */
18
- username?: string
19
- /** Пароль БД */
20
- password?: string
21
- /** Включить синхронизацию схемы (только для разработки) */
22
- synchronize?: boolean
23
- /** Включить логирование SQL запросов */
24
- logging?: boolean
25
- }
26
-
27
- /**
28
- * Создает конфигурацию DataSource для TypeORM
29
- */
30
- export function createDataSourceOptions(config: DatabaseConfig = {}): DataSourceOptions {
31
- const { type = 'sqlite', database = './data/evogram.db', host, port, username, password, synchronize = false, logging = false } = config
32
-
33
- const baseOptions: DataSourceOptions = {
34
- type: type as any,
35
- entities: [Session, SessionEventLog],
36
- synchronize,
37
- logging,
38
- }
39
-
40
- if (type === 'sqlite') {
41
- // Для SQLite используем специальную конфигурацию
42
- const sqliteOptions: any = {
43
- ...baseOptions,
44
- type: 'better-sqlite3',
45
- database,
46
- }
47
- return sqliteOptions as DataSourceOptions
48
- }
49
-
50
- if (type === 'postgres') {
51
- return {
52
- ...baseOptions,
53
- type: 'postgres',
54
- host: host || 'localhost',
55
- port: port || 5432,
56
- username,
57
- password,
58
- database: database || 'evogram',
59
- } as DataSourceOptions
60
- }
61
-
62
- if (type === 'mysql' || type === 'mariadb') {
63
- return {
64
- ...baseOptions,
65
- type: type === 'mariadb' ? 'mariadb' : 'mysql',
66
- host: host || 'localhost',
67
- port: port || 3306,
68
- username,
69
- password,
70
- database: database || 'evogram',
71
- } as DataSourceOptions
72
- }
73
-
74
- return baseOptions
75
- }
@@ -1,58 +0,0 @@
1
- import { Column, CreateDateColumn, Entity, OneToMany, PrimaryColumn } from 'typeorm'
2
- import { SessionEventLog } from './SessionEventLog.entity'
3
-
4
- /**
5
- * Сущность сессии Telegram в базе данных
6
- */
7
- @Entity('sessions')
8
- export class Session {
9
- /** Уникальный идентификатор сессии */
10
- @PrimaryColumn({ type: 'varchar', length: 255 })
11
- sessionId!: string
12
-
13
- /** API ID из Telegram */
14
- @Column({ type: 'integer', nullable: true })
15
- apiId?: number
16
-
17
- /** API Hash из Telegram */
18
- @Column({ type: 'varchar', length: 255, nullable: true })
19
- apiHash?: string
20
-
21
- @Column({ type: 'bigint' })
22
- userId!: number
23
-
24
- @Column({ type: 'varchar', length: 255, nullable: true })
25
- username?: string
26
-
27
- @Column({ type: 'varchar', length: 255, nullable: true })
28
- firstName?: string
29
-
30
- @Column({ type: 'varchar', length: 255, nullable: true })
31
- lastName?: string
32
-
33
- @Column({ type: 'varchar', length: 255, nullable: true })
34
- phoneNumber?: string
35
-
36
- @Column({ type: 'text', nullable: true })
37
- error?: string
38
-
39
- /** Строка сессии (зашифрованная) */
40
- @Column({ type: 'text', nullable: true })
41
- sessionString?: string
42
-
43
- /** Дополнительные опции клиента (JSON) */
44
- @Column({ type: 'text', nullable: true })
45
- clientOptions?: string
46
-
47
- /** URL аватарки пользователя */
48
- @Column({ type: 'varchar', length: 500, nullable: true })
49
- avatarUrl?: string
50
-
51
- /** Связанные события сессии */
52
- @OneToMany(() => SessionEventLog, (eventLog) => eventLog.session, { cascade: true })
53
- eventLogs!: SessionEventLog[]
54
-
55
- /** Время создания сессии */
56
- @CreateDateColumn()
57
- createdAt!: Date
58
- }
@@ -1,41 +0,0 @@
1
- import { Column, CreateDateColumn, Entity, JoinColumn, ManyToOne, PrimaryGeneratedColumn } from 'typeorm'
2
- import { Session } from './Session.entity'
3
-
4
- /**
5
- * Сущность для логирования событий сессии
6
- */
7
- @Entity('session_event_logs')
8
- export class SessionEventLog {
9
- /** Уникальный идентификатор записи */
10
- @PrimaryGeneratedColumn()
11
- id!: number
12
-
13
- /** Идентификатор сессии */
14
- @Column({ type: 'varchar', length: 255 })
15
- sessionId!: string
16
-
17
- /** Тип события */
18
- @Column({ type: 'varchar', length: 100 })
19
- eventType!: string
20
-
21
- /** Уровень логирования */
22
- @Column({ type: 'varchar', length: 20, default: 'INFO' })
23
- level!: string
24
-
25
- /** Сообщение события */
26
- @Column({ type: 'text' })
27
- message!: string
28
-
29
- /** Дополнительные данные события (JSON) */
30
- @Column({ type: 'text', nullable: true })
31
- data?: string
32
-
33
- /** Время создания события */
34
- @CreateDateColumn()
35
- createdAt!: Date
36
-
37
- /** Связь с сессией */
38
- @ManyToOne(() => Session, (session) => session.eventLogs, { onDelete: 'CASCADE' })
39
- @JoinColumn({ name: 'sessionId' })
40
- session!: Session
41
- }
package/src/index.ts DELETED
@@ -1,7 +0,0 @@
1
- export * from './EvogramGramJS'
2
- export * from './config/database.config'
3
- export * from './entities/Session.entity'
4
- export * from './entities/SessionEventLog.entity'
5
- export * from './services/DatabaseService'
6
- export * from './types/auth.types'
7
- export * from './types/session.types'