]> nmode's Git Repositories - signal-cli/blob - client/src/main.rs
68de03d44cab39409857db7d7d8fec44f5ea489c
[signal-cli] / client / src / main.rs
1 use std::{path::PathBuf, time::Duration};
2
3 use clap::Parser;
4 use jsonrpsee::core::client::{Error as RpcError, Subscription, SubscriptionClientT};
5 use serde_json::{Error, Value};
6 use tokio::{select, time::sleep};
7
8 use cli::Cli;
9
10 use crate::cli::{CliCommands, GroupPermission, LinkState};
11 use crate::jsonrpc::RpcClient;
12
13 mod cli;
14 #[allow(non_snake_case, clippy::too_many_arguments)]
15 mod jsonrpc;
16 mod transports;
17
18 const DEFAULT_TCP: &str = "127.0.0.1:7583";
19 const DEFAULT_SOCKET_SUFFIX: &str = "signal-cli/socket";
20 const DEFAULT_HTTP: &str = "http://localhost:8080/api/v1/rpc";
21
22 #[tokio::main]
23 async fn main() -> Result<(), anyhow::Error> {
24 let cli = cli::Cli::parse();
25
26 let result = connect(cli).await;
27
28 match result {
29 Ok(Value::Null) => {}
30 Ok(v) => println!("{v}"),
31 Err(e) => return Err(anyhow::anyhow!("JSON-RPC command failed: {e:?}")),
32 }
33 Ok(())
34 }
35
36 async fn handle_command(
37 cli: Cli,
38 client: impl SubscriptionClientT + Sync,
39 ) -> Result<Value, RpcError> {
40 match cli.command {
41 CliCommands::Receive { timeout } => {
42 let mut stream = client.subscribe_receive(cli.account).await?;
43
44 {
45 while let Some(v) = stream_next(timeout, &mut stream).await {
46 let v = v?;
47 println!("{v}");
48 }
49 }
50 stream.unsubscribe().await?;
51 Ok(Value::Null)
52 }
53 CliCommands::AddDevice { uri } => client.add_device(cli.account, uri).await,
54 CliCommands::Block {
55 recipient,
56 group_id,
57 } => client.block(cli.account, recipient, group_id).await,
58 CliCommands::DeleteLocalAccountData { ignore_registered } => {
59 client
60 .delete_local_account_data(cli.account, ignore_registered)
61 .await
62 }
63 CliCommands::GetUserStatus { recipient } => {
64 client.get_user_status(cli.account, recipient).await
65 }
66 CliCommands::JoinGroup { uri } => client.join_group(cli.account, uri).await,
67 CliCommands::Link { name } => {
68 let url = client
69 .start_link(cli.account)
70 .await
71 .map_err(|e| RpcError::Custom(format!("JSON-RPC command startLink failed: {e:?}")))?
72 .device_link_uri;
73 println!("{url}");
74 client.finish_link(url, name).await
75 }
76 CliCommands::ListAccounts => client.list_accounts().await,
77 CliCommands::ListContacts {
78 recipient,
79 all_recipients,
80 blocked,
81 name,
82 } => {
83 client
84 .list_contacts(cli.account, recipient, all_recipients, blocked, name)
85 .await
86 }
87 CliCommands::ListDevices => client.list_devices(cli.account).await,
88 CliCommands::ListGroups {
89 detailed: _,
90 group_id,
91 } => client.list_groups(cli.account, group_id).await,
92 CliCommands::ListIdentities { number } => client.list_identities(cli.account, number).await,
93 CliCommands::ListStickerPacks => client.list_sticker_packs(cli.account).await,
94 CliCommands::QuitGroup {
95 group_id,
96 delete,
97 admin,
98 } => {
99 client
100 .quit_group(cli.account, group_id, delete, admin)
101 .await
102 }
103 CliCommands::Register { voice, captcha } => {
104 client.register(cli.account, voice, captcha).await
105 }
106 CliCommands::RemoveContact {
107 recipient,
108 forget,
109 hide,
110 } => {
111 client
112 .remove_contact(cli.account, recipient, forget, hide)
113 .await
114 }
115 CliCommands::RemoveDevice { device_id } => {
116 client.remove_device(cli.account, device_id).await
117 }
118 CliCommands::RemovePin => client.remove_pin(cli.account).await,
119 CliCommands::RemoteDelete {
120 target_timestamp,
121 recipient,
122 group_id,
123 note_to_self,
124 } => {
125 client
126 .remote_delete(
127 cli.account,
128 target_timestamp,
129 recipient,
130 group_id,
131 note_to_self,
132 )
133 .await
134 }
135 CliCommands::Send {
136 recipient,
137 group_id,
138 note_to_self,
139 end_session,
140 message,
141 attachment,
142 mention,
143 text_style,
144 quote_timestamp,
145 quote_author,
146 quote_message,
147 quote_mention,
148 quote_text_style,
149 quote_attachment,
150 preview_url,
151 preview_title,
152 preview_description,
153 preview_image,
154 sticker,
155 story_timestamp,
156 story_author,
157 edit_timestamp,
158 } => {
159 client
160 .send(
161 cli.account,
162 recipient,
163 group_id,
164 note_to_self,
165 end_session,
166 message.unwrap_or_default(),
167 attachment,
168 mention,
169 text_style,
170 quote_timestamp,
171 quote_author,
172 quote_message,
173 quote_mention,
174 quote_text_style,
175 quote_attachment,
176 preview_url,
177 preview_title,
178 preview_description,
179 preview_image,
180 sticker,
181 story_timestamp,
182 story_author,
183 edit_timestamp,
184 )
185 .await
186 }
187 CliCommands::SendContacts => client.send_contacts(cli.account).await,
188 CliCommands::SendPaymentNotification {
189 recipient,
190 receipt,
191 note,
192 } => {
193 client
194 .send_payment_notification(cli.account, recipient, receipt, note)
195 .await
196 }
197 CliCommands::SendReaction {
198 recipient,
199 group_id,
200 note_to_self,
201 emoji,
202 target_author,
203 target_timestamp,
204 remove,
205 story,
206 } => {
207 client
208 .send_reaction(
209 cli.account,
210 recipient,
211 group_id,
212 note_to_self,
213 emoji,
214 target_author,
215 target_timestamp,
216 remove,
217 story,
218 )
219 .await
220 }
221 CliCommands::SendReceipt {
222 recipient,
223 target_timestamp,
224 r#type,
225 } => {
226 client
227 .send_receipt(
228 cli.account,
229 recipient,
230 target_timestamp,
231 match r#type {
232 cli::ReceiptType::Read => "read".to_owned(),
233 cli::ReceiptType::Viewed => "viewed".to_owned(),
234 },
235 )
236 .await
237 }
238 CliCommands::SendSyncRequest => client.send_sync_request(cli.account).await,
239 CliCommands::SendTyping {
240 recipient,
241 group_id,
242 stop,
243 } => {
244 client
245 .send_typing(cli.account, recipient, group_id, stop)
246 .await
247 }
248 CliCommands::SetPin { pin } => client.set_pin(cli.account, pin).await,
249 CliCommands::SubmitRateLimitChallenge { challenge, captcha } => {
250 client
251 .submit_rate_limit_challenge(cli.account, challenge, captcha)
252 .await
253 }
254 CliCommands::Trust {
255 recipient,
256 trust_all_known_keys,
257 verified_safety_number,
258 } => {
259 client
260 .trust(
261 cli.account,
262 recipient,
263 trust_all_known_keys,
264 verified_safety_number,
265 )
266 .await
267 }
268 CliCommands::Unblock {
269 recipient,
270 group_id,
271 } => client.unblock(cli.account, recipient, group_id).await,
272 CliCommands::Unregister { delete_account } => {
273 client.unregister(cli.account, delete_account).await
274 }
275 CliCommands::UpdateAccount {
276 device_name,
277 unrestricted_unidentified_sender,
278 discoverable_by_number,
279 number_sharing,
280 } => {
281 client
282 .update_account(
283 cli.account,
284 device_name,
285 unrestricted_unidentified_sender,
286 discoverable_by_number,
287 number_sharing,
288 )
289 .await
290 }
291 CliCommands::UpdateConfiguration {
292 read_receipts,
293 unidentified_delivery_indicators,
294 typing_indicators,
295 link_previews,
296 } => {
297 client
298 .update_configuration(
299 cli.account,
300 read_receipts,
301 unidentified_delivery_indicators,
302 typing_indicators,
303 link_previews,
304 )
305 .await
306 }
307 CliCommands::UpdateContact {
308 recipient,
309 expiration,
310 name,
311 } => {
312 client
313 .update_contact(cli.account, recipient, name, expiration)
314 .await
315 }
316 CliCommands::UpdateGroup {
317 group_id,
318 name,
319 description,
320 avatar,
321 member,
322 remove_member,
323 admin,
324 remove_admin,
325 ban,
326 unban,
327 reset_link,
328 link,
329 set_permission_add_member,
330 set_permission_edit_details,
331 set_permission_send_messages,
332 expiration,
333 } => {
334 client
335 .update_group(
336 cli.account,
337 group_id,
338 name,
339 description,
340 avatar,
341 member,
342 remove_member,
343 admin,
344 remove_admin,
345 ban,
346 unban,
347 reset_link,
348 link.map(|link| match link {
349 LinkState::Enabled => "enabled".to_owned(),
350 LinkState::EnabledWithApproval => "enabledWithApproval".to_owned(),
351 LinkState::Disabled => "disabled".to_owned(),
352 }),
353 set_permission_add_member.map(|p| match p {
354 GroupPermission::EveryMember => "everyMember".to_owned(),
355 GroupPermission::OnlyAdmins => "onlyAdmins".to_owned(),
356 }),
357 set_permission_edit_details.map(|p| match p {
358 GroupPermission::EveryMember => "everyMember".to_owned(),
359 GroupPermission::OnlyAdmins => "onlyAdmins".to_owned(),
360 }),
361 set_permission_send_messages.map(|p| match p {
362 GroupPermission::EveryMember => "everyMember".to_owned(),
363 GroupPermission::OnlyAdmins => "onlyAdmins".to_owned(),
364 }),
365 expiration,
366 )
367 .await
368 }
369 CliCommands::UpdateProfile {
370 given_name,
371 family_name,
372 about,
373 about_emoji,
374 mobile_coin_address,
375 avatar,
376 remove_avatar,
377 } => {
378 client
379 .update_profile(
380 cli.account,
381 given_name,
382 family_name,
383 about,
384 about_emoji,
385 mobile_coin_address,
386 avatar,
387 remove_avatar,
388 )
389 .await
390 }
391 CliCommands::UploadStickerPack { path } => {
392 client.upload_sticker_pack(cli.account, path).await
393 }
394 CliCommands::Verify {
395 verification_code,
396 pin,
397 } => client.verify(cli.account, verification_code, pin).await,
398 CliCommands::Version => client.version().await,
399 CliCommands::AddStickerPack { uri } => client.add_sticker_pack(cli.account, uri).await,
400 CliCommands::FinishChangeNumber {
401 number,
402 verification_code,
403 pin,
404 } => {
405 client
406 .finish_change_number(cli.account, number, verification_code, pin)
407 .await
408 }
409 CliCommands::GetAttachment {
410 id,
411 recipient,
412 group_id,
413 } => {
414 client
415 .get_attachment(cli.account, id, recipient, group_id)
416 .await
417 }
418 CliCommands::GetAvatar {
419 contact,
420 profile,
421 group_id,
422 } => {
423 client
424 .get_avatar(cli.account, contact, profile, group_id)
425 .await
426 }
427 CliCommands::GetSticker {
428 pack_id,
429 sticker_id,
430 } => client.get_sticker(cli.account, pack_id, sticker_id).await,
431 CliCommands::StartChangeNumber {
432 number,
433 voice,
434 captcha,
435 } => {
436 client
437 .start_change_number(cli.account, number, voice, captcha)
438 .await
439 }
440 CliCommands::SendMessageRequestResponse {
441 recipient,
442 group_id,
443 r#type,
444 } => {
445 client
446 .send_message_request_response(
447 cli.account,
448 recipient,
449 group_id,
450 match r#type {
451 cli::MessageRequestResponseType::Accept => "accept".to_owned(),
452 cli::MessageRequestResponseType::Delete => "delete".to_owned(),
453 },
454 )
455 .await
456 }
457 }
458 }
459
460 async fn connect(cli: Cli) -> Result<Value, RpcError> {
461 if let Some(http) = &cli.json_rpc_http {
462 let uri = if let Some(uri) = http {
463 uri
464 } else {
465 DEFAULT_HTTP
466 };
467 let client = jsonrpc::connect_http(uri)
468 .await
469 .map_err(|e| RpcError::Custom(format!("Failed to connect to socket: {e}")))?;
470
471 handle_command(cli, client).await
472 } else if let Some(tcp) = cli.json_rpc_tcp {
473 let socket_addr = tcp.unwrap_or_else(|| DEFAULT_TCP.parse().unwrap());
474 let client = jsonrpc::connect_tcp(socket_addr)
475 .await
476 .map_err(|e| RpcError::Custom(format!("Failed to connect to socket: {e}")))?;
477
478 handle_command(cli, client).await
479 } else {
480 let socket_path = cli
481 .json_rpc_socket
482 .clone()
483 .unwrap_or(None)
484 .or_else(|| {
485 std::env::var_os("XDG_RUNTIME_DIR").map(|runtime_dir| {
486 PathBuf::from(runtime_dir)
487 .join(DEFAULT_SOCKET_SUFFIX)
488 .into()
489 })
490 })
491 .unwrap_or_else(|| ("/run".to_owned() + DEFAULT_SOCKET_SUFFIX).into());
492 let client = jsonrpc::connect_unix(socket_path)
493 .await
494 .map_err(|e| RpcError::Custom(format!("Failed to connect to socket: {e}")))?;
495
496 handle_command(cli, client).await
497 }
498 }
499
500 async fn stream_next(
501 timeout: f64,
502 stream: &mut Subscription<Value>,
503 ) -> Option<Result<Value, Error>> {
504 if timeout < 0.0 {
505 stream.next().await
506 } else {
507 select! {
508 v = stream.next() => v,
509 _= sleep(Duration::from_millis((timeout * 1000.0) as u64)) => None,
510 }
511 }
512 }