use crate::error::{OpenteleError, Result};
use crate::td::auth::{AuthKey, AUTH_KEY_LEN};
use crate::utils::{replace_file, temporary_sibling};
use rusqlite::{params, Connection};
use std::path::Path;
const TELETHON_SCHEMA_VERSION: i64 = 8;
pub struct TelethonSession;
impl TelethonSession {
pub fn save_to_sqlite(
auth_key: &AuthKey,
dc_id: u32,
server_address: &str,
port: u32,
db_path: &Path,
) -> Result<()> {
validate_dc(dc_id)?;
let temporary = temporary_sibling(db_path)?;
let result = (|| -> Result<()> {
let mut db = Connection::open(&temporary)?;
let tx = db.transaction()?;
tx.execute_batch(
"CREATE TABLE version (version INTEGER PRIMARY KEY);
CREATE TABLE sessions (
dc_id INTEGER PRIMARY KEY,
server_address TEXT,
port INTEGER,
auth_key BLOB,
takeout_id INTEGER,
tmp_auth_key BLOB
);
CREATE TABLE entities (
id INTEGER PRIMARY KEY,
hash INTEGER NOT NULL,
username TEXT,
phone INTEGER,
name TEXT,
date INTEGER
);
CREATE TABLE sent_files (
md5_digest BLOB,
file_size INTEGER,
type INTEGER,
id INTEGER,
hash INTEGER,
PRIMARY KEY(md5_digest, file_size, type)
);
CREATE TABLE update_state (
id INTEGER PRIMARY KEY,
pts INTEGER,
qts INTEGER,
date INTEGER,
seq INTEGER
);",
)?;
tx.execute(
"INSERT INTO version (version) VALUES (?1)",
[TELETHON_SCHEMA_VERSION],
)?;
tx.execute(
"INSERT INTO sessions
(dc_id, server_address, port, auth_key, takeout_id, tmp_auth_key)
VALUES (?1, ?2, ?3, ?4, NULL, NULL)",
params![dc_id, server_address, port, auth_key.as_bytes()],
)?;
tx.commit()?;
drop(db);
replace_file(&temporary, db_path)?;
Ok(())
})();
if result.is_err() {
let _ = std::fs::remove_file(&temporary);
}
result
}
pub fn read_telethon_session(session_path: &Path) -> Result<(Vec<u8>, u32)> {
if !session_path.is_file() {
return Err(OpenteleError::Io(std::io::Error::new(
std::io::ErrorKind::NotFound,
format!("session file {} does not exist", session_path.display()),
)));
}
let conn = Connection::open(session_path)?;
let schema_version: i64 = conn
.query_row("SELECT version FROM version LIMIT 1", [], |row| row.get(0))
.map_err(|error| {
OpenteleError::InvalidTData(format!(
"Telethon session has no readable schema version: {error}"
))
})?;
if schema_version != TELETHON_SCHEMA_VERSION {
return Err(OpenteleError::Unsupported(format!(
"Telethon schema version {schema_version}; expected {TELETHON_SCHEMA_VERSION}"
)));
}
let (dc_id, auth_key): (i64, Vec<u8>) = conn
.query_row("SELECT dc_id, auth_key FROM sessions LIMIT 1", [], |row| {
Ok((row.get(0)?, row.get(1)?))
})
.map_err(|error| match error {
rusqlite::Error::QueryReturnedNoRows => OpenteleError::InvalidTData(
"Telethon session contains no authorization row".into(),
),
other => other.into(),
})?;
let dc_id = u32::try_from(dc_id)
.map_err(|_| OpenteleError::InvalidTData("Telethon DC ID is negative".into()))?;
validate_dc(dc_id)?;
if auth_key.len() != AUTH_KEY_LEN {
return Err(OpenteleError::InvalidTData(format!(
"Telethon auth key must contain {AUTH_KEY_LEN} bytes, got {}",
auth_key.len()
)));
}
Ok((auth_key, dc_id))
}
}
fn validate_dc(dc_id: u32) -> Result<()> {
if !(1..=5).contains(&dc_id) {
return Err(OpenteleError::InvalidArgument(format!(
"Telegram data-center ID must be between 1 and 5, got {dc_id}"
)));
}
Ok(())
}