aboutsummaryrefslogtreecommitdiffstats
path: root/src/bin/rbw-agent/notifications.rs
blob: ffdefe99668a8a2f312f3c38c46799fd3a21dab3 (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
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
use tokio_tungstenite::{connect_async, tungstenite::protocol::Message};
use futures_util::{StreamExt, SinkExt};

struct SyncCipherUpdate {
    id: String
}

struct SyncCipherCreate {
    id: String
}

enum NotificationMessage {
    SyncCipherUpdate(SyncCipherUpdate),
    SyncCipherCreate(SyncCipherCreate),
    SyncLoginDelete,
    SyncFolderDelete,
    SyncCiphers,

    SyncVault,
    SyncOrgKeys,
    SyncFolderCreate,
    SyncFolderUpdate,
    SyncCipherDelete,
    SyncSettings,

    Logout,

    SyncSendCreate,
    SyncSendUpdate,
    SyncSendDelete,

    AuthRequest,
    AuthRequestResponse,

    None,
}

fn parse_messagepack(data: &[u8]) -> Option<NotificationMessage> {
    if data.len() < 2 {
        return None;
    }

    // the first few bytes with th 0x80 bit set, plus one byte terminating the length contain the length of the message
    let len_buffer_length = data.iter().position(|&x| (x & 0x80) == 0 )? + 1;

    println!("len_buffer_length: {:?}", len_buffer_length);
    println!("data: {:?}", data);
    let unpacked_messagepack = rmpv::decode::read_value(&mut &data[len_buffer_length..]).ok().unwrap();
    println!("unpacked_messagepack: {:?}", unpacked_messagepack);
    if !unpacked_messagepack.is_array() {
        return None;
    }
    let unpacked_message = unpacked_messagepack.as_array().unwrap();
    println!("unpacked_message: {:?}", unpacked_message);
    let message_type = unpacked_message.iter().next()?.as_u64()?;
    let message = unpacked_message.iter().skip(4).next()?.as_array()?.first()?.as_map()?;
    let payload = message.iter().filter(|x| x.0.as_str().unwrap() == "Payload").next()?.1.as_map()?;
    println!("message_type: {:?}", message_type);
    println!("payload: {:?}", payload);

    let message = match message_type {
        0  => {
            let id = payload.iter().filter(|x| x.0.as_str().unwrap() == "Id").next()?.1.as_str()?;

            Some(NotificationMessage::SyncCipherUpdate(
                SyncCipherUpdate {
                    id: id.to_string()
                }
            ))
        },
        1  => {
            let id = payload.iter().filter(|x| x.0.as_str().unwrap() == "Id").next()?.1.as_str()?;

            Some(NotificationMessage::SyncCipherCreate(
                SyncCipherCreate {
                    id: id.to_string()
                }
            ))
        },
        2  => Some(NotificationMessage::SyncLoginDelete),
        3  => Some(NotificationMessage::SyncFolderDelete),
        4  => Some(NotificationMessage::SyncCiphers),
        5  => Some(NotificationMessage::SyncVault),
        6  => Some(NotificationMessage::SyncOrgKeys),
        7  => Some(NotificationMessage::SyncFolderCreate),
        8  => Some(NotificationMessage::SyncFolderUpdate),
        9  => Some(NotificationMessage::SyncCipherDelete),
        10 => Some(NotificationMessage::SyncSettings),
        11 => Some(NotificationMessage::Logout),
        12 => Some(NotificationMessage::SyncSendCreate),
        13 => Some(NotificationMessage::SyncSendUpdate),
        14 => Some(NotificationMessage::SyncSendDelete),
        15 => Some(NotificationMessage::AuthRequest),
        16 => Some(NotificationMessage::AuthRequestResponse),
        100 => Some(NotificationMessage::None),
        _ => None
    };

    return message;
}

pub async fn subscribe_to_notifications(url: String) {
    let url = url::Url::parse(url.as_str()).unwrap();

    let (ws_stream, _response) = connect_async(url).await.expect("Failed to connect");

    let (mut write, read) = ws_stream.split();

    write.send(Message::Text("{\"protocol\":\"messagepack\",\"version\":1}\n".to_string())).await.unwrap();

    let read_future = read.for_each(|message| async {
        match message {
            Ok(Message::Binary(binary)) => {
                let msg = parse_messagepack(&binary);
                match msg {
                    Some(NotificationMessage::SyncCipherUpdate(update)) => {
                        println!("Websocket sent SyncCipherUpdate for id: {:?}", update.id);
                        crate::actions::sync(None).await.unwrap();
                        println!("Synced")
                    },
                    Some(NotificationMessage::SyncCipherCreate(update)) => {
                        println!("Websocket sent SyncCipherUpdate for id: {:?}", update.id);
                        crate::actions::sync(None).await.unwrap();
                        println!("Synced")
                    },
                    Some(NotificationMessage::SyncLoginDelete) => {
                        crate::actions::sync(None).await.unwrap();
                    },
                    Some(NotificationMessage::SyncFolderDelete) => {
                        crate::actions::sync(None).await.unwrap();
                    },
                    Some(NotificationMessage::SyncCiphers) => {
                        crate::actions::sync(None).await.unwrap();
                    },
                    Some(NotificationMessage::SyncVault) => {
                        crate::actions::sync(None).await.unwrap();
                    },
                    Some(NotificationMessage::SyncOrgKeys) => {
                        crate::actions::sync(None).await.unwrap();
                    },
                    Some(NotificationMessage::SyncFolderCreate) => {
                        crate::actions::sync(None).await.unwrap();
                    },
                    Some(NotificationMessage::SyncFolderUpdate) => {
                        crate::actions::sync(None).await.unwrap();
                    },
                    Some(NotificationMessage::SyncCipherDelete) => {
                        crate::actions::sync(None).await.unwrap();
                    },
                    Some(NotificationMessage::Logout) => {
                        println!("Websocket sent Logout");
                        // todo: proper logout?
                        std::process::exit(0);
                    },
                    _ => {}
                }
            },
            Err(e) => {
                println!("websocket error: {:?}", e);
            },
            _ => {}
        }
    });

    read_future.await;
}