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
use std::{convert::TryFrom, error::Error, net::SocketAddr, sync::Mutex, time::Duration};

use tauri::async_runtime::block_on;
use tokio::time::timeout;
use tonic::{transport::Endpoint, Request};

use super::{
    server::editor_rpc::{
        editor_client::EditorClient,
        AuthorizeRequest,
        ContentPosition,
        DisconnectRequest,
        GetContentReply,
        GetContentRequest,
        SetCursorRequest,
        UpdateContentRequest,
    },
    Modification,
};
use crate::{
    dprintln,
    interface::remote::RpcClient,
    remote::server::editor_rpc::UpdateContentReply,
    types::ResultVoid,
};

pub struct RpcClientImpl {
    server_addr: Mutex<SocketAddr>,
    client: Option<EditorClient<tonic::transport::Channel>>,
}

impl Default for RpcClientImpl {
    fn default() -> Self {
        Self {
            server_addr: Mutex::new(SocketAddr::new("127.0.0.1".parse().unwrap(), 0)),
            client: None,
        }
    }
}

impl RpcClientImpl {
    fn should_not_running(&self) -> ResultVoid {
        if self.client.is_some() {
            return Err("Client is running, you need disconnect first".into());
        }
        Ok(())
    }

    fn should_running(&self) -> ResultVoid {
        if self.client.is_none() {
            return Err("Client is not running, you need connect first".into());
        }
        Ok(())
    }

    pub fn start(&mut self) -> ResultVoid {
        self.should_not_running()?;
        block_on(self.connect())?;
        Ok(())
    }

    pub fn stop(&mut self) -> ResultVoid {
        self.should_running()?;
        self.disconnect();
        Ok(())
    }

    pub fn set_server_addr(&mut self, server_addr: SocketAddr) -> ResultVoid {
        self.should_not_running()?;
        *self.server_addr.lock().unwrap() = server_addr;
        Ok(())
    }

    pub async fn send_authorize(
        &mut self,
        password: &str,
    ) -> Result<(String, u64, String), Box<dyn Error>> {
        self.should_running()?;
        let request = Request::new(AuthorizeRequest {
            password: password.to_string(),
        });
        let reply = match timeout(
            Duration::from_secs(2),
            self.client.as_mut().unwrap().authorize(request),
        )
        .await
        {
            Ok(reply) => reply?,
            Err(_) => return Err("Timeout".into()),
        };
        let reply_ref = reply.get_ref();
        if reply_ref.success {
            Ok((
                reply_ref.file_name.to_owned(),
                reply_ref.version,
                reply_ref.content.to_owned(),
            ))
        } else {
            Err("Authorize failed".into())
        }
    }

    pub async fn send_disconnect(&mut self) -> ResultVoid {
        let request = Request::new(DisconnectRequest {});

        let reply = match timeout(
            Duration::from_secs(2),
            self.client.as_mut().unwrap().disconnect(request),
        )
        .await
        {
            Ok(reply) => reply?,
            Err(_) => return Err("Timeout".into()),
        };
        let reply_ref = reply.get_ref();
        if !reply_ref.success {
            return Err("Disconnect failed".into());
        } else {
            Ok(())
        }
    }

    pub async fn send_set_cursor(&mut self, row: u64, col: u64) -> ResultVoid {
        let request = Request::new(SetCursorRequest { row, col });
        let reply = match timeout(
            Duration::from_secs(1),
            self.client.as_mut().unwrap().set_cursor(request),
        )
        .await
        {
            Ok(reply) => reply?,
            Err(_) => return Err("Timeout".into()),
        };
        if !reply.get_ref().success {
            Err("Failed to set cursor, the line already use by others".into())
        } else {
            Ok(())
        }
    }

    pub async fn send_get_content(
        &mut self,
        version: u64,
    ) -> Result<GetContentReply, Box<dyn Error>> {
        let request = Request::new(GetContentRequest {
            version,
            full_content: false,
        });
        let reply = match timeout(
            Duration::from_secs(1),
            self.client.as_mut().unwrap().get_content(request),
        )
        .await
        {
            Ok(reply) => reply?,
            Err(_) => return Err("Timeout".into()),
        };
        Ok(reply.get_ref().clone())
    }

    pub async fn send_update_content(
        &mut self,
        version: u64,
        history: &Modification,
    ) -> Result<UpdateContentReply, Box<dyn Error>> {
        let pos: ContentPosition = history.op_range.clone().into();
        let request = Request::new(UpdateContentRequest {
            version,
            op: history.op.clone().into(),
            op_range: Some(pos),
            modified_content: history.modified_content.clone(),
        });
        let reply = match timeout(
            Duration::from_secs(1),
            self.client.as_mut().unwrap().update_content(request),
        )
        .await
        {
            Ok(reply) => reply?,
            Err(_) => return Err("Timeout".into()),
        };
        dprintln!("{:?}", reply.get_ref());
        Ok(reply.get_ref().clone())
    }
}

impl RpcClient for RpcClientImpl {
    async fn connect(&mut self) -> Result<(), Box<dyn Error>> {
        let uri = format!("https://{}", self.server_addr.lock().unwrap());
        let endpoint = Endpoint::try_from(uri)?;
        let client = EditorClient::connect(endpoint).await?;
        self.client = Some(client);
        Ok(())
    }

    fn disconnect(&mut self) {
        self.client = None;
    }
}