]> nmode's Git Repositories - signal-cli/blob - client/src/main.rs
Implement JSON-RPC client PoC
[signal-cli] / client / src / main.rs
1 use clap::StructOpt;
2 use jsonrpc_client_transports::{RpcError, TypedSubscriptionStream};
3 use jsonrpc_core::{futures_util::StreamExt, Value};
4 use std::{path::PathBuf, time::Duration};
5 use tokio::{select, time::sleep};
6
7 use crate::cli::{GroupPermission, LinkState};
8
9 mod cli;
10 #[allow(clippy::too_many_arguments)]
11 mod jsonrpc;
12 mod tcp;
13
14 const DEFAULT_TCP: &str = "127.0.0.1:7583";
15 const DEFAULT_SOCKET_SUFFIX: &str = "signal-cli/socket";
16
17 #[tokio::main]
18 async fn main() -> Result<(), anyhow::Error> {
19 let cli = cli::Cli::parse();
20
21 let client = connect(&cli)
22 .await
23 .map_err(|e| anyhow::anyhow!("Failed to connect to socket: {e}"))?;
24
25 let result = match cli.command {
26 cli::CliCommands::Receive { timeout } => {
27 let mut stream = client
28 .subscribe_receive(cli.account)
29 .map_err(|e| anyhow::anyhow!("JSON-RPC command failed: {:?}", e))?;
30
31 {
32 while let Some(v) = stream_next(timeout, &mut stream).await {
33 let v = v.map_err(|e| anyhow::anyhow!("JSON-RPC command failed: {:?}", e))?;
34 println!("{v}");
35 }
36 }
37 return Ok(());
38 }
39 cli::CliCommands::AddDevice { uri } => client.add_device(cli.account, uri).await,
40 cli::CliCommands::Block {
41 recipient,
42 group_id,
43 } => client.block(cli.account, recipient, group_id).await,
44 cli::CliCommands::GetUserStatus { recipient } => {
45 client.get_user_status(cli.account, recipient).await
46 }
47 cli::CliCommands::JoinGroup { uri } => client.join_group(cli.account, uri).await,
48 cli::CliCommands::Link { name } => {
49 let url = client
50 .start_link(cli.account)
51 .await
52 .map_err(|e| anyhow::anyhow!("JSON-RPC command startLink failed: {e:?}",))?
53 .device_link_uri;
54 println!("{}", url);
55 client.finish_link(url, name).await
56 }
57 cli::CliCommands::ListAccounts => client.list_accounts().await,
58 cli::CliCommands::ListContacts => client.list_contacts(cli.account).await,
59 cli::CliCommands::ListDevices => client.list_devices(cli.account).await,
60 cli::CliCommands::ListGroups { detailed: _ } => client.list_groups(cli.account).await,
61 cli::CliCommands::ListIdentities { number } => {
62 client.list_identities(cli.account, number).await
63 }
64 cli::CliCommands::ListStickerPacks => client.list_sticker_packs(cli.account).await,
65 cli::CliCommands::QuitGroup {
66 group_id,
67 delete,
68 admin,
69 } => {
70 client
71 .quit_group(cli.account, group_id, delete, admin)
72 .await
73 }
74 cli::CliCommands::Register { voice, captcha } => {
75 client.register(cli.account, voice, captcha).await
76 }
77 cli::CliCommands::RemoveContact { recipient, forget } => {
78 client.remove_contact(cli.account, recipient, forget).await
79 }
80 cli::CliCommands::RemoveDevice { device_id } => {
81 client.remove_device(cli.account, device_id).await
82 }
83 cli::CliCommands::RemovePin => client.remove_pin(cli.account).await,
84 cli::CliCommands::RemoteDelete {
85 target_timestamp,
86 recipient,
87 group_id,
88 note_to_self,
89 } => {
90 client
91 .remote_delete(
92 cli.account,
93 target_timestamp,
94 recipient,
95 group_id,
96 note_to_self,
97 )
98 .await
99 }
100 cli::CliCommands::Send {
101 recipient,
102 group_id,
103 note_to_self,
104 end_session,
105 message,
106 attachment,
107 mention,
108 quote_timestamp,
109 quote_author,
110 quote_message,
111 quote_mention,
112 sticker,
113 } => {
114 client
115 .send(
116 cli.account,
117 recipient,
118 group_id,
119 note_to_self,
120 end_session,
121 message.unwrap_or_default(),
122 attachment,
123 mention,
124 quote_timestamp,
125 quote_author,
126 quote_message,
127 quote_mention,
128 sticker,
129 )
130 .await
131 }
132 cli::CliCommands::SendContacts => client.send_contacts(cli.account).await,
133 cli::CliCommands::SendReaction {
134 recipient,
135 group_id,
136 note_to_self,
137 emoji,
138 target_author,
139 target_timestamp,
140 remove,
141 } => {
142 client
143 .send_reaction(
144 cli.account,
145 recipient,
146 group_id,
147 note_to_self,
148 emoji,
149 target_author,
150 target_timestamp,
151 remove,
152 )
153 .await
154 }
155 cli::CliCommands::SendReceipt {
156 recipient,
157 target_timestamp,
158 r#type,
159 } => {
160 client
161 .send_receipt(
162 cli.account,
163 recipient,
164 target_timestamp,
165 match r#type {
166 cli::ReceiptType::Read => "read".to_owned(),
167 cli::ReceiptType::Viewed => "viewed".to_owned(),
168 },
169 )
170 .await
171 }
172 cli::CliCommands::SendSyncRequest => client.send_sync_request(cli.account).await,
173 cli::CliCommands::SendTyping {
174 recipient,
175 group_id,
176 stop,
177 } => {
178 client
179 .send_typing(cli.account, recipient, group_id, stop)
180 .await
181 }
182 cli::CliCommands::SetPin { pin } => client.set_pin(cli.account, pin).await,
183 cli::CliCommands::SubmitRateLimitChallenge { challenge, captcha } => {
184 client
185 .submit_rate_limit_challenge(cli.account, challenge, captcha)
186 .await
187 }
188 cli::CliCommands::Trust {
189 recipient,
190 trust_all_known_keys,
191 verified_safety_number,
192 } => {
193 client
194 .trust(
195 cli.account,
196 recipient,
197 trust_all_known_keys,
198 verified_safety_number,
199 )
200 .await
201 }
202 cli::CliCommands::Unblock {
203 recipient,
204 group_id,
205 } => client.unblock(cli.account, recipient, group_id).await,
206 cli::CliCommands::Unregister { delete_account } => {
207 client.unregister(cli.account, delete_account).await
208 }
209 cli::CliCommands::UpdateAccount { device_name } => {
210 client.update_account(cli.account, device_name).await
211 }
212 cli::CliCommands::UpdateConfiguration {
213 read_receipts,
214 unidentified_delivery_indicators,
215 typing_indicators,
216 link_previews,
217 } => {
218 client
219 .update_configuration(
220 cli.account,
221 read_receipts,
222 unidentified_delivery_indicators,
223 typing_indicators,
224 link_previews,
225 )
226 .await
227 }
228 cli::CliCommands::UpdateContact {
229 recipient,
230 expiration,
231 name,
232 } => {
233 client
234 .update_contact(cli.account, recipient, name, expiration)
235 .await
236 }
237 cli::CliCommands::UpdateGroup {
238 group_id,
239 name,
240 description,
241 avatar,
242 member,
243 remove_member,
244 admin,
245 remove_admin,
246 reset_link,
247 link,
248 set_permission_add_member,
249 set_permission_edit_details,
250 set_permission_send_messages,
251 expiration,
252 } => {
253 client
254 .update_group(
255 cli.account,
256 group_id,
257 name,
258 description,
259 avatar,
260 member,
261 remove_member,
262 admin,
263 remove_admin,
264 reset_link,
265 link.map(|link| match link {
266 LinkState::Enabled => "enabled".to_owned(),
267 LinkState::EnabledWithApproval => "enabledWithApproval".to_owned(),
268 LinkState::Disabled => "disabled".to_owned(),
269 }),
270 set_permission_add_member.map(|p| match p {
271 GroupPermission::EveryMember => "everyMember".to_owned(),
272 GroupPermission::OnlyAdmins => "onlyAdmins".to_owned(),
273 }),
274 set_permission_edit_details.map(|p| match p {
275 GroupPermission::EveryMember => "everyMember".to_owned(),
276 GroupPermission::OnlyAdmins => "onlyAdmins".to_owned(),
277 }),
278 set_permission_send_messages.map(|p| match p {
279 GroupPermission::EveryMember => "everyMember".to_owned(),
280 GroupPermission::OnlyAdmins => "onlyAdmins".to_owned(),
281 }),
282 expiration,
283 )
284 .await
285 }
286 cli::CliCommands::UpdateProfile {
287 given_name,
288 family_name,
289 about,
290 about_emoji,
291 avatar,
292 remove_avatar,
293 } => {
294 client
295 .update_profile(
296 cli.account,
297 given_name,
298 family_name,
299 about,
300 about_emoji,
301 avatar,
302 remove_avatar,
303 )
304 .await
305 }
306 cli::CliCommands::UploadStickerPack { path } => {
307 client.upload_sticker_pack(cli.account, path).await
308 }
309 cli::CliCommands::Verify {
310 verification_code,
311 pin,
312 } => client.verify(cli.account, verification_code, pin).await,
313 cli::CliCommands::Version => client.version().await,
314 };
315
316 result
317 .map(|v| println!("{v}"))
318 .map_err(|e| anyhow::anyhow!("JSON-RPC command failed: {e:?}",))?;
319 Ok(())
320 }
321
322 async fn connect(cli: &cli::Cli) -> Result<jsonrpc::SignalCliClient, RpcError> {
323 if let Some(tcp) = cli.json_rpc_tcp {
324 let socket_addr = tcp.unwrap_or_else(|| DEFAULT_TCP.parse().unwrap());
325 jsonrpc::connect_tcp(socket_addr).await
326 } else {
327 let socket_path = cli
328 .json_rpc_socket
329 .clone()
330 .unwrap_or(None)
331 .or_else(|| {
332 std::env::var_os("XDG_RUNTIME_DIR").map(|runtime_dir| {
333 PathBuf::from(runtime_dir)
334 .join(DEFAULT_SOCKET_SUFFIX)
335 .into()
336 })
337 })
338 .unwrap_or_else(|| ("/run".to_owned() + DEFAULT_SOCKET_SUFFIX).into());
339 jsonrpc::connect_unix(socket_path).await
340 }
341 }
342
343 async fn stream_next(
344 timeout: f64,
345 stream: &mut TypedSubscriptionStream<Value>,
346 ) -> Option<Result<Value, RpcError>> {
347 if timeout < 0.0 {
348 stream.next().await
349 } else {
350 select! {
351 v = stream.next() => v,
352 _= sleep(Duration::from_millis((timeout * 1000.0) as u64)) => None,
353 }
354 }
355 }