src/lib.rs

8454dcd1674dfb48ab4ee615134e2d4d5fc04fa7
weechat-matrix-rs/src/lib.rs history · blame · raw

334 lines · 9509 bytes

  1// Increase recursion limit to pre-rustc 1.94 level for macro expansion and auto-dereferencing.
  2#![recursion_limit = "256"]
  3
  4mod bar_items;
  5mod commands;
  6mod completions;
  7mod config;
  8mod connection;
  9mod debug;
 10mod render;
 11mod room;
 12mod server;
 13mod utils;
 14mod verification_buffer;
 15
 16use std::{
 17    cell::{Ref, RefCell},
 18    collections::HashMap,
 19    rc::Rc,
 20};
 21
 22use tokio::runtime::{Handle, Runtime};
 23use tracing_subscriber::layer::SubscriberExt;
 24
 25use weechat::{
 26    buffer::{Buffer, BufferHandle},
 27    hooks::{SignalCallback, SignalData, SignalHook},
 28    plugin, Args, Plugin, ReturnCode, Weechat,
 29};
 30
 31use crate::{
 32    bar_items::BarItems, commands::Commands, completions::Completions,
 33    config::ConfigHandle, room::RoomHandle, server::MatrixServer,
 34    verification_buffer::VerificationBuffer,
 35};
 36
 37const PLUGIN_NAME: &str = "matrix";
 38
 39#[derive(Clone, Debug)]
 40pub struct Servers {
 41    inner: Rc<RefCell<HashMap<String, MatrixServer>>>,
 42    runtime: Handle,
 43}
 44
 45#[allow(clippy::large_enum_variant)]
 46pub enum BufferOwner {
 47    Server(MatrixServer),
 48    Room(MatrixServer, RoomHandle),
 49    Verification(MatrixServer, VerificationBuffer),
 50    None,
 51}
 52
 53impl BufferOwner {
 54    fn into_server(self) -> Option<MatrixServer> {
 55        match self {
 56            BufferOwner::Server(s) => Some(s),
 57            BufferOwner::Room(s, _) => Some(s),
 58            BufferOwner::Verification(s, _) => Some(s),
 59            BufferOwner::None => None,
 60        }
 61    }
 62
 63    fn into_room(self) -> Option<RoomHandle> {
 64        if let BufferOwner::Room(_, r) = self {
 65            Some(r)
 66        } else {
 67            None
 68        }
 69    }
 70}
 71
 72impl Servers {
 73    fn new(handle: tokio::runtime::Handle) -> Self {
 74        Servers {
 75            inner: Rc::new(RefCell::new(HashMap::new())),
 76            runtime: handle,
 77        }
 78    }
 79
 80    fn borrow(&self) -> Ref<'_, HashMap<String, MatrixServer>> {
 81        self.inner.borrow()
 82    }
 83
 84    pub fn runtime(&self) -> &Handle {
 85        &self.runtime
 86    }
 87
 88    pub fn is_empty(&self) -> bool {
 89        self.inner.borrow().is_empty()
 90    }
 91
 92    pub fn contains(&self, server_name: &str) -> bool {
 93        self.inner.borrow().contains_key(server_name)
 94    }
 95
 96    pub fn clear(&self) {
 97        self.inner.borrow_mut().clear();
 98    }
 99
100    pub fn insert(&self, server: MatrixServer) {
101        self.inner
102            .borrow_mut()
103            .insert(server.name().to_string(), server);
104    }
105
106    pub fn get(&self, server_name: &str) -> Option<MatrixServer> {
107        self.inner.borrow().get(server_name).cloned()
108    }
109
110    pub fn remove(&self, server_name: &str) -> Option<MatrixServer> {
111        self.inner.borrow_mut().remove(server_name)
112    }
113
114    pub fn buffer_owner(&self, buffer: &Buffer) -> BufferOwner {
115        let servers = self.borrow();
116
117        for server in servers.values() {
118            if let Some(b) = &*server.server_buffer() {
119                if b.upgrade().is_ok_and(|b| &b == buffer) {
120                    return BufferOwner::Server(server.clone());
121                }
122            }
123
124            for room in server.rooms() {
125                if room.owns_buffer(buffer) {
126                    return BufferOwner::Room(server.clone(), room);
127                }
128            }
129
130            for verification in server.verifications() {
131                if let Ok(b) = verification.buffer().upgrade() {
132                    if buffer == &b {
133                        return BufferOwner::Verification(
134                            server.clone(),
135                            verification,
136                        );
137                    }
138                }
139            }
140        }
141
142        BufferOwner::None
143    }
144
145    /// Find a `MatrixServer` that the given buffer belongs to.
146    ///
147    /// Returns None if the buffer doesn't belong to any of our servers of
148    /// rooms.
149    pub fn find_server(&self, buffer: &Buffer) -> Option<MatrixServer> {
150        self.buffer_owner(buffer).into_server()
151    }
152
153    /// Find a `RoomHandle` that the given buffer belongs to.
154    ///
155    /// Returns None if the buffer doesn't belong to any of our servers of
156    /// rooms.
157    pub fn find_room(&self, buffer: &Buffer) -> Option<RoomHandle> {
158        self.buffer_owner(buffer).into_room()
159    }
160}
161
162impl SignalCallback for Servers {
163    fn callback(
164        &mut self,
165        _: &Weechat,
166        signal_name: &str,
167        data: Option<SignalData>,
168    ) -> ReturnCode {
169        if let Some(SignalData::Buffer(buffer)) = data {
170            if let Some(room) = self.find_room(&buffer) {
171                match signal_name {
172                    "buffer_switch" => {
173                        room.mark_as_read_silent();
174                        Weechat::spawn(async move {
175                            room.get_messages_if_empty().await
176                        })
177                        .detach();
178                    }
179                    "input_text_changed" => room.update_typing_notice(),
180                    _ => (),
181                }
182            }
183        }
184        ReturnCode::Ok
185    }
186}
187
188struct Matrix {
189    #[allow(dead_code)]
190    global_runtime: Runtime,
191    servers: Servers,
192    #[allow(dead_code)]
193    commands: Commands,
194    config: ConfigHandle,
195    #[allow(dead_code)]
196    bar_items: BarItems,
197    #[allow(dead_code)]
198    typing_notice_signal: SignalHook,
199    #[allow(dead_code)]
200    history_fetch_signal: SignalHook,
201    #[allow(dead_code)]
202    read_marker_signal: SignalHook,
203    #[allow(dead_code)]
204    completions: Completions,
205    debug_buffer: RefCell<Option<BufferHandle>>,
206}
207
208impl std::fmt::Debug for Matrix {
209    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
210        let mut fmt = f.debug_struct("Matrix");
211        fmt.field("servers", &self.servers).finish()
212    }
213}
214
215impl Matrix {
216    fn autoconnect(servers: &HashMap<String, MatrixServer>) {
217        for server in servers.values() {
218            if server.autoconnect() {
219                match server.connect() {
220                    Ok(_) => (),
221                    Err(e) => Weechat::print(&format!("{:?}", e)),
222                }
223            }
224        }
225    }
226
227    fn create_default_server(servers: Servers, config: &ConfigHandle) {
228        // TODO change this to matrix.org.
229        let server_name = "localhost";
230
231        let mut config_borrow = config.borrow_mut();
232        let mut section = config_borrow
233            .search_section_mut("server")
234            .expect("Can't get server section");
235
236        let server = MatrixServer::new(
237            server_name,
238            config,
239            &mut section,
240            servers.clone(),
241        );
242        servers.insert(server);
243    }
244}
245
246impl Plugin for Matrix {
247    fn init(_: &Weechat, _args: Args) -> Result<Self, ()> {
248        let global_runtime =
249            Runtime::new().expect("Couldn't create a new global runtime");
250
251        let servers = Servers::new(global_runtime.handle().to_owned());
252        let config = ConfigHandle::new(&servers);
253        let commands = Commands::hook_all(&servers, &config)?;
254
255        let bar_items = BarItems::hook_all(servers.clone())?;
256        let completions = Completions::hook_all(servers.clone())?;
257
258        let subscriber = tracing_subscriber::registry()
259            .with(tracing_subscriber::filter::EnvFilter::from_default_env())
260            .with(tracing_subscriber::fmt::layer().with_writer(debug::Debug));
261
262        let _ = tracing::subscriber::set_global_default(subscriber).map_err(
263            |_err| Weechat::print("Unable to set global default subscriber"),
264        );
265
266        {
267            let config_borrow = config.borrow();
268            if config_borrow.read().is_err() {
269                return Err(());
270            }
271        }
272
273        if servers.is_empty() {
274            Matrix::create_default_server(servers.clone(), &config)
275        }
276
277        let typing = SignalHook::new("input_text_changed", servers.clone())
278            .expect("Can't create signal hook for the typing notice cb");
279        let history_fetch = SignalHook::new("buffer_switch", servers.clone())
280            .expect("Can't create signal hook for the history fetch cb");
281        let read_marker = SignalHook::new("buffer_switch", servers.clone())
282            .expect("Can't create signal hook for the read marker cb");
283
284        let plugin = Matrix {
285            global_runtime,
286            servers: servers.clone(),
287            commands,
288            config,
289            bar_items,
290            completions,
291            debug_buffer: RefCell::new(None),
292            typing_notice_signal: typing,
293            history_fetch_signal: history_fetch,
294            read_marker_signal: read_marker,
295        };
296
297        Weechat::spawn(async move {
298            let servers = servers.borrow();
299            Matrix::autoconnect(&servers);
300        })
301        .detach();
302
303        Ok(plugin)
304    }
305}
306
307impl Drop for Matrix {
308    fn drop(&mut self) {
309        let servers = self.servers.borrow();
310
311        // Buffer close callbacks get called after this, so drop active
312        // connections here so we don't leave all our rooms.
313        //
314        // TODO set a flag on the server as well so we don't even try to leave
315        // the rooms, once leaving the rooms is implemented when the buffer gets
316        // closed.
317        for server in servers.values() {
318            server.shutdown();
319        }
320
321        drop(servers);
322
323        self.servers.clear();
324    }
325}
326
327plugin!(
328    Matrix,
329    name: "matrix",
330    author: "Damir Jelić <poljar@termina.org.uk>",
331    description: "Matrix protocol",
332    version: "0.1.0",
333    license: "ISC"
334);