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
package/lib/test.js
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
const tslib_1 = require("tslib");
|
|
4
|
+
const path = tslib_1.__importStar(require("path"));
|
|
5
|
+
const QRCode = tslib_1.__importStar(require("qrcode"));
|
|
6
|
+
const telegram_1 = require("telegram");
|
|
7
|
+
const EvogramGramJS_1 = require("./EvogramGramJS");
|
|
8
|
+
const ImageUploadService_1 = require("./services/ImageUploadService");
|
|
9
|
+
/**
|
|
10
|
+
* Пример авторизации через QR-код
|
|
11
|
+
*/
|
|
12
|
+
function authWithQRCode() {
|
|
13
|
+
return tslib_1.__awaiter(this, void 0, void 0, function* () {
|
|
14
|
+
EvogramGramJS_1.EvogramGramJS.initialize(29997404, '475e53e15bcb402f3a218e1141a585cf', {
|
|
15
|
+
type: 'sqlite',
|
|
16
|
+
database: './evogramjs.sqlite',
|
|
17
|
+
synchronize: true,
|
|
18
|
+
});
|
|
19
|
+
// Убедитесь, что EvogramGramJS инициализирован перед использованием
|
|
20
|
+
// EvogramGramJS.initialize(apiId, apiHash, databaseConfig)
|
|
21
|
+
const sessionId = `qr-auth-${Date.now()}`;
|
|
22
|
+
try {
|
|
23
|
+
// Создаем новую сессию
|
|
24
|
+
const session = yield EvogramGramJS_1.EvogramGramJS.sessionManager.addSession({
|
|
25
|
+
sessionId,
|
|
26
|
+
logging: {
|
|
27
|
+
enabled: true,
|
|
28
|
+
logsDirectory: './logs',
|
|
29
|
+
},
|
|
30
|
+
});
|
|
31
|
+
console.log('🔐 Начинаем авторизацию через QR-код...');
|
|
32
|
+
// Получаем API credentials из клиента
|
|
33
|
+
const apiCredentials = {
|
|
34
|
+
apiId: session.client.apiId,
|
|
35
|
+
apiHash: session.client.apiHash,
|
|
36
|
+
};
|
|
37
|
+
// Выполняем авторизацию через QR-код
|
|
38
|
+
const user = yield session.client.signInUserWithQrCode(apiCredentials, {
|
|
39
|
+
qrCode: (qrCode) => tslib_1.__awaiter(this, void 0, void 0, function* () {
|
|
40
|
+
// Преобразуем токен в URL для сканирования
|
|
41
|
+
const qrToken = qrCode.token.toString('base64url');
|
|
42
|
+
const qrUrl = `tg://login?token=${qrToken}`;
|
|
43
|
+
console.log('\n📱 Отсканируйте QR-код в приложении Telegram:');
|
|
44
|
+
console.log(`\n🔗 URL: ${qrUrl}`);
|
|
45
|
+
console.log(`\n⏱️ QR-код действителен до: ${new Date(Date.now() + qrCode.expires * 1000).toLocaleString()}`);
|
|
46
|
+
try {
|
|
47
|
+
// Генерируем QR-код для терминала
|
|
48
|
+
const qrCodeTerminal = yield QRCode.toString(qrUrl, { type: 'terminal', small: true });
|
|
49
|
+
console.log('\n📱 QR-код (терминал):');
|
|
50
|
+
console.log(qrCodeTerminal);
|
|
51
|
+
// Генерируем QR-код как изображение PNG
|
|
52
|
+
const qrCodeFileName = `qr-code-${sessionId}.png`;
|
|
53
|
+
const qrCodeFilePath = path.join(process.cwd(), qrCodeFileName);
|
|
54
|
+
yield QRCode.toFile(qrCodeFilePath, qrUrl, {
|
|
55
|
+
type: 'png',
|
|
56
|
+
width: 500,
|
|
57
|
+
margin: 2,
|
|
58
|
+
color: {
|
|
59
|
+
dark: '#000000',
|
|
60
|
+
light: '#FFFFFF',
|
|
61
|
+
},
|
|
62
|
+
});
|
|
63
|
+
console.log(`\n💾 QR-код сохранен в файл: ${qrCodeFilePath}`);
|
|
64
|
+
console.log(`\n💡 Откройте файл и отсканируйте QR-код в приложении Telegram`);
|
|
65
|
+
}
|
|
66
|
+
catch (error) {
|
|
67
|
+
console.error('⚠️ Ошибка при генерации QR-кода:', error);
|
|
68
|
+
console.log('\n💡 Вы можете использовать URL выше для генерации QR-кода вручную');
|
|
69
|
+
}
|
|
70
|
+
}),
|
|
71
|
+
password: (hint) => tslib_1.__awaiter(this, void 0, void 0, function* () {
|
|
72
|
+
// Если требуется пароль 2FA
|
|
73
|
+
console.log(`\n🔒 Требуется пароль 2FA${hint ? ` (подсказка: ${hint})` : ''}`);
|
|
74
|
+
// В реальном приложении здесь нужно запросить пароль у пользователя
|
|
75
|
+
// Для примера возвращаем пустую строку (это вызовет ошибку)
|
|
76
|
+
throw new Error('Пароль 2FA не предоставлен. Реализуйте логику получения пароля.');
|
|
77
|
+
}),
|
|
78
|
+
onError: (error) => tslib_1.__awaiter(this, void 0, void 0, function* () {
|
|
79
|
+
console.error('\n❌ Ошибка авторизации:', error.message);
|
|
80
|
+
// Возвращаем false, чтобы продолжить попытки авторизации
|
|
81
|
+
return false;
|
|
82
|
+
}),
|
|
83
|
+
});
|
|
84
|
+
console.log('\n✅ Авторизация успешна!');
|
|
85
|
+
// Проверяем, что это реальный пользователь, а не UserEmpty
|
|
86
|
+
if (!(user instanceof telegram_1.Api.User)) {
|
|
87
|
+
throw new Error('Получен неверный тип пользователя');
|
|
88
|
+
}
|
|
89
|
+
console.log(`👤 Пользователь: ${user.firstName || ''} ${user.lastName || ''} (@${user.username || 'без username'})`);
|
|
90
|
+
console.log(`📞 Телефон: ${user.phone || 'не указан'}`);
|
|
91
|
+
// Сохраняем сессию в базу данных
|
|
92
|
+
try {
|
|
93
|
+
let avatarBuffer = yield session.client.downloadProfilePhoto('me');
|
|
94
|
+
let avatarUrl;
|
|
95
|
+
if (avatarBuffer) {
|
|
96
|
+
avatarUrl = yield ImageUploadService_1.ImageUploadService.uploadToImgbox(Buffer.isBuffer(avatarBuffer) ? avatarBuffer : Buffer.from(avatarBuffer));
|
|
97
|
+
}
|
|
98
|
+
yield EvogramGramJS_1.EvogramGramJS.databaseService.saveSession({
|
|
99
|
+
sessionId: session.sessionId,
|
|
100
|
+
apiId: session.client.apiId,
|
|
101
|
+
apiHash: session.client.apiHash,
|
|
102
|
+
userId: Number(user.id),
|
|
103
|
+
username: user.username,
|
|
104
|
+
firstName: user.firstName,
|
|
105
|
+
lastName: user.lastName,
|
|
106
|
+
phoneNumber: user.phone,
|
|
107
|
+
sessionString: session.client.session.save(),
|
|
108
|
+
avatarUrl,
|
|
109
|
+
});
|
|
110
|
+
console.log('💾 Сессия сохранена в базу данных');
|
|
111
|
+
}
|
|
112
|
+
catch (error) {
|
|
113
|
+
console.error('⚠️ Ошибка при сохранении сессии:', error);
|
|
114
|
+
}
|
|
115
|
+
return {
|
|
116
|
+
success: true,
|
|
117
|
+
user,
|
|
118
|
+
sessionId: session.sessionId,
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
catch (error) {
|
|
122
|
+
console.error('\n❌ Критическая ошибка:', error);
|
|
123
|
+
return {
|
|
124
|
+
success: false,
|
|
125
|
+
error: error instanceof Error ? error.message : String(error),
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
// Запускаем авторизацию
|
|
131
|
+
authWithQRCode()
|
|
132
|
+
.then((result) => {
|
|
133
|
+
if (result.success) {
|
|
134
|
+
console.log('\n🎉 Авторизация завершена успешно!');
|
|
135
|
+
}
|
|
136
|
+
else {
|
|
137
|
+
console.log('\n💥 Авторизация не удалась');
|
|
138
|
+
}
|
|
139
|
+
process.exit(0);
|
|
140
|
+
})
|
|
141
|
+
.catch((error) => {
|
|
142
|
+
console.error('💥 Необработанная ошибка:', error);
|
|
143
|
+
process.exit(1);
|
|
144
|
+
});
|