]> nmode's Git Repositories - signal-cli/blob - src/main/java/cli/Main.java
Print detailed error messages for send failures
[signal-cli] / src / main / java / cli / Main.java
1 /**
2 * Copyright (C) 2015 AsamK
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17 package cli;
18
19 import net.sourceforge.argparse4j.ArgumentParsers;
20 import net.sourceforge.argparse4j.impl.Arguments;
21 import net.sourceforge.argparse4j.inf.*;
22 import org.apache.commons.io.IOUtils;
23 import org.whispersystems.textsecure.api.TextSecureMessageSender;
24 import org.whispersystems.textsecure.api.crypto.UntrustedIdentityException;
25 import org.whispersystems.textsecure.api.messages.*;
26 import org.whispersystems.textsecure.api.messages.multidevice.TextSecureSyncMessage;
27 import org.whispersystems.textsecure.api.push.TextSecureAddress;
28 import org.whispersystems.textsecure.api.push.exceptions.EncapsulatedExceptions;
29 import org.whispersystems.textsecure.api.push.exceptions.NetworkFailureException;
30 import org.whispersystems.textsecure.api.push.exceptions.UnregisteredUserException;
31 import org.whispersystems.textsecure.api.util.InvalidNumberException;
32
33 import java.io.File;
34 import java.io.FileInputStream;
35 import java.io.IOException;
36 import java.io.InputStream;
37 import java.nio.file.Files;
38 import java.nio.file.Paths;
39 import java.security.Security;
40 import java.util.ArrayList;
41 import java.util.List;
42
43 public class Main {
44
45 public static void main(String[] args) {
46 // Workaround for BKS truststore
47 Security.insertProviderAt(new org.spongycastle.jce.provider.BouncyCastleProvider(), 1);
48
49 ArgumentParser parser = ArgumentParsers.newArgumentParser("textsecure-cli")
50 .defaultHelp(true)
51 .description("Commandline interface for TextSecure.");
52 Subparsers subparsers = parser.addSubparsers()
53 .title("subcommands")
54 .dest("command")
55 .description("valid subcommands")
56 .help("additional help");
57 Subparser parserRegister = subparsers.addParser("register");
58 parserRegister.addArgument("-v", "--voice")
59 .help("The verification should be done over voice, not sms.")
60 .action(Arguments.storeTrue());
61 Subparser parserVerify = subparsers.addParser("verify");
62 parserVerify.addArgument("verificationCode")
63 .help("The verification code you received via sms or voice call.");
64 Subparser parserSend = subparsers.addParser("send");
65 parserSend.addArgument("recipient")
66 .help("Specify the recipients' phone number.")
67 .nargs("*");
68 parserSend.addArgument("-m", "--message")
69 .help("Specify the message, if missing standard input is used.");
70 parserSend.addArgument("-a", "--attachment")
71 .nargs("*")
72 .help("Add file as attachment");
73 Subparser parserReceive = subparsers.addParser("receive");
74 parser.addArgument("-u", "--username")
75 .required(true)
76 .help("Specify your phone number, that will be used for verification.");
77 Namespace ns = null;
78 try {
79 ns = parser.parseArgs(args);
80 } catch (ArgumentParserException e) {
81 parser.handleError(e);
82 System.exit(1);
83 }
84
85 final String username = ns.getString("username");
86 final Manager m = new Manager(username);
87 if (m.userExists()) {
88 try {
89 m.load();
90 } catch (Exception e) {
91 System.out.println("Loading file error: " + e.getMessage());
92 System.exit(2);
93 }
94 }
95 switch (ns.getString("command")) {
96 case "register":
97 if (!m.userHasKeys()) {
98 m.createNewIdentity();
99 }
100 try {
101 m.register(ns.getBoolean("voice"));
102 } catch (IOException e) {
103 System.out.println("Request verify error: " + e.getMessage());
104 System.exit(3);
105 }
106 break;
107 case "verify":
108 if (!m.userHasKeys()) {
109 System.out.println("User has no keys, first call register.");
110 System.exit(1);
111 }
112 if (m.isRegistered()) {
113 System.out.println("User registration is already verified");
114 System.exit(1);
115 }
116 try {
117 m.verifyAccount(ns.getString("verificationCode"));
118 } catch (IOException e) {
119 System.out.println("Verify error: " + e.getMessage());
120 System.exit(3);
121 }
122 break;
123 case "send":
124 if (!m.isRegistered()) {
125 System.out.println("User is not registered.");
126 System.exit(1);
127 }
128 TextSecureMessageSender messageSender = m.getMessageSender();
129 String messageText = ns.getString("message");
130 if (messageText == null) {
131 try {
132 messageText = IOUtils.toString(System.in);
133 } catch (IOException e) {
134 System.out.println("Failed to read message from stdin: " + e.getMessage());
135 System.exit(1);
136 }
137 }
138 final TextSecureDataMessage.Builder messageBuilder = TextSecureDataMessage.newBuilder().withBody(messageText);
139 final List<String> attachments = ns.<String>getList("attachment");
140 if (attachments != null) {
141 List<TextSecureAttachment> textSecureAttachments = new ArrayList<TextSecureAttachment>(attachments.size());
142 for (String attachment : attachments) {
143 try {
144 File attachmentFile = new File(attachment);
145 InputStream attachmentStream = new FileInputStream(attachmentFile);
146 final long attachmentSize = attachmentFile.length();
147 String mime = Files.probeContentType(Paths.get(attachment));
148 textSecureAttachments.add(new TextSecureAttachmentStream(attachmentStream, mime, attachmentSize, null));
149 } catch (IOException e) {
150 System.out.println("Failed to add attachment \"" + attachment + "\": " + e.getMessage());
151 System.exit(1);
152 }
153 }
154 messageBuilder.withAttachments(textSecureAttachments);
155 }
156 TextSecureDataMessage message = messageBuilder.build();
157
158 List<TextSecureAddress> recipients = new ArrayList<>(ns.<String>getList("recipient").size());
159 for (String recipient : ns.<String>getList("recipient")) {
160 try {
161 recipients.add(m.getPushAddress(recipient));
162 } catch (InvalidNumberException e) {
163 System.out.println("Failed to send message to \"" + recipient + "\": " + e.getMessage());
164 }
165 }
166 try {
167 messageSender.sendMessage(recipients, message);
168 } catch (IOException e) {
169 System.out.println("Failed to send message: " + e.getMessage());
170 } catch (EncapsulatedExceptions e) {
171 System.out.println("Failed to send (some) messages:");
172 for (NetworkFailureException n : e.getNetworkExceptions()) {
173 System.out.println("Network failure for \"" + n.getE164number() + "\": " + n.getMessage());
174 }
175 for (UnregisteredUserException n : e.getUnregisteredUserExceptions()) {
176 System.out.println("Unregistered user \"" + n.getE164Number() + "\": " + n.getMessage());
177 }
178 for (UntrustedIdentityException n : e.getUntrustedIdentityExceptions()) {
179 System.out.println("Untrusted Identity for \"" + n.getE164Number() + "\": " + n.getMessage());
180 }
181 }
182 break;
183 case "receive":
184 if (!m.isRegistered()) {
185 System.out.println("User is not registered.");
186 System.exit(1);
187 }
188 try {
189 m.receiveMessages(new Manager.ReceiveMessageHandler() {
190 @Override
191 public void handleMessage(TextSecureEnvelope envelope) {
192 System.out.println("Envelope from: " + envelope.getSource());
193 System.out.println("Timestamp: " + envelope.getTimestamp());
194
195 if (envelope.isReceipt()) {
196 System.out.println("Got receipt.");
197 } else if (envelope.isWhisperMessage() | envelope.isPreKeyWhisperMessage()) {
198 TextSecureContent content = m.decryptMessage(envelope);
199
200 if (content == null) {
201 System.out.println("Failed to decrypt message.");
202 } else {
203 if (content.getDataMessage().isPresent()) {
204 TextSecureDataMessage message = content.getDataMessage().get();
205 System.out.println("Body: " + message.getBody().get());
206
207 if (message.isEndSession()) {
208 m.handleEndSession(envelope.getSource());
209 } else if (message.getAttachments().isPresent()) {
210 System.out.println("Attachments: ");
211 for (TextSecureAttachment attachment : message.getAttachments().get()) {
212 System.out.println("- " + attachment.getContentType() + " (" + (attachment.isPointer() ? "Pointer" : "") + (attachment.isStream() ? "Stream" : "") + ")");
213 if (attachment.isPointer()) {
214 System.out.println(" Id: " + attachment.asPointer().getId() + " Key length: " + attachment.asPointer().getKey().length + (attachment.asPointer().getRelay().isPresent() ? " Relay: " + attachment.asPointer().getRelay().get() : ""));
215 }
216 }
217 }
218 }
219 if (content.getSyncMessage().isPresent()) {
220 TextSecureSyncMessage syncMessage = content.getSyncMessage().get();
221 System.out.println("Received sync message");
222 }
223 }
224 } else {
225 System.out.println("Unknown message received.");
226 }
227 System.out.println();
228 }
229 });
230 } catch (IOException e) {
231 System.out.println("Error while receiving message: " + e.getMessage());
232 }
233 break;
234 }
235 m.save();
236 }
237 }