summaryrefslogtreecommitdiff
path: root/src/plugins.rs
blob: c0bbdae04d62179c4639af51ebc1a61797369bed (plain)
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
/*
 * meli - ui plugins
 *
 * Copyright 2019 Manos Pitsidianakis
 *
 * This file is part of meli.
 *
 * meli is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * meli is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with meli. If not, see <http://www.gnu.org/licenses/>.
 */

/*! Plugins are executed by meli and communication is done by `messagepack` IPC.
 */
use melib::error::{MeliError, Result};
use std::collections::HashMap;
use std::io::Write;
use std::os::unix::net::{UnixListener, UnixStream};
use std::path::PathBuf;
use std::process::Stdio;
use uuid::Uuid;

//pub mod backend;
pub mod rpc;
pub use rpc::*;

pub const BACKEND_FN: i8 = 0;
pub const BACKEND_OP_FN: i8 = 1;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum PluginKind {
    LongLived,
    Filter,
    Backend,
}

impl Default for PluginKind {
    fn default() -> Self {
        Self::LongLived
    }
}

#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct Plugin {
    kind: PluginKind,
    executable: String,
    name: String,
    #[serde(default)]
    hooks: Vec<String>,
}

impl Plugin {
    pub fn kind(&self) -> PluginKind {
        self.kind
    }
}

#[derive(Debug)]
pub struct PluginManager {
    plugins: HashMap<String, Plugin>,
    sessions: HashMap<Uuid, String>,
    instances: HashMap<Uuid, std::process::Child>,
    streams: HashMap<Uuid, RpcChannel>,
    hooks: HashMap<String, UIHook>,
    listener: UnixListener,
}

fn socket_path() -> PathBuf {
    xdg::BaseDirectories::new()
        .and_then(|base_dirs| {
            base_dirs
                .place_runtime_file("meli-plugins")
                .or_else(|_| base_dirs.place_cache_file("meli-plugins"))
                .or_else(|_| {
                    let mut p = base_dirs.get_cache_home();
                    p.push("meli-plugins");
                    Ok(p)
                })
        })
        .unwrap_or_else(|_| PathBuf::from("."))
}

impl Drop for PluginManager {
    fn drop(&mut self) {
        let _ = std::fs::remove_file(&socket_path());
        for (k, c) in self.instances.iter_mut() {
            if let Err(err) = debug!(c.kill()) {
                eprintln!(
                    "Error: could not kill process {} spawned by plugin {} ({})",
                    c.id(),
                    &self.plugins[&self.sessions[k]].name,
                    err
                );
            }
        }
    }
}

impl PluginManager {
    pub fn new() -> Self {
        let socket_path = socket_path();
        let _ = std::fs::remove_file(&socket_path);
        let listener = UnixListener::bind(&socket_path).unwrap();
        /*
            debug!("bound");
            // accept connections and process them, spawning a new thread for each one
            thread::spawn(move || {
                debug!("spawn");
                let stream = listener.accept();
                debug!("socket stream {:?}", &stream);
                match stream {
                    Ok((mut stream, _)) => {
                        debug!("socket stream {:?}", &stream);
                        /* connection succeeded */
                        thread::spawn(move || {
                            debug!("socket listen {:?}", &stream);
                            debug!(initialize(stream));
                            //let mut response = Vec::new();
                            //debug!(stream.read_to_end(&mut response));
                            //loop {
                            //    debug!("pre-flush 1");
                            //    stream.flush();
                            //    debug!("post-flush 1");
                            //    if debug!(rmpv::decode::value::read_value(&mut stream)).is_err() {
                            //        return;
                            //    }
                            //    debug!("post-read_value");
                            //    //debug!("socket response {}", unsafe {
                            //    //    String::from_utf8_lossy(&response)
                            //    //});
                            //    stream.flush();
                            //    debug!("post-flush 2");
                            //    if debug!(rmpv::encode::write_value(
                            //        &mut stream,
                            //        &rmpv::Value::String("hello 2 u 2".into())
                            //    ))
                            //    .is_err()
                            //    {
                            //        return;
                            //    }
                            //    debug!("post-write_value");
                            //}
                        });
                    }
                    Err(err) => {
                        /* connection failed */
                        debug!(err);
                    }
                }
            });
        */
        let mut hooks: HashMap<String, UIHook> = Default::default();

        hooks.insert(
            "attachment-view".to_string(),
            UIHook {
                name: "attachment-view".to_string(),
                wait_response: true,
                listeners: Vec::new(),
            },
        );

        hooks.insert(
            "refresh-account".to_string(),
            UIHook {
                name: "refresh-account".to_string(),
                wait_response: false,
                listeners: Vec::new(),
            },
        );

        PluginManager {
            plugins: Default::default(),
            sessions: Default::default(),
            instances: Default::default(),
            streams: Default::default(),
            hooks,
            listener,
        }
    }

    pub fn register(&mut self, plugin: Plugin) -> Result<()> {
        debug!(&plugin);
        match plugin.kind {
            PluginKind::LongLived => {
                /* spawn thread */
                let inv = &plugin.executable;
                let child = std::process::Command::new("sh")
                    .args(&["-c", inv])
                    .stdin(Stdio::piped())
                    .stdout(Stdio::piped())
                    .spawn()?;
                let (stream, _) = self.listener.accept()?;
                /* send init message to plugin to register hooks */
                let session = Uuid::new_v4();
                let channel = RpcChannel::new(stream, &session)?;

                for h in &plugin.hooks {
                    self.add_listener(h, session);
                }

                self.instances.insert(session, child);
                self.sessions.insert(session, plugin.name.clone());
                self.streams.insert(session, channel);
                self.plugins.insert(plugin.name.clone(), plugin);
                Ok(())
            }
            PluginKind::Filter => {
                let session = Uuid::new_v4();
                for h in &plugin.hooks {
                    self.add_listener(h, session);
                }

                self.sessions.insert(session, plugin.name.clone());
                self.plugins.insert(plugin.name.clone(), plugin);
                /* send init message to plugin to register hooks */
                Ok(())
            }
            PluginKind::Backend => {
                self.plugins.insert(plugin.name.clone(), plugin);
                /* send init message to plugin to register hooks */
                Ok(())
            }
        }
    }

    pub fn register_hook(&mut self, hook: UIHook) {
        self.hooks.insert(hook.name.clone(), hook);
    }

    pub fn add_listener(&mut self, hook: &str, session: Uuid) {
        self.hooks
            .entry(hook.to_string())
            .and_modify(|entry| entry.listeners.push(session));
    }

    pub fn activate_hook(&mut self, hook: &str, bytes: Vec<u8>) -> Result<FilterResult> {
        debug!("activate_hook {}", hook);
        debug!("bytes {:?}", &bytes);
        for l in &self.hooks[hook].listeners {
            let plugin = &self.plugins[&self.sessions[l]];
            debug!(&plugin);
            match &plugin.kind {
                PluginKind::LongLived => {
                    debug!("listener: {}", l);
                    let channel = self.streams.get_mut(l).unwrap();
                    channel.write_ref(&rmpv::ValueRef::Binary(bytes.as_slice()))?;
                    let reply: Result<FilterResult> = channel.from_read();
                    return reply;
                }
                PluginKind::Filter => {
                    let inv = &plugin.executable;
                    let mut child = std::process::Command::new("sh")
                        .args(&["-c", inv])
                        .stdin(Stdio::piped())
                        .stdout(Stdio::piped())
                        .spawn()?;
                    let (stream, _) = self.listener.accept()?;
                    let mut channel = RpcChannel::new(stream, l)?;
                    channel.write_ref(&rmpv::ValueRef::Binary(bytes.as_slice()))?;
                    let reply: Result<FilterResult> = channel.from_read();
                    child.kill()?;
                    return reply;
                }
                k => {
                    debug!("got plugin kind {:?} in hook  {}", k, hook);
                }
            }
        }
        Err(MeliError::new("no listeners for this hook"))
    }

    pub fn listener(&self) -> UnixListener {
        self.listener.try_clone().unwrap()
    }
}

#[derive(Debug)]
pub struct UIHook {
    name: String,
    wait_response: bool,
    listeners: Vec<Uuid>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[serde(tag = "t", content = "c")]
pub enum FilterResult {
    UiMessage(String),
    Text(String),
    Ansi(String),
    Binary(Vec<u8>),
    Error(String),
}