]> nmode's Git Repositories - signal-cli/blob - client/src/main.rs
Add command to retrieve avatars and stickers
[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::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 } => {
279 client
280 .update_account(cli.account, device_name, unrestricted_unidentified_sender)
281 .await
282 }
283 CliCommands::UpdateConfiguration {
284 read_receipts,
285 unidentified_delivery_indicators,
286 typing_indicators,
287 link_previews,
288 } => {
289 client
290 .update_configuration(
291 cli.account,
292 read_receipts,
293 unidentified_delivery_indicators,
294 typing_indicators,
295 link_previews,
296 )
297 .await
298 }
299 CliCommands::UpdateContact {
300 recipient,
301 expiration,
302 name,
303 } => {
304 client
305 .update_contact(cli.account, recipient, name, expiration)
306 .await
307 }
308 CliCommands::UpdateGroup {
309 group_id,
310 name,
311 description,
312 avatar,
313 member,
314 remove_member,
315 admin,
316 remove_admin,
317 ban,
318 unban,
319 reset_link,
320 link,
321 set_permission_add_member,
322 set_permission_edit_details,
323 set_permission_send_messages,
324 expiration,
325 } => {
326 client
327 .update_group(
328 cli.account,
329 group_id,
330 name,
331 description,
332 avatar,
333 member,
334 remove_member,
335 admin,
336 remove_admin,
337 ban,
338 unban,
339 reset_link,
340 link.map(|link| match link {
341 LinkState::Enabled => "enabled".to_owned(),
342 LinkState::EnabledWithApproval => "enabledWithApproval".to_owned(),
343 LinkState::Disabled => "disabled".to_owned(),
344 }),
345 set_permission_add_member.map(|p| match p {
346 GroupPermission::EveryMember => "everyMember".to_owned(),
347 GroupPermission::OnlyAdmins => "onlyAdmins".to_owned(),
348 }),
349 set_permission_edit_details.map(|p| match p {
350 GroupPermission::EveryMember => "everyMember".to_owned(),
351 GroupPermission::OnlyAdmins => "onlyAdmins".to_owned(),
352 }),
353 set_permission_send_messages.map(|p| match p {
354 GroupPermission::EveryMember => "everyMember".to_owned(),
355 GroupPermission::OnlyAdmins => "onlyAdmins".to_owned(),
356 }),
357 expiration,
358 )
359 .await
360 }
361 CliCommands::UpdateProfile {
362 given_name,
363 family_name,
364 about,
365 about_emoji,
366 mobile_coin_address,
367 avatar,
368 remove_avatar,
369 } => {
370 client
371 .update_profile(
372 cli.account,
373 given_name,
374 family_name,
375 about,
376 about_emoji,
377 mobile_coin_address,
378 avatar,
379 remove_avatar,
380 )
381 .await
382 }
383 CliCommands::UploadStickerPack { path } => {
384 client.upload_sticker_pack(cli.account, path).await
385 }
386 CliCommands::Verify {
387 verification_code,
388 pin,
389 } => client.verify(cli.account, verification_code, pin).await,
390 CliCommands::Version => client.version().await,
391 CliCommands::AddStickerPack { uri } => client.add_sticker_pack(cli.account, uri).await,
392 CliCommands::FinishChangeNumber {
393 number,
394 verification_code,
395 pin,
396 } => {
397 client
398 .finish_change_number(cli.account, number, verification_code, pin)
399 .await
400 }
401 CliCommands::GetAttachment {
402 id,
403 recipient,
404 group_id,
405 } => {
406 client
407 .get_attachment(cli.account, id, recipient, group_id)
408 .await
409 }
410 CliCommands::GetAvatar {
411 contact,
412 profile,
413 group_id,
414 } => {
415 client
416 .get_avatar(cli.account, contact, profile, group_id)
417 .await
418 }
419 CliCommands::GetSticker {
420 pack_id,
421 sticker_id,
422 } => client.get_sticker(cli.account, pack_id, sticker_id).await,
423 CliCommands::StartChangeNumber {
424 number,
425 voice,
426 captcha,
427 } => {
428 client
429 .start_change_number(cli.account, number, voice, captcha)
430 .await
431 }
432 }
433 }
434
435 async fn connect(cli: Cli) -> Result<Value, RpcError> {
436 if let Some(http) = &cli.json_rpc_http {
437 let uri = if let Some(uri) = http {
438 uri
439 } else {
440 DEFAULT_HTTP
441 };
442 let client = jsonrpc::connect_http(uri)
443 .await
444 .map_err(|e| RpcError::Custom(format!("Failed to connect to socket: {e}")))?;
445
446 handle_command(cli, client).await
447 } else if let Some(tcp) = cli.json_rpc_tcp {
448 let socket_addr = tcp.unwrap_or_else(|| DEFAULT_TCP.parse().unwrap());
449 let client = jsonrpc::connect_tcp(socket_addr)
450 .await
451 .map_err(|e| RpcError::Custom(format!("Failed to connect to socket: {e}")))?;
452
453 handle_command(cli, client).await
454 } else {
455 let socket_path = cli
456 .json_rpc_socket
457 .clone()
458 .unwrap_or(None)
459 .or_else(|| {
460 std::env::var_os("XDG_RUNTIME_DIR").map(|runtime_dir| {
461 PathBuf::from(runtime_dir)
462 .join(DEFAULT_SOCKET_SUFFIX)
463 .into()
464 })
465 })
466 .unwrap_or_else(|| ("/run".to_owned() + DEFAULT_SOCKET_SUFFIX).into());
467 let client = jsonrpc::connect_unix(socket_path)
468 .await
469 .map_err(|e| RpcError::Custom(format!("Failed to connect to socket: {e}")))?;
470
471 handle_command(cli, client).await
472 }
473 }
474
475 async fn stream_next(
476 timeout: f64,
477 stream: &mut Subscription<Value>,
478 ) -> Option<Result<Value, RpcError>> {
479 if timeout < 0.0 {
480 stream.next().await
481 } else {
482 select! {
483 v = stream.next() => v,
484 _= sleep(Duration::from_millis((timeout * 1000.0) as u64)) => None,
485 }
486 }
487 }