aboutsummaryrefslogtreecommitdiffstats
path: root/teleterm-web/src/model.rs
blob: c3428e1edb8d057cdc32437ecb98dcda84f58e1e (plain) (blame)
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
use crate::prelude::*;

const LIST_URL: &str = "http://127.0.0.1:4145/list";
const WATCH_URL: &str = "ws://127.0.0.1:4145/watch";

struct WatchConn {
    ws: WebSocket,
    term: vt100::Parser,
}

impl Drop for WatchConn {
    fn drop(&mut self) {
        self.ws.close().unwrap();
    }
}

#[derive(Clone, Debug, serde::Deserialize)]
pub struct Session {
    pub id: String,
    pub username: String,
}

#[derive(Default)]
pub struct Model {
    sessions: Vec<Session>,
    watch_conn: Option<WatchConn>,
}

impl Model {
    pub(crate) fn list(
        &self,
    ) -> impl futures::Future<Item = crate::Msg, Error = crate::Msg> {
        seed::Request::new(LIST_URL).fetch_json_data(crate::Msg::List)
    }

    pub(crate) fn watch(
        &mut self,
        id: &str,
        orders: &mut impl Orders<crate::Msg>,
    ) {
        let ws = crate::ws::connect(
            &format!("{}?id={}", WATCH_URL, id),
            id,
            crate::Msg::Watch,
            orders,
        );
        let term = vt100::Parser::default();
        self.watch_conn = Some(WatchConn { ws, term })
    }

    pub fn sessions(&self) -> &[Session] {
        &self.sessions
    }

    pub fn update_sessions(&mut self, sessions: Vec<Session>) {
        self.sessions = sessions;
    }

    pub fn process(&mut self, bytes: &[u8]) {
        if let Some(conn) = &mut self.watch_conn {
            conn.term.process(bytes);
        }
    }

    pub fn screen(&self) -> String {
        if let Some(conn) = &self.watch_conn {
            conn.term.screen().contents()
        } else {
            "".to_string()
        }
    }
}