import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import type { TelegramConfig } from './types.js';
interface StoredTelegramConfig extends TelegramConfig {
updatedAt: string;
}
const CONFIG_DIR = path.join(os.homedir(), '.config', 'telegram-brief');
const CONFIG_PATH = path.join(CONFIG_DIR, 'config.json');
function ensureConfigDir(): void {
if (!fs.existsSync(CONFIG_DIR)) {
fs.mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
}
}
export function getConfigPath(): string {
return CONFIG_PATH;
}
export function readStoredConfig(): TelegramConfig | null {
if (!fs.existsSync(CONFIG_PATH)) {
return null;
}
try {
const raw = fs.readFileSync(CONFIG_PATH, 'utf-8');
const parsed = JSON.parse(raw) as StoredTelegramConfig;
if (
typeof parsed.apiId !== 'number' ||
typeof parsed.apiHash !== 'string' ||
typeof parsed.phone !== 'string' ||
typeof parsed.session !== 'string'
) {
return null;
}
return {
apiId: parsed.apiId,
apiHash: parsed.apiHash,
phone: parsed.phone,
session: parsed.session,
};
} catch {
return null;
}
}
export function loadTelegramConfig(): TelegramConfig | null {
const stored = readStoredConfig();
const envApiId = process.env.TELEGRAM_API_ID;
const envApiHash = process.env.TELEGRAM_API_HASH;
const envPhone = process.env.TELEGRAM_PHONE;
const envSession = process.env.TELEGRAM_SESSION;
const apiIdRaw = envApiId ?? (stored ? String(stored.apiId) : undefined);
const apiHash = envApiHash ?? stored?.apiHash;
const phone = envPhone ?? stored?.phone;
const session = envSession ?? stored?.session ?? '';
if (!apiIdRaw || !apiHash || !phone) {
return null;
}
const apiId = parseInt(apiIdRaw, 10);
if (Number.isNaN(apiId)) {
return null;
}
return {
apiId,
apiHash,
phone,
session,
};
}
export function saveTelegramConfig(config: TelegramConfig): void {
ensureConfigDir();
const payload: StoredTelegramConfig = {
...config,
updatedAt: new Date().toISOString(),
};
fs.writeFileSync(CONFIG_PATH, `${JSON.stringify(payload, null, 2)}\n`, {
encoding: 'utf-8',
mode: 0o600,
});
fs.chmodSync(CONFIG_PATH, 0o600);
}