]> nmode's Git Repositories - signal-cli/blob - client/src/main.rs
Update README.md
[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::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 } => {
131 client
132 .send(
133 cli.account,
134 recipient,
135 group_id,
136 note_to_self,
137 end_session,
138 message.unwrap_or_default(),
139 attachment,
140 mention,
141 quote_timestamp,
142 quote_author,
143 quote_message,
144 quote_mention,
145 sticker,
146 )
147 .await
148 }
149 cli::CliCommands::SendContacts => client.send_contacts(cli.account).await,
150 cli::CliCommands::SendReaction {
151 recipient,
152 group_id,
153 note_to_self,
154 emoji,
155 target_author,
156 target_timestamp,
157 remove,
158 } => {
159 client
160 .send_reaction(
161 cli.account,
162 recipient,
163 group_id,
164 note_to_self,
165 emoji,
166 target_author,
167 target_timestamp,
168 remove,
169 )
170 .await
171 }
172 cli::CliCommands::SendReceipt {
173 recipient,
174 target_timestamp,
175 r#type,
176 } => {
177 client
178 .send_receipt(
179 cli.account,
180 recipient,
181 target_timestamp,
182 match r#type {
183 cli::ReceiptType::Read => "read".to_owned(),
184 cli::ReceiptType::Viewed => "viewed".to_owned(),
185 },
186 )
187 .await
188 }
189 cli::CliCommands::SendSyncRequest => client.send_sync_request(cli.account).await,
190 cli::CliCommands::SendTyping {
191 recipient,
192 group_id,
193 stop,
194 } => {
195 client
196 .send_typing(cli.account, recipient, group_id, stop)
197 .await
198 }
199 cli::CliCommands::SetPin { pin } => client.set_pin(cli.account, pin).await,
200 cli::CliCommands::SubmitRateLimitChallenge { challenge, captcha } => {
201 client
202 .submit_rate_limit_challenge(cli.account, challenge, captcha)
203 .await
204 }
205 cli::CliCommands::Trust {
206 recipient,
207 trust_all_known_keys,
208 verified_safety_number,
209 } => {
210 client
211 .trust(
212 cli.account,
213 recipient,
214 trust_all_known_keys,
215 verified_safety_number,
216 )
217 .await
218 }
219 cli::CliCommands::Unblock {
220 recipient,
221 group_id,
222 } => client.unblock(cli.account, recipient, group_id).await,
223 cli::CliCommands::Unregister { delete_account } => {
224 client.unregister(cli.account, delete_account).await
225 }
226 cli::CliCommands::UpdateAccount { device_name } => {
227 client.update_account(cli.account, device_name).await
228 }
229 cli::CliCommands::UpdateConfiguration {
230 read_receipts,
231 unidentified_delivery_indicators,
232 typing_indicators,
233 link_previews,
234 } => {
235 client
236 .update_configuration(
237 cli.account,
238 read_receipts,
239 unidentified_delivery_indicators,
240 typing_indicators,
241 link_previews,
242 )
243 .await
244 }
245 cli::CliCommands::UpdateContact {
246 recipient,
247 expiration,
248 name,
249 } => {
250 client
251 .update_contact(cli.account, recipient, name, expiration)
252 .await
253 }
254 cli::CliCommands::UpdateGroup {
255 group_id,
256 name,
257 description,
258 avatar,
259 member,
260 remove_member,
261 admin,
262 remove_admin,
263 ban,
264 unban,
265 reset_link,
266 link,
267 set_permission_add_member,
268 set_permission_edit_details,
269 set_permission_send_messages,
270 expiration,
271 } => {
272 client
273 .update_group(
274 cli.account,
275 group_id,
276 name,
277 description,
278 avatar,
279 member,
280 remove_member,
281 admin,
282 remove_admin,
283 ban,
284 unban,
285 reset_link,
286 link.map(|link| match link {
287 LinkState::Enabled => "enabled".to_owned(),
288 LinkState::EnabledWithApproval => "enabledWithApproval".to_owned(),
289 LinkState::Disabled => "disabled".to_owned(),
290 }),
291 set_permission_add_member.map(|p| match p {
292 GroupPermission::EveryMember => "everyMember".to_owned(),
293 GroupPermission::OnlyAdmins => "onlyAdmins".to_owned(),
294 }),
295 set_permission_edit_details.map(|p| match p {
296 GroupPermission::EveryMember => "everyMember".to_owned(),
297 GroupPermission::OnlyAdmins => "onlyAdmins".to_owned(),
298 }),
299 set_permission_send_messages.map(|p| match p {
300 GroupPermission::EveryMember => "everyMember".to_owned(),
301 GroupPermission::OnlyAdmins => "onlyAdmins".to_owned(),
302 }),
303 expiration,
304 )
305 .await
306 }
307 cli::CliCommands::UpdateProfile {
308 given_name,
309 family_name,
310 about,
311 about_emoji,
312 avatar,
313 remove_avatar,
314 } => {
315 client
316 .update_profile(
317 cli.account,
318 given_name,
319 family_name,
320 about,
321 about_emoji,
322 avatar,
323 remove_avatar,
324 )
325 .await
326 }
327 cli::CliCommands::UploadStickerPack { path } => {
328 client.upload_sticker_pack(cli.account, path).await
329 }
330 cli::CliCommands::Verify {
331 verification_code,
332 pin,
333 } => client.verify(cli.account, verification_code, pin).await,
334 cli::CliCommands::Version => client.version().await,
335 };
336
337 result
338 .map(|v| println!("{v}"))
339 .map_err(|e| anyhow::anyhow!("JSON-RPC command failed: {e:?}",))?;
340 Ok(())
341 }
342
343 async fn connect(cli: &cli::Cli) -> Result<jsonrpc::SignalCliClient, RpcError> {
344 if let Some(tcp) = cli.json_rpc_tcp {
345 let socket_addr = tcp.unwrap_or_else(|| DEFAULT_TCP.parse().unwrap());
346 jsonrpc::connect_tcp(socket_addr).await
347 } else {
348 let socket_path = cli
349 .json_rpc_socket
350 .clone()
351 .unwrap_or(None)
352 .or_else(|| {
353 std::env::var_os("XDG_RUNTIME_DIR").map(|runtime_dir| {
354 PathBuf::from(runtime_dir)
355 .join(DEFAULT_SOCKET_SUFFIX)
356 .into()
357 })
358 })
359 .unwrap_or_else(|| ("/run".to_owned() + DEFAULT_SOCKET_SUFFIX).into());
360 jsonrpc::connect_unix(socket_path).await
361 }
362 }
363
364 async fn stream_next(
365 timeout: f64,
366 stream: &mut TypedSubscriptionStream<Value>,
367 ) -> Option<Result<Value, RpcError>> {
368 if timeout < 0.0 {
369 stream.next().await
370 } else {
371 select! {
372 v = stream.next() => v,
373 _= sleep(Duration::from_millis((timeout * 1000.0) as u64)) => None,
374 }
375 }
376 }