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