tgt 1.0.0

A simple TUI for Telegram
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
use crate::component_name::ComponentName::Prompt;
use crate::{
    action::Action, app_context::AppContext, app_error::AppError,
    configs::custom::keymap_custom::ActionBinding, event::Event, tg::tg_backend::TgBackend,
    tui::Tui, tui_backend::TuiBackend,
};
use ratatui::layout::Rect;
use std::{collections::HashMap, io, sync::Arc, time::Instant};
use tdlib_rs::enums::ChatList;
use tokio::sync::mpsc::UnboundedSender;

/// Run the main event loop for the application.
/// This function will process events and actions for the tui and the backend.
///
/// # Arguments
/// * `app_context` - An Arc wrapped AppContext struct.
/// * `tui` - A mutable reference to the Tui struct.
/// * `tui_backend` - A mutable reference to the TuiBackend struct.
/// * `tg_backend` - A mutable reference to the TgBackend struct.
///
/// # Returns
/// * `Result<(), AppError>` - An Ok result or an error.
pub async fn run_app(
    app_context: Arc<AppContext>,
    tui: &mut Tui,
    tui_backend: &mut TuiBackend,
    tg_backend: &mut TgBackend,
) -> Result<(), AppError<Action>> {
    tracing::info!("Starting run_app");

    // Clear the terminal and move the cursor to the top left corner
    io::Write::write_all(&mut io::stdout().lock(), b"\x1b[2J\x1b[1;1H").unwrap();

    tg_backend.start();
    tg_backend.set_logging().await;
    tg_backend.handle_authorization_state().await;
    tg_backend.use_quick_ack().await;
    tg_backend.get_me().await;
    tg_backend.load_chats(ChatList::Main, 30).await;

    match handle_cli(Arc::clone(&app_context), tg_backend).await {
        HandleCliOutcome::Quit => {
            futures::join!(quit_cli(tg_backend));
            return Ok(());
        }
        HandleCliOutcome::Logout => {
            futures::join!(log_out(tg_backend));
            return Ok(());
        }
        HandleCliOutcome::Continue => {}
    }

    tg_backend.online().await;
    tg_backend.disable_animated_emoji(true).await;

    tui_backend.enter()?;
    tui.register_action_handler(app_context.action_tx().clone())?;

    // Main loop
    while tg_backend.have_authorization {
        handle_tui_backend_events(Arc::clone(&app_context), tui, tui_backend).await?;
        handle_tg_backend_events(Arc::clone(&app_context), tg_backend).await?;
        handle_app_actions(Arc::clone(&app_context), tui, tui_backend, tg_backend).await?;

        if app_context.quit_acquire() {
            quit_tui(tg_backend, tui_backend).await;
            tracing::info!("Quitting");
            return Ok(());
        }
    }

    Ok(())
}
/// Handle incoming events from the Telegram backend and produce actions if
/// necessary.
///
/// # Arguments
/// * `app_context` - An Arc wrapped AppContext struct.
/// * `tg_backend` - A mutable reference to the TgBackend struct.
///
/// # Returns
/// * `Result<(), AppError>` - An Ok result or an error.
async fn handle_tg_backend_events(
    app_context: Arc<AppContext>,
    tg_backend: &mut TgBackend,
) -> Result<(), AppError<Action>> {
    if let Some(event) = tg_backend.next().await {
        match event {
            Event::LoadChats(chat_list, limit) => {
                app_context
                    .action_tx()
                    .send(Action::LoadChats(chat_list, limit))?;
            }
            Event::SendMessage(message, reply_to) => {
                app_context
                    .action_tx()
                    .send(Action::SendMessage(message, reply_to))?;
            }
            Event::SendMessageEdited(message_id, message) => {
                app_context
                    .action_tx()
                    .send(Action::SendMessageEdited(message_id, message))?;
            }
            Event::GetChatHistory => {
                app_context.action_tx().send(Action::GetChatHistory)?;
            }
            Event::DeleteMessages(message_ids, revoke) => {
                app_context
                    .action_tx()
                    .send(Action::DeleteMessages(message_ids, revoke))?;
            }
            Event::EditMessage(message_id, message) => {
                // It is important to focus the prompt before editing the message.
                // Because the actions are sent to the focused component.
                app_context
                    .action_tx()
                    .send(Action::FocusComponent(Prompt))?;

                app_context
                    .action_tx()
                    .send(Action::EditMessage(message_id, message))?;
            }
            Event::ReplyMessage(message_id, message) => {
                app_context
                    .action_tx()
                    .send(Action::FocusComponent(Prompt))?;

                app_context
                    .action_tx()
                    .send(Action::ReplyMessage(message_id, message))?;
            }
            Event::ViewAllMessages => {
                app_context.action_tx().send(Action::ViewAllMessages)?;
            }
            _ => {}
        }
    }
    Ok(())
}

#[allow(clippy::await_holding_lock)]
/// Handle incoming events from the TUI backend and produce actions if
/// necessary.
///
/// # Arguments
/// * `app_context` - An Arc wrapped AppContext struct.
/// * `tui` - A mutable reference to the Tui struct.
/// * `tui_backend` - A mutable reference to the TuiBackend struct.
///
/// # Returns
/// * `Result<(), AppError>` - An Ok result or an error.
async fn handle_tui_backend_events(
    app_context: Arc<AppContext>,
    tui: &mut Tui,
    tui_backend: &mut TuiBackend,
) -> Result<(), AppError<Action>> {
    if let Some(event) = tui_backend.next().await {
        match event {
            Event::Render => app_context.action_tx().send(Action::Render)?,
            Event::Resize(width, height) => app_context
                .action_tx()
                .send(Action::Resize(width, height))?,
            Event::Key(key, modifiers) => {
                app_context
                    .action_tx()
                    .send(Action::from_key_event(key, modifiers))?;

                // Handle core_window key bindings.
                if let Some(action_binding) = app_context
                    .keymap_config()
                    .core_window
                    .get(&Event::Key(key, modifiers))
                {
                    match action_binding {
                        ActionBinding::Single { action, .. } => {
                            app_context.action_tx().send(action.clone())?;
                            return Ok(());
                        }
                        ActionBinding::Multiple(map_event_action) => {
                            consume_until_single_action(
                                &app_context.action_tx(),
                                tui_backend,
                                map_event_action.clone(),
                            )
                            .await;
                            // We need to return here to avoid sending the
                            // event to the tui. At the moment, the components
                            // are not able to handle multiple events.
                            return Ok(());
                        }
                    }
                }
            }
            Event::Paste(ref text) => app_context.action_tx().send(Action::Paste(text.clone()))?,
            _ => {}
        }

        // Note that sending the event to the tui it will send the event
        // directly to the `CoreWindow` component.
        if let Some(action) = tui.handle_events(Some(event.clone()))? {
            app_context.action_tx().send(action)?
        }
    }
    Ok(())
}
/// Consume events until a single action is produced.
/// This function is used to consume events until a single action is produced
/// from a map of events to actions.
/// This is useful for handling multiple key bindings that produce the same
/// action, or simply to consume events until a single action is produced.
/// The time limit for consuming events is 1 second.
///
/// # Arguments
/// * `action_tx` - An unbounded sender that can send actions.
/// * `tui_backend` - A mutable reference to the `TuiBackend` struct.
/// * `map_event_action` - A map of events to actions.
async fn consume_until_single_action(
    action_tx: &UnboundedSender<Action>,
    tui_backend: &mut TuiBackend,
    map_event_action: HashMap<Event, ActionBinding>,
) {
    let start = Instant::now();
    loop {
        if let Some(event) = tui_backend.next().await {
            if let Some(ActionBinding::Single { action, .. }) = map_event_action.get(&event) {
                action_tx.send(action.clone()).unwrap();
                break;
            }
        }
        if start.elapsed().as_secs() > 1 {
            break;
        }
    }
}
#[allow(clippy::await_holding_lock)]
/// Handle incoming actions from the application.
///
/// # Arguments
/// * `app_context` - An Arc wrapped AppContext struct.
/// * `tui` - A mutable reference to the Tui struct.
/// * `tui_backend` - A mutable reference to the TuiBackend struct.
/// * `tg_backend` - A mutable reference to the TgBackend struct.
///
/// # Returns
/// * `Result<(), AppError>` - An Ok result or an error.
pub async fn handle_app_actions(
    app_context: Arc<AppContext>,
    tui: &mut Tui,
    tui_backend: &mut TuiBackend,
    tg_backend: &mut TgBackend,
) -> Result<(), AppError<Action>> {
    while let Ok(action) = app_context.action_rx().try_recv() {
        match action {
            Action::Render => {
                tui_backend.terminal.draw(|f| {
                    tui.draw(f, f.size()).unwrap();
                })?;
            }
            Action::Resize(width, height) => {
                tui_backend
                    .terminal
                    .resize(Rect::new(0, 0, width, height))?;
                tui_backend.terminal.draw(|f| {
                    tui.draw(f, f.size()).unwrap();
                })?;
            }
            Action::Quit => {
                app_context.quit_store(true);
            }
            Action::LoadChats(chat_list, limit) => {
                tg_backend.load_chats(chat_list.into(), limit).await;
            }
            Action::SendMessage(ref message, ref reply_to) => {
                let _ = tg_backend
                    .send_message(
                        message.to_string(),
                        app_context.tg_context().open_chat_id(),
                        reply_to.clone(),
                    )
                    .await;
            }
            Action::SendMessageEdited(message_id, ref message) => {
                tg_backend
                    .send_message_edited(message_id, message.to_string())
                    .await;
            }
            Action::GetChatHistory => {
                tg_backend
                    .get_chat_history(app_context.tg_context().open_chat_id())
                    .await;
            }
            Action::DeleteMessages(ref message_ids, revoke) => {
                tg_backend
                    .delete_messages(
                        app_context.tg_context().open_chat_id(),
                        message_ids.to_vec(),
                        revoke,
                    )
                    .await;
            }
            Action::ReplyMessage(message_id, ref message) => {
                app_context
                    .tg_context()
                    .set_reply_message(message_id, message.to_string());
            }
            Action::ViewAllMessages => {
                tg_backend.view_all_messages().await;
            }
            _ => {}
        }

        tui.update(action.clone())
    }
    Ok(())
}

/// An enum to represent the outcome of the handle_cli function.
enum HandleCliOutcome {
    /// The application should quit.
    Quit,
    /// The application should continue.
    Continue,
    /// The user should be logged out.
    Logout,
}

#[allow(clippy::await_holding_lock)]
/// Handle the command line arguments.
/// This function will handle the command line arguments.
///
/// # Arguments
/// * `app_context` - An Arc wrapped AppContext struct.
/// * `tui_backend` - A mutable reference to the TuiBackend struct.
/// * `tg_backend` - A mutable reference to the TgBackend struct.
async fn handle_cli(app_context: Arc<AppContext>, tg_backend: &mut TgBackend) -> HandleCliOutcome {
    if app_context.cli_args().telegram_cli().logout() {
        return HandleCliOutcome::Logout;
    }
    if let Some(chat) = app_context.cli_args().telegram_cli().send_message() {
        futures::join!(tg_backend.load_all_chats());

        let [chat_name, message_text] = chat.as_slice() else {
            tracing::error!("Invalid number of arguments for send message");
            println!("Invalid number of arguments for send message");
            return HandleCliOutcome::Quit;
        };
        match tg_backend.search_chats(chat_name.to_string()).await {
            Ok(chat) => {
                tracing::info!("Chat found: {:?}", chat);
                let total_chats = chat.total_count;
                let chats_vec = chat.chat_ids;
                if total_chats == 0 {
                    tracing::error!("No chat found with the name: {}", chat_name);
                    println!("No chat found with the name: {}", chat_name);
                    return HandleCliOutcome::Quit;
                }
                if total_chats > 1 {
                    tracing::error!("Multiple chats found with the name: {}", chat_name);
                    println!("Multiple chats found with the name: {}", chat_name);
                    return HandleCliOutcome::Quit;
                }
                let chat_id = chats_vec[0];
                let msg = tg_backend
                    .send_message(message_text.to_string(), chat_id, None)
                    .await;
                match msg {
                    Ok(msg) => {
                        let message_id = msg.id;
                        while app_context.tg_context().last_acknowledged_message_id() != message_id
                        {
                        }
                    }
                    Err(e) => {
                        tracing::error!("Error sending message: {:?}", e);
                        println!("Error sending message: {:?}", e);
                        return HandleCliOutcome::Quit;
                    }
                }

                tracing::info!(
                    "Sent message {} to chat_name {} ({})",
                    message_text,
                    chat_name,
                    chat_id
                );
                return HandleCliOutcome::Quit;
            }
            Err(e) => {
                tracing::error!("Error searching for chat: {:?}", e);
                println!("Error searching for chat: {:?}", e);
                return HandleCliOutcome::Quit;
            }
        }
    }
    HandleCliOutcome::Continue
}

/// Quit the tui.
///
/// # Arguments
/// * `tg_backend` - A mutable reference to the TgBackend struct.
/// * `tui_backend` - A mutable reference to the TuiBackend struct.
async fn quit_tui(tg_backend: &mut TgBackend, tui_backend: &mut TuiBackend) {
    futures::join!(tg_backend.offline());
    tg_backend.have_authorization = false;
    tg_backend.close().await;
    tui_backend.exit();
    tg_backend.handle_authorization_state().await;

    // Clear the terminal and move the cursor to the top left corner
    io::Write::write_all(&mut io::stdout().lock(), b"\x1b[2J\x1b[1;1H").unwrap();
}

/// Quit the cli.
///
/// # Arguments
/// * `tg_backend` - A mutable reference to the TgBackend struct.
async fn quit_cli(tg_backend: &mut TgBackend) {
    tg_backend.have_authorization = false;
    tg_backend.close().await;
    tg_backend.handle_authorization_state().await;

    // Clear the terminal and move the cursor to the top left corner
    io::Write::write_all(&mut io::stdout().lock(), b"\x1b[2J\x1b[1;1H").unwrap();
}

/// Logout the user from the Telegram backend.
///
/// # Arguments
/// * `tg_backend` - A mutable reference to the TgBackend struct.
async fn log_out(tg_backend: &mut TgBackend) {
    tg_backend.log_out().await;
    tg_backend.handle_authorization_state().await;

    // Clear the terminal and move the cursor to the top left corner
    io::Write::write_all(&mut io::stdout().lock(), b"\x1b[2J\x1b[1;1H").unwrap();
}