Commit 3efa953fea

3efa953feabb5abc4d16d43dfa6a4e9991789f7b

parent: cd352fe17d

Unsigned

Damir Jelić <poljar@termina.org.uk> · 2020-01-11 19:30 UTC

server: Allow setting the homeserver from the config.

Layout: unified · split

src/commands.rs +23 −16
@@ -2,7 +2,7 @@ use std::collections::HashMap;
22
33use clap::App as Argparse;
44use clap::AppSettings as ArgParseSettings;
5use clap::{SubCommand, Arg, ArgMatches};
5use clap::{Arg, ArgMatches, SubCommand};
66
77use crate::{Servers, ServersHandle};
88use weechat::Weechat;
@@ -17,22 +17,19 @@ impl Commands {
1717 let matrix_desc = CommandDescription {
1818 name: "matrix",
1919 description: "Matrix chat protocol command",
20 args:
21 "server add <server-name> <hostname>[:<port>] ||\
20 args: "server add <server-name> <hostname>[:<port>] ||\
2221 server delete|list|listfull <server-name> ||\
2322 connect <server-name> ||\
2423 disconnect <server-name> ||\
2524 reconnect <server-name> ||\
2625 help <matrix-command>",
27 args_description:
28" server: list, add, or remove Matrix servers
26 args_description: " server: list, add, or remove Matrix servers
2927 connect: connect to Matrix servers
3028 disconnect: disconnect from one or all Matrix servers
3129 reconnect: reconnect to server(s)
3230 help: show detailed command help\n
3331Use /matrix help [command] to find out more.\n",
34 completion:
35 "server |add|delete|list|listfull ||
32 completion: "server |add|delete|list|listfull ||
3633 connect ||
3734 disconnect ||
3835 reconnect ||
@@ -67,11 +64,18 @@ Use /matrix help [command] to find out more.\n",
6764 ) {
6865 let weechat = unsafe { Weechat::weechat() };
6966 let server_command = SubCommand::with_name("server")
70 .subcommand(SubCommand::with_name("add")
71 .arg(Arg::with_name("name").value_name("server-name")
72 .required(true))
73 .arg(Arg::with_name("homeserver").value_name("homeserver-address")
74 .required(true))
67 .subcommand(
68 SubCommand::with_name("add")
69 .arg(
70 Arg::with_name("name")
71 .value_name("server-name")
72 .required(true),
73 )
74 .arg(
75 Arg::with_name("homeserver")
76 .value_name("homeserver-address")
77 .required(true),
78 ),
7579 )
7680 .subcommand(SubCommand::with_name("delete"));
7781
@@ -100,19 +104,22 @@ Use /matrix help [command] to find out more.\n",
100104 weechat.print("Connecting");
101105 let mut servers = servers.borrow_mut();
102106 for server in servers.values_mut() {
103 server.connect();
107 match server.connect() {
108 Ok(_) => (),
109 Err(e) => weechat.print(&format!("{:?}", e)),
110 }
104111 }
105 },
112 }
106113 ("disconnect", Some(subargs)) => {
107114 weechat.print("Disconnecting");
108115 let mut servers = servers.borrow_mut();
109116 for server in servers.values_mut() {
110117 server.disconnect();
111118 }
112 },
119 }
113120 ("server", Some(subargs)) => {
114121 Commands::server_command(&buffer, subargs, &servers);
115 },
122 }
116123 _ => unreachable!(),
117124 }
118125 }
src/lib.rs +4 −1
@@ -64,7 +64,10 @@ impl Matrix {
6464 weechat.print(&format!("Autconnecting servers {:?}", servers.keys()));
6565
6666 for server in servers.values_mut() {
67 server.connect();
67 match server.connect() {
68 Ok(_) => (),
69 Err(e) => weechat.print(&format!("{:?}", e)),
70 }
6871 }
6972 }
7073
src/server.rs +101 −43
@@ -20,7 +20,7 @@ use matrix_nio::{
2020};
2121
2222use weechat::config::{
23 BooleanOptionSettings, ConfigSection, IntegerOptionSettings,
23 BooleanOptionSettings, ConfigSection, StringOptionSettings,
2424};
2525use weechat::Weechat;
2626
@@ -77,7 +77,6 @@ impl Connection {
7777pub(crate) struct MatrixServer {
7878 server_name: Rc<String>,
7979 inner: Rc<RefCell<InnerServer>>,
80 client: AsyncClient,
8180}
8281
8382pub(crate) struct InnerServer {
@@ -86,7 +85,7 @@ pub(crate) struct InnerServer {
8685 room_buffers: HashMap<String, RoomBuffer>,
8786 settings: ServerSettings,
8887 config: Config,
89 homeserver: Url,
88 client: Option<AsyncClient>,
9089 login_state: Option<LoginState>,
9190 connected_state: Rc<RefCell<Option<Connection>>>,
9291}
@@ -97,66 +96,85 @@ impl MatrixServer {
9796 config: &Config,
9897 server_section: &mut ConfigSection,
9998 ) -> Self {
100 let homeserver = Url::parse("http://localhost:8008").unwrap();
101
102 let client_config = AsyncClientConfig::new()
103 .proxy("http://localhost:8080")
104 .unwrap()
105 .disable_ssl_verification();
106
107 let client = AsyncClient::new_with_config(
108 homeserver.clone(),
109 None,
110 client_config,
111 )
112 .unwrap();
113
11499 let server_name = Rc::new(name.to_owned());
115100
116 let mut server = InnerServer {
101 let server = InnerServer {
117102 server_name: server_name.clone(),
118103 connected: false,
119104 room_buffers: HashMap::new(),
120105 settings: ServerSettings { homeserver: None },
121106 config: config.clone(),
122 homeserver,
107 client: None,
123108 login_state: None,
124109 connected_state: Rc::new(RefCell::new(None)),
125110 };
126 server.create_server_conf(server_section);
111
112 let server = Rc::new(RefCell::new(server));
113 MatrixServer::create_server_conf(&server_name, server_section, &server);
127114
128115 MatrixServer {
129116 server_name,
130 client,
131 inner: Rc::new(RefCell::new(server)),
117 inner: server,
132118 }
133119 }
134120
135121 pub fn name(&self) -> &str {
136122 &self.server_name
137123 }
138}
139124
140impl InnerServer {
141 fn create_server_conf(&mut self, server_section: &mut ConfigSection) {
142 let autoconnect = BooleanOptionSettings::new(format!(
143 "{}.autoconnect",
144 self.server_name
145 ))
146 .set_change_callback(|weechat, option| {
147 weechat.print("Hello");
148 });
125 fn create_server_conf(
126 server_name: &str,
127 server_section: &mut ConfigSection,
128 server_ref: &Rc<RefCell<InnerServer>>,
129 ) {
130 let server = Rc::downgrade(server_ref);
131 let autoconnect =
132 BooleanOptionSettings::new(format!("{}.autoconnect", server_name));
149133
150 let autoconnect = server_section
134 server_section
151135 .new_boolean_option(autoconnect)
152136 .expect("Can't create autoconnect option");
137
138 let homeserver = StringOptionSettings::new(format!(
139 "{}.homeserver",
140 server_name
141 ))
142 .set_check_callback(|_, _, value| {
143 let url = Url::parse(value.as_ref());
144
145 if let Ok(u) = url {
146 !u.cannot_be_a_base()
147 } else {
148 false
149 }
150 })
151 .set_change_callback(move |_, option| {
152 let server = server.clone();
153 let server_ref = server
154 .upgrade()
155 .expect("Server got deleted while server config is alive");
156
157 let mut server = server_ref.borrow_mut();
158 let mut homeserver = Url::parse(option.value().as_ref()).expect(
159 "Can't parse homeserver URL, did the check callback fail?",
160 );
161
162 server.settings.homeserver = Some(homeserver)
163 });
164
165 server_section
166 .new_string_option(homeserver)
167 .expect("Can't create homeserver option");
153168 }
169}
154170
171impl InnerServer {
155172 pub(crate) fn get_or_create_room(
156173 &mut self,
157174 room_id: &str,
158175 ) -> &mut RoomBuffer {
159176 if !self.room_buffers.contains_key(room_id) {
177 let homeserver = self.settings.homeserver.as_ref().expect("Creating room buffer while no homeserver");
160178 let login_state = self
161179 .login_state
162180 .as_ref()
@@ -164,7 +182,7 @@ impl InnerServer {
164182 let buffer = RoomBuffer::new(
165183 &self.server_name,
166184 &self.connected_state,
167 &self.homeserver,
185 homeserver,
168186 &self.config,
169187 room_id,
170188 &login_state.user_id,
@@ -175,6 +193,11 @@ impl InnerServer {
175193 self.room_buffers.get_mut(room_id).unwrap()
176194 }
177195
196 /// Is the server connected.
197 pub fn connected(&self) -> bool {
198 self.connected_state.borrow().is_some()
199 }
200
178201 pub(crate) fn receive_joined_state_event(
179202 &mut self,
180203 room_id: &str,
@@ -200,27 +223,60 @@ impl InnerServer {
200223 };
201224 self.login_state = Some(login_state);
202225 }
226
227 pub fn create_client(&mut self) -> Result<AsyncClient, ServerError> {
228 let homeserver =
229 self.settings.homeserver.as_ref().ok_or_else(|| {
230 ServerError::StartError("Homeserver not configured".to_owned())
231 })?;
232 let client_config = AsyncClientConfig::new()
233 .proxy("http://localhost:8080")
234 .unwrap()
235 .disable_ssl_verification();
236
237 let client = AsyncClient::new_with_config(
238 homeserver.clone(),
239 None,
240 client_config,
241 )
242 .unwrap();
243 self.client = Some(client.clone());
244 Ok(client)
245 }
203246}
204247
205248impl MatrixServer {
206 pub fn connect(&self) {
249 pub fn connect(&self) -> Result<(), ServerError> {
207250 let runtime = Runtime::new().unwrap();
208 let server = self.inner.borrow_mut();
251 let mut server = self.inner.borrow_mut();
252
253 let client = if let Some(c) = server.client.as_ref() {
254 c.clone()
255 } else {
256 server.create_client()?
257 };
258
259 // Check if the homeserver setting changed and swap our client if it
260 // did.
261 let client = if client.homeserver()
262 != server.settings.homeserver.as_ref().unwrap()
263 {
264 // TODO close all the room buffers of the server here, they don't
265 // belong to our client anymore.
266 server.create_client()?
267 } else {
268 client
269 };
209270
210 let send_client = self.client.clone();
211271 let (tx, rx) = async_channel(1000);
212 runtime.spawn(MatrixServer::sync_loop(self.client.clone(), tx.clone()));
272 runtime.spawn(MatrixServer::sync_loop(client.clone(), tx.clone()));
213273 let response_receiver = spawn_weechat(MatrixServer::response_receiver(
214274 rx,
215275 Rc::downgrade(&self.inner),
216276 ));
217277
218278 let (client_sender, client_receiver) = async_channel(10);
219 runtime.spawn(MatrixServer::send_loop(
220 send_client,
221 client_receiver,
222 tx,
223 ));
279 runtime.spawn(MatrixServer::send_loop(client, client_receiver, tx));
224280
225281 let mut connected_state = server.connected_state.borrow_mut();
226282
@@ -229,6 +285,8 @@ impl MatrixServer {
229285 client_channel: client_sender,
230286 runtime,
231287 });
288
289 Ok(())
232290 }
233291
234292 pub fn disconnect(&self) {