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
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:
@@ -1,10 +1,9 @@
|
||||
use crate::constants::TDLIB_CHAT_LIMIT;
|
||||
use crate::types::{ChatId, UserId};
|
||||
use std::time::Instant;
|
||||
use tdlib_rs::enums::{ChatAction, ChatList, ChatType};
|
||||
use tdlib_rs::functions;
|
||||
|
||||
use super::types::{ChatInfo, FolderInfo, MessageInfo, ProfileInfo};
|
||||
use super::types::{ChatInfo, FolderInfo, ProfileInfo};
|
||||
|
||||
/// Менеджер чатов TDLib.
|
||||
///
|
||||
@@ -183,10 +182,7 @@ impl ChatManager {
|
||||
Err(e) => return Err(format!("Ошибка получения чата: {:?}", e)),
|
||||
};
|
||||
|
||||
let chat = match chat_enum {
|
||||
tdlib_rs::enums::Chat::Chat(c) => c,
|
||||
_ => return Err("Неожиданный тип чата".to_string()),
|
||||
};
|
||||
let tdlib_rs::enums::Chat::Chat(chat) = chat_enum;
|
||||
|
||||
let chat_type_str = match &chat.r#type {
|
||||
ChatType::Private(_) => "Личный чат",
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use crate::constants::{MAX_MESSAGES_IN_CHAT, TDLIB_MESSAGE_LIMIT};
|
||||
use crate::types::{ChatId, MessageId};
|
||||
use tdlib_rs::enums::{ChatAction, InputMessageContent, InputMessageReplyTo, MessageContent, MessageSender, SearchMessagesFilter, TextParseMode};
|
||||
use tdlib_rs::enums::{InputMessageContent, InputMessageReplyTo, MessageContent, MessageSender, SearchMessagesFilter, TextParseMode};
|
||||
use tdlib_rs::functions;
|
||||
use tdlib_rs::types::{Chat as TdChat, FormattedText, InputMessageReplyToMessage, InputMessageText, Message as TdMessage, TextEntity, TextParseModeMarkdown};
|
||||
use tdlib_rs::types::{FormattedText, InputMessageReplyToMessage, InputMessageText, Message as TdMessage, TextParseModeMarkdown};
|
||||
|
||||
use super::types::{ForwardInfo, MessageBuilder, MessageInfo, ReactionInfo, ReplyInfo};
|
||||
|
||||
@@ -178,7 +178,6 @@ impl MessageManager {
|
||||
sleep(Duration::from_millis(200)).await;
|
||||
}
|
||||
}
|
||||
Ok(_) => return Err("Неожиданный тип сообщений".to_string()),
|
||||
Err(e) => return Err(format!("Ошибка загрузки истории: {:?}", e)),
|
||||
}
|
||||
}
|
||||
@@ -237,7 +236,6 @@ impl MessageManager {
|
||||
}
|
||||
Ok(messages)
|
||||
}
|
||||
Ok(_) => Err("Неожиданный тип сообщений".to_string()),
|
||||
Err(e) => Err(format!("Ошибка загрузки старых сообщений: {:?}", e)),
|
||||
}
|
||||
}
|
||||
@@ -286,7 +284,6 @@ impl MessageManager {
|
||||
}
|
||||
Ok(pinned_messages)
|
||||
}
|
||||
Ok(_) => Err("Неожиданный тип результата поиска".to_string()),
|
||||
Err(e) => Err(format!("Ошибка загрузки закреплённых: {:?}", e)),
|
||||
}
|
||||
}
|
||||
@@ -362,7 +359,6 @@ impl MessageManager {
|
||||
}
|
||||
Ok(search_results)
|
||||
}
|
||||
Ok(_) => Err("Неожиданный тип результата поиска".to_string()),
|
||||
Err(e) => Err(format!("Ошибка поиска: {:?}", e)),
|
||||
}
|
||||
}
|
||||
@@ -464,10 +460,9 @@ impl MessageManager {
|
||||
if let Some(reply) = reply_info {
|
||||
msg_info.interactions.reply_to = Some(reply);
|
||||
}
|
||||
|
||||
|
||||
Ok(msg_info)
|
||||
}
|
||||
Ok(_) => Err("Неожиданный тип сообщения".to_string()),
|
||||
Err(e) => Err(format!("Ошибка отправки сообщения: {:?}", e)),
|
||||
}
|
||||
}
|
||||
@@ -523,7 +518,6 @@ impl MessageManager {
|
||||
.convert_message(&msg)
|
||||
.await
|
||||
.ok_or_else(|| "Не удалось конвертировать отредактированное сообщение".to_string()),
|
||||
Ok(_) => Err("Неожиданный тип сообщения".to_string()),
|
||||
Err(e) => Err(format!("Ошибка редактирования: {:?}", e)),
|
||||
}
|
||||
}
|
||||
@@ -832,8 +826,8 @@ impl MessageManager {
|
||||
if let Ok(original_msg_enum) =
|
||||
functions::get_message(chat_id.as_i64(), message_id.as_i64(), self.client_id).await
|
||||
{
|
||||
if let tdlib_rs::enums::Message::Message(original_msg) = original_msg_enum {
|
||||
if let Some(orig_info) = self.convert_message(&original_msg).await {
|
||||
let tdlib_rs::enums::Message::Message(original_msg) = original_msg_enum;
|
||||
if let Some(orig_info) = self.convert_message(&original_msg).await {
|
||||
// Update the reply info
|
||||
for msg in &mut self.current_chat_messages {
|
||||
if let Some(ref mut reply) = msg.interactions.reply_to {
|
||||
@@ -848,7 +842,6 @@ impl MessageManager {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,8 +11,7 @@ pub mod users;
|
||||
pub use auth::AuthState;
|
||||
pub use client::TdClient;
|
||||
pub use types::{
|
||||
ChatInfo, FolderInfo, ForwardInfo, MessageBuilder, MessageInfo, NetworkState, ProfileInfo,
|
||||
ReactionInfo, ReplyInfo, UserOnlineStatus,
|
||||
ChatInfo, MessageBuilder, MessageInfo, NetworkState, ProfileInfo, ReplyInfo, UserOnlineStatus,
|
||||
};
|
||||
|
||||
// Re-export ChatAction для удобства
|
||||
|
||||
@@ -70,7 +70,7 @@ impl ReactionManager {
|
||||
) -> Result<Vec<String>, String> {
|
||||
// Получаем сообщение
|
||||
let msg_result = functions::get_message(chat_id.as_i64(), message_id.as_i64(), self.client_id).await;
|
||||
let msg = match msg_result {
|
||||
let _msg = match msg_result {
|
||||
Ok(m) => m,
|
||||
Err(e) => return Err(format!("Ошибка получения сообщения: {:?}", e)),
|
||||
};
|
||||
|
||||
@@ -160,10 +160,6 @@ impl MessageInfo {
|
||||
self.metadata.date
|
||||
}
|
||||
|
||||
pub fn edit_date(&self) -> i32 {
|
||||
self.metadata.edit_date
|
||||
}
|
||||
|
||||
pub fn is_edited(&self) -> bool {
|
||||
self.metadata.edit_date > 0
|
||||
}
|
||||
@@ -308,12 +304,6 @@ impl MessageBuilder {
|
||||
self
|
||||
}
|
||||
|
||||
/// Пометить сообщение как отредактированное (edit_date = date + 60)
|
||||
pub fn edited(mut self) -> Self {
|
||||
self.edit_date = self.date + 60;
|
||||
self
|
||||
}
|
||||
|
||||
/// Пометить сообщение как прочитанное
|
||||
pub fn read(mut self) -> Self {
|
||||
self.is_read = true;
|
||||
@@ -362,12 +352,6 @@ impl MessageBuilder {
|
||||
self
|
||||
}
|
||||
|
||||
/// Добавить одну реакцию
|
||||
pub fn add_reaction(mut self, reaction: ReactionInfo) -> Self {
|
||||
self.reactions.push(reaction);
|
||||
self
|
||||
}
|
||||
|
||||
/// Построить MessageInfo из данных builder'а
|
||||
pub fn build(self) -> MessageInfo {
|
||||
MessageInfo::new(
|
||||
@@ -430,11 +414,11 @@ mod tests {
|
||||
let message = MessageBuilder::new(MessageId::new(789))
|
||||
.text("Original text")
|
||||
.date(1640000000)
|
||||
.edited()
|
||||
.edit_date(1640000060)
|
||||
.build();
|
||||
|
||||
assert!(message.is_edited());
|
||||
assert_eq!(message.edit_date(), 1640000060);
|
||||
assert_eq!(message.metadata.edit_date, 1640000060);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -464,7 +448,7 @@ mod tests {
|
||||
|
||||
let message = MessageBuilder::new(MessageId::new(300))
|
||||
.text("Cool message")
|
||||
.add_reaction(reaction.clone())
|
||||
.reactions(vec![reaction.clone()])
|
||||
.build();
|
||||
|
||||
assert_eq!(message.reactions().len(), 1);
|
||||
|
||||
@@ -152,21 +152,6 @@ impl UserCache {
|
||||
}
|
||||
}
|
||||
|
||||
/// Получить username пользователя
|
||||
pub fn get_username(&mut self, user_id: &UserId) -> Option<&String> {
|
||||
self.user_usernames.get(user_id)
|
||||
}
|
||||
|
||||
/// Получить имя пользователя
|
||||
pub fn get_name(&mut self, user_id: &UserId) -> Option<&String> {
|
||||
self.user_names.get(user_id)
|
||||
}
|
||||
|
||||
/// Получить user_id по chat_id
|
||||
pub fn get_user_id_by_chat(&self, chat_id: ChatId) -> Option<UserId> {
|
||||
self.chat_user_ids.get(&chat_id).copied()
|
||||
}
|
||||
|
||||
/// Получить статус пользователя по chat_id
|
||||
pub fn get_status_by_chat_id(&self, chat_id: ChatId) -> Option<&UserOnlineStatus> {
|
||||
let user_id = self.chat_user_ids.get(&chat_id)?;
|
||||
@@ -181,21 +166,20 @@ impl UserCache {
|
||||
///
|
||||
/// * `user_enum` - Обновление пользователя от TDLib
|
||||
pub fn handle_user_update(&mut self, user_enum: &User) {
|
||||
if let User::User(user) = user_enum {
|
||||
let user_id = user.id;
|
||||
let User::User(user) = user_enum;
|
||||
let user_id = user.id;
|
||||
|
||||
// Сохраняем username
|
||||
if let Some(username) = user.usernames.as_ref().map(|u| u.editable_username.clone()) {
|
||||
self.user_usernames.insert(UserId::new(user_id), username);
|
||||
}
|
||||
|
||||
// Сохраняем имя
|
||||
let display_name = format!("{} {}", user.first_name, user.last_name).trim().to_string();
|
||||
self.user_names.insert(UserId::new(user_id), display_name);
|
||||
|
||||
// Обновляем статус
|
||||
self.update_status(UserId::new(user_id), &user.status);
|
||||
// Сохраняем username
|
||||
if let Some(username) = user.usernames.as_ref().map(|u| u.editable_username.clone()) {
|
||||
self.user_usernames.insert(UserId::new(user_id), username);
|
||||
}
|
||||
|
||||
// Сохраняем имя
|
||||
let display_name = format!("{} {}", user.first_name, user.last_name).trim().to_string();
|
||||
self.user_names.insert(UserId::new(user_id), display_name);
|
||||
|
||||
// Обновляем статус
|
||||
self.update_status(UserId::new(user_id), &user.status);
|
||||
}
|
||||
|
||||
/// Обновляет онлайн-статус пользователя.
|
||||
@@ -216,11 +200,6 @@ impl UserCache {
|
||||
self.user_statuses.insert(user_id, online_status);
|
||||
}
|
||||
|
||||
/// Сохранить связь chat_id -> user_id
|
||||
pub fn register_private_chat(&mut self, chat_id: ChatId, user_id: UserId) {
|
||||
self.chat_user_ids.insert(chat_id, user_id);
|
||||
}
|
||||
|
||||
/// Получает имя пользователя из кэша или загружает из TDLib.
|
||||
///
|
||||
/// Сначала проверяет кэш, затем при необходимости загружает из API.
|
||||
|
||||
Reference in New Issue
Block a user