Commit d6f30f37d9

d6f30f37d96ec3f8fceeddd428a80713dac81bb0

Unsigned

Damir Jelić <poljar@termina.org.uk> · 2019-11-04 19:00 UTC

Initial commit.

Layout: unified · split

.gitignore added +2
@@ -0,0 +1,2 @@
1/target
2**/*.rs.bk
.rustfmt.toml added +1
@@ -0,0 +1 @@
1max_width = 80
Cargo.toml added +22
@@ -0,0 +1,22 @@
1[package]
2name = "weechat-rust-sample-plugin"
3version = "0.1.0"
4authors = ["Damir Jelić <poljar@termina.org.uk>"]
5edition = "2018"
6
7[lib]
8name = "weechat_matrix"
9crate-type = ["dylib"]
10
11[dependencies]
12libc = "*"
13futures-preview = "0.3.0-alpha.18"
14tokio = "0.2.0-alpha.6"
15
16matrix-nio = { path = "/home/poljar/werk/priv/nio-rust/" }
17
18weechat = { path = "/home/poljar/werk/misc/rust-weechat/weechat-rs" }
19weechat-sys = { path = "/home/poljar/werk/misc/rust-weechat/weechat-sys" }
20async-std = { version = "0.99.11", features = [ "unstable" ] }
21async-task = { path = "/home/poljar/werk/misc/async-task" }
22pipe-channel = "*"
Makefile added +17
@@ -0,0 +1,17 @@
1WEECHAT_HOME ?= $(HOME)/.weechat
2PREFIX ?= $(WEECHAT_HOME)
3
4.PHONY: install install-dir phony lint
5
6target/debug/libweechat_matrix.so: src/lib.rs
7 cargo build
8
9install: install-dir
10 install -m644 target/debug/libweechat_matrix.so $(DESTDIR)$(PREFIX)/plugins/weechat-matrix-rs.so
11
12install-dir:
13 install -d $(DESTDIR)$(PREFIX)/plugins
14
15lint:
16 cargo clippy
17
src/lib.rs added +252
@@ -0,0 +1,252 @@
1use std::time::Duration;
2use std::sync::{Arc, Mutex};
3
4use pipe_channel::{channel, Sender, Receiver};
5use tokio::runtime::Runtime;
6
7use async_task;
8use async_std;
9use async_std::sync::channel as async_channel;
10use async_std::sync::Sender as AsyncSender;
11use std::future::Future;
12use std::collections::VecDeque;
13
14use weechat::{weechat_plugin, ArgsWeechat, Weechat, WeechatPlugin, WeechatResult,
15 FdHookMode, FdHook};
16
17use matrix_nio::{
18 self,
19 events::{
20 collections::all::RoomEvent,
21 room::message::{MessageEvent, MessageEventContent, TextMessageEventContent},
22 },
23 AsyncClient,
24 SyncSettings,
25 AsyncClientConfig,
26};
27
28static mut _WEECHAT: Option<Weechat> = None;
29
30struct SamplePlugin {
31 weechat: Weechat,
32 tokio: Option<Runtime>,
33}
34
35fn spawn_cb(future_queue: &FutureQueue, receiver: &mut Receiver<()>) {
36 receiver.recv().unwrap();
37
38 let mut queue = future_queue.lock().unwrap();
39 let task = queue.pop_front();
40
41 if let Some(task) = task {
42 task.run();
43 }
44}
45
46
47type Job = async_task::Task<()>;
48
49static mut _FUTURE_HOOK: Option<FdHook<FutureQueue, Receiver<()>>> = None;
50static mut _SENDER: Option<Arc<Mutex<Sender<()>>>> = None;
51static mut _FUTURE_QUEUE: Option<FutureQueue> = None;
52
53type FutureQueue = Arc<Mutex<VecDeque<Job>>>;
54
55fn spawn_weechat<F, T>(future: F)
56where
57 F: Future<Output = T> + 'static,
58 T: 'static
59{
60 let weechat = get_weechat();
61
62 unsafe {
63 if _FUTURE_HOOK.is_none() {
64 let (sender, receiver) = channel();
65 let sender = Arc::new(Mutex::new(sender));
66 _SENDER = Some(sender);
67 let queue = Arc::new(Mutex::new(VecDeque::new()));
68 _FUTURE_QUEUE = Some(queue.clone());
69
70 let fd_hook = weechat.hook_fd(
71 receiver,
72 FdHookMode::Read,
73 spawn_cb,
74 Some(queue)
75 );
76 _FUTURE_HOOK = Some(fd_hook);
77 }
78 }
79
80 let weechat_notify = unsafe {
81 if let Some(s) = &_SENDER {
82 s.clone()
83 } else {
84 panic!("Future queue wasn't initialized")
85 }
86 };
87
88 let queue: FutureQueue = unsafe {
89 if let Some(q) = &_FUTURE_QUEUE {
90 q.clone()
91 } else {
92 panic!("Future queue wasn't initialized")
93 }
94 };
95
96 let schedule = move |task| {
97 let mut weechat_notify = weechat_notify.lock().unwrap();
98 let mut queue = queue.lock().unwrap();
99
100 queue.push_back(task);
101 weechat_notify.send(()).unwrap();
102 };
103
104 let (task, _handle) = async_task::spawn(future, schedule, ());
105 task.schedule();
106}
107
108
109fn get_weechat() -> &'static mut Weechat {
110 unsafe {
111 match &mut _WEECHAT {
112 Some(x) => x,
113 None => panic!(),
114 }
115 }
116}
117
118fn get_plugin() -> &'static mut SamplePlugin {
119 unsafe {
120 match &mut __PLUGIN {
121 Some(x) => x,
122 None => panic!(),
123 }
124 }
125}
126
127async fn sync_loop(channel: AsyncSender<Result<(String, String), String>>) {
128 let server = "http://localhost:8008";
129 let config = AsyncClientConfig::new().proxy("http://localhost:8080").unwrap().disable_ssl_verification();
130 let mut client = AsyncClient::new_with_config(server, None, config).unwrap();
131
132 channel.send(Err("HELLO WORLD".to_string())).await;
133 channel.send(Err("HELLO WORLD".to_string())).await;
134
135 let ret = client.login("example", "wordpass", None).await;
136
137 match ret {
138 Ok(_) => (),
139 Err(e) => {
140 channel.send(Err("No logging in".to_string())).await;
141 return;
142 },
143 }
144
145 channel.send(Err("Syncing now".to_string())).await;
146
147 let sync_settings = SyncSettings::new().timeout(30000).unwrap();
148 let response = client.sync(sync_settings).await;
149
150 channel.send(Err("Synced now".to_string())).await;
151
152 match response {
153 Ok(r) => {
154 for (room_id, room) in r.rooms.join {
155 for event in room.timeline.events {
156 let event = match event.into_result() {
157 Ok(e) => e,
158 Err(e) => continue,
159 };
160 if let RoomEvent::RoomMessage(MessageEvent {
161 content:
162 MessageEventContent::Text(TextMessageEventContent { body: msg_body, .. }),
163 sender,
164 ..
165 }) = event
166 {
167 channel.send(Ok((sender.to_string(), msg_body.to_string()))).await;
168 }
169 }
170 }
171 },
172 Err(e) => {
173 let err = format!("{:?}", e.to_string());
174 channel.send(Err(err)).await;
175 ()
176 }
177 }
178
179 loop {
180 channel.send(Ok(("Hello".to_string(), "world".to_string()))).await;
181 async_std::task::sleep(Duration::from_secs(3)).await;
182 }
183
184}
185
186impl WeechatPlugin for SamplePlugin {
187 fn init(weechat: Weechat, _args: ArgsWeechat) -> WeechatResult<Self> {
188 unsafe {
189 _WEECHAT = Some(weechat.clone());
190 }
191
192 let runtime = Runtime::new().unwrap();
193 let (tx, rx) = async_channel(100);
194
195 let weechat_task = async move {
196 let weechat = get_weechat();
197 weechat.print("Hello async/await");
198 let plugin = get_plugin();
199
200 loop {
201 let ret = match rx.recv().await {
202 Some(m) => m,
203 None => {
204 weechat.print("Error receiving message");
205 return;
206 }
207 };
208
209 match ret {
210 Ok((sender, msg)) => {
211 weechat.print(&format!("Got message from {}: {}", sender, msg));
212 },
213 Err(e) => weechat.print(&format!("Ruma error {}", e)),
214 };
215 }
216 };
217
218 runtime.spawn(async move {
219 sync_loop(tx).await;
220 });
221
222 spawn_weechat(weechat_task);
223
224 Ok(SamplePlugin { weechat, tokio: Some(runtime) })
225 }
226}
227
228impl Drop for SamplePlugin {
229 fn drop(&mut self) {
230 let runtime = self.tokio.take();
231
232 if let Some(r) = runtime {
233 r.shutdown_now();
234 }
235
236 self.weechat.print("Bye rust!");
237 unsafe {
238 _FUTURE_HOOK.take();
239 _SENDER.take();
240 _FUTURE_QUEUE.take();
241 }
242 }
243}
244
245weechat_plugin!(
246 SamplePlugin,
247 name: "weechat-matrix",
248 author: "poljar",
249 description: "",
250 version: "0.1.0",
251 license: "MIT"
252);