Files
ridebus-admin/backend/scripts/telegram-login.js
Zakhar Timoshenko f7f0b039dd Add Telegram cancellation import functionality with tests and documentation
- Implemented Telegram cancellation parsing logic in `telegramCancellationParser.js`.
- Created unit tests for cancellation parsing in `telegramCancellationParser.test.js`.
- Developed integration tests for Telegram import service in `telegramImport.integration.test.js`.
- Added API tests for Telegram import endpoints in `telegramImportApi.test.js`.
- Introduced service tests for Telegram import logic in `telegramImportService.test.js`.
- Documented the Telegram cancellation import process in `telegram-cancellation-import.md`.
- Built a React component for managing Telegram imports in `TelegramImportPanel.jsx`.
2026-10-03 00:45:41 +03:00

51 lines
2.8 KiB
JavaScript

require('dotenv').config();
const fs = require('node:fs/promises');
const readline = require('node:readline');
const { getTelegramConfig, missingTelegramConfig, assertExternalSessionFile } = require('../src/config/telegram');
const { publicError } = require('../src/services/telegramImportService');
function ask(prompt, hidden = false) {
return new Promise((resolve, reject) => {
const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: true });
rl.question(prompt, answer => { rl.close(); process.stdout.write('\n'); resolve(answer.trim()); });
if (hidden) rl._writeToOutput = () => {};
rl.on('SIGINT', () => { rl.close(); reject(new Error('LOGIN_CANCELLED')); });
});
}
async function main() {
const config = getTelegramConfig();
if (!process.stdin.isTTY) throw new Error('LOGIN_REQUIRES_TERMINAL');
if (missingTelegramConfig(config).length) throw new Error('LOGIN_CONFIG_REQUIRED');
// The operator creates a private directory outside the checkout first.
const file = await assertExternalSessionFile(config.sessionFile);
let session = '';
try { session = (await fs.readFile(file, 'utf8')).trim(); }
catch (error) { if (error.code !== 'ENOENT') throw error; }
const { TelegramClient } = require('teleproto');
const { StringSession } = require('teleproto/sessions');
const { Logger } = require('teleproto/extensions/Logger');
const client = new TelegramClient(new StringSession(session), config.apiId, config.apiHash, { baseLogger: new Logger('none'), connectionRetries: 2 });
try {
await client.start({
phoneNumber: () => ask('Номер отдельного Telegram-аккаунта: '),
phoneCode: () => ask('Код из Telegram: ', true),
password: () => ask('Пароль двухэтапной проверки: ', true),
// Do not register a new account or accept registration terms from this utility.
firstAndLastNames: () => { throw new Error('USE_EXISTING_ACCOUNT'); },
onError: () => true
});
if (!await client.checkAuthorization() || (await client.getMe()).bot) throw new Error('USER_ACCOUNT_REQUIRED');
const handle = await fs.open(file, session ? 'w' : 'wx', 0o600);
try { await handle.writeFile(client.session.save()); await handle.sync(); }
finally { await handle.close(); }
console.log('Авторизация сохранена в защищённый файл. Теперь можно включить TELEGRAM_IMPORT_ENABLED=true.');
} finally { await client.destroy(); }
}
main().catch(error => {
const local = ['LOGIN_CANCELLED', 'LOGIN_REQUIRES_TERMINAL', 'LOGIN_CONFIG_REQUIRED', 'USE_EXISTING_ACCOUNT'];
console.error(`Авторизация не завершена (${local.includes(error.message) ? error.message : publicError(error)}).`);
process.exitCode = 1;
});