refactor: cleanup unused code and warnings
Some checks failed
CI / Check (pull_request) Has been cancelled
CI / Format (pull_request) Has been cancelled
CI / Clippy (pull_request) Has been cancelled
CI / Build (macos-latest) (pull_request) Has been cancelled
CI / Build (ubuntu-latest) (pull_request) Has been cancelled
CI / Build (windows-latest) (pull_request) Has been cancelled

Comprehensive cleanup of unused methods, dead code, and compiler warnings:

## Removed Methods (15):
- Duplicate delegation methods: is_authenticated, get_typing_text, get_user_name from TdClient
- Obsolete methods: TdClient::init() (duplicated in main.rs)
- Unused getters: UserCache::{get_username, get_name, get_user_id_by_chat}
- Unused builder methods: MessageBuilder::{edited, add_reaction}
- Unused utility: ChatState::is_normal()
- Dead code: HotkeysConfig::{matches, key_matches} (kept for tests)
- Unused method: UserCache::register_private_chat()
- Getter replaced with direct field access: MessageInfo::edit_date()

## Removed Module:
- error.rs - Unused error handling module (TeletuiError, ErrorVariant, IntoTeletuiError)

## Removed Constants (8):
- EMOJI_PICKER_COLUMNS, EMOJI_PICKER_ROWS, MAX_INPUT_HEIGHT
- MIN_TERMINAL_WIDTH, MIN_TERMINAL_HEIGHT
- TDLIB_CHAT_LIMIT, MAX_USERNAME_DISPLAY_LENGTH, MESSAGE_TEXT_INDENT

## Fixed Warnings:
- Removed unused imports (8 instances)
- Fixed unreachable patterns (10 instances)
- Fixed irrefutable if let patterns (2 instances)
- Fixed unused variables (1 instance)
- Removed dead_code annotations where appropriate

## Improvements:
- Integrated Config::load_credentials() into TdClient::new() for better credential management
- Replaced edit_date() getter with direct field access (message.metadata.edit_date)
- Updated tests to use direct field access instead of removed getters

## Test Results:
All tests passing: 499 passed, 0 failed

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
Mikhail Kilin
2026-02-01 18:57:55 +03:00
parent f1a26b906c
commit 2b04b785c0
20 changed files with 57 additions and 292 deletions

View File

@@ -62,18 +62,28 @@ pub struct TdClient {
impl TdClient {
/// Creates a new TDLib client instance.
///
/// Reads API credentials from environment variables `API_ID` and `API_HASH`.
/// Reads API credentials from:
/// 1. ~/.config/tele-tui/credentials file
/// 2. Environment variables `API_ID` and `API_HASH` (fallback)
///
/// Initializes all managers and sets initial network state to Connecting.
///
/// # Returns
///
/// A new `TdClient` instance ready for authentication.
pub fn new() -> Self {
let api_id = env::var("API_ID")
.unwrap_or_else(|_| "0".to_string())
.parse()
.unwrap_or(0);
let api_hash = env::var("API_HASH").unwrap_or_default();
// Пробуем загрузить credentials из Config (файл или env)
let (api_id, api_hash) = crate::config::Config::load_credentials()
.unwrap_or_else(|_| {
// Fallback на прямое чтение из env (старое поведение)
let api_id = env::var("API_ID")
.unwrap_or_else(|_| "0".to_string())
.parse()
.unwrap_or(0);
let api_hash = env::var("API_HASH").unwrap_or_default();
(api_id, api_hash)
});
let client_id = tdlib_rs::create_client();
Self {
@@ -91,15 +101,6 @@ impl TdClient {
// Делегирование к auth
/// Checks if the user is authenticated.
///
/// # Returns
///
/// `true` if authentication is complete, `false` otherwise.
pub fn is_authenticated(&self) -> bool {
self.auth.is_authenticated()
}
/// Sends phone number for authentication.
///
/// This is the first step of the authentication flow.
@@ -213,10 +214,6 @@ impl TdClient {
self.chat_manager.send_chat_action(chat_id, action).await
}
pub fn get_typing_text(&self) -> Option<String> {
self.chat_manager.get_typing_text()
}
pub fn clear_stale_typing_status(&mut self) -> bool {
self.chat_manager.clear_stale_typing_status()
}
@@ -318,10 +315,6 @@ impl TdClient {
}
// Делегирование к user_cache
pub async fn get_user_name(&self, user_id: UserId) -> String {
self.user_cache.get_user_name(user_id).await
}
pub fn get_user_status_by_chat_id(&self, chat_id: ChatId) -> Option<&UserOnlineStatus> {
self.user_cache.get_status_by_chat_id(chat_id)
}
@@ -360,7 +353,6 @@ impl TdClient {
pub async fn get_me(&self) -> Result<i64, String> {
match functions::get_me(self.client_id).await {
Ok(tdlib_rs::enums::User::User(user)) => Ok(user.id),
Ok(_) => Err("Неожиданный тип пользователя".to_string()),
Err(e) => Err(format!("Ошибка получения текущего пользователя: {:?}", e)),
}
}
@@ -451,33 +443,6 @@ impl TdClient {
&mut self.user_cache
}
/// Инициализация TDLib
pub async fn init(&mut self) -> Result<(), String> {
let result = functions::set_tdlib_parameters(
false, // use_test_dc
"tdlib_data".to_string(), // database_directory
"".to_string(), // files_directory
"".to_string(), // database_encryption_key
true, // use_file_database
true, // use_chat_info_database
true, // use_message_database
false, // use_secret_chats
self.api_id, // api_id
self.api_hash.clone(), // api_hash
"en".to_string(), // system_language_code
"Desktop".to_string(), // device_model
"".to_string(), // system_version
env!("CARGO_PKG_VERSION").to_string(), // application_version
self.client_id,
)
.await;
match result {
Ok(_) => Ok(()),
Err(e) => Err(format!("Failed to set TDLib parameters: {:?}", e)),
}
}
/// Обрабатываем одно обновление от TDLib
pub fn handle_update(&mut self, update: Update) {
match update {
@@ -845,10 +810,7 @@ impl TdClient {
fn add_or_update_chat(&mut self, td_chat_enum: &TdChat) {
// Pattern match to get inner Chat struct
let td_chat = match td_chat_enum {
TdChat::Chat(chat) => chat,
_ => return,
};
let TdChat::Chat(td_chat) = td_chat_enum;
// Пропускаем удалённые аккаунты
if td_chat.title == "Deleted Account" || td_chat.title.is_empty() {