]> nmode's Git Repositories - signal-cli/blob - src/main/java/cli/Main.java
Improve receiving messages
[signal-cli] / src / main / java / cli / Main.java
1 /**
2 * Copyright (C) 2015 AsamK
3 * <p>
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 * <p>
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 * <p>
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
29 import java.io.File;
30 import java.io.FileInputStream;
31 import java.io.IOException;
32 import java.io.InputStream;
33 import java.nio.file.Files;
34 import java.nio.file.Paths;
35 import java.security.Security;
36 import java.util.ArrayList;
37 import java.util.List;
38
39 public class Main {
40
41 public static void main(String[] args) {
42 // Workaround for BKS truststore
43 Security.insertProviderAt(new org.spongycastle.jce.provider.BouncyCastleProvider(), 1);
44
45 ArgumentParser parser = ArgumentParsers.newArgumentParser("textsecure-cli")
46 .defaultHelp(true)
47 .description("Commandline interface for TextSecure.");
48 Subparsers subparsers = parser.addSubparsers()
49 .title("subcommands")
50 .dest("command")
51 .description("valid subcommands")
52 .help("additional help");
53 Subparser parserRegister = subparsers.addParser("register");
54 parserRegister.addArgument("-v", "--voice")
55 .help("The verification should be done over voice, not sms.")
56 .action(Arguments.storeTrue());
57 Subparser parserVerify = subparsers.addParser("verify");
58 parserVerify.addArgument("verificationCode")
59 .help("The verification code you received via sms or voice call.");
60 Subparser parserSend = subparsers.addParser("send");
61 parserSend.addArgument("recipient")
62 .help("Specify the recipients' phone number.")
63 .nargs("*");
64 parserSend.addArgument("-m", "--message")
65 .help("Specify the message, if missing standard input is used.");
66 parserSend.addArgument("-a", "--attachment")
67 .nargs("*")
68 .help("Add file as attachment");
69 Subparser parserReceive = subparsers.addParser("receive");
70 parser.addArgument("-u", "--username")
71 .required(true)
72 .help("Specify your phone number, that will be used for verification.");
73 Namespace ns = null;
74 try {
75 ns = parser.parseArgs(args);
76 } catch (ArgumentParserException e) {
77 parser.handleError(e);
78 System.exit(1);
79 }
80
81 final String username = ns.getString("username");
82 final Manager m = new Manager(username);
83 if (m.userExists()) {
84 try {
85 m.load();
86 } catch (Exception e) {
87 System.out.println("Loading file error: " + e.getMessage());
88 System.exit(2);
89 }
90 }
91 switch (ns.getString("command")) {
92 case "register":
93 if (!m.userHasKeys()) {
94 m.createNewIdentity();
95 }
96 try {
97 m.register(ns.getBoolean("voice"));
98 } catch (IOException e) {
99 System.out.println("Request verify error: " + e.getMessage());
100 System.exit(3);
101 }
102 break;
103 case "verify":
104 if (!m.userHasKeys()) {
105 System.out.println("User has no keys, first call register.");
106 System.exit(1);
107 }
108 if (m.isRegistered()) {
109 System.out.println("User registration is already verified");
110 System.exit(1);
111 }
112 try {
113 m.verifyAccount(ns.getString("verificationCode"));
114 } catch (IOException e) {
115 System.out.println("Verify error: " + e.getMessage());
116 System.exit(3);
117 }
118 break;
119 case "send":
120 if (!m.isRegistered()) {
121 System.out.println("User is not registered.");
122 System.exit(1);
123 }
124 TextSecureMessageSender messageSender = m.getMessageSender();
125 String messageText = ns.getString("message");
126 if (messageText == null) {
127 try {
128 messageText = IOUtils.toString(System.in);
129 } catch (IOException e) {
130 System.out.println("Failed to read message from stdin: " + e.getMessage());
131 System.exit(1);
132 }
133 }
134 final TextSecureDataMessage.Builder messageBuilder = TextSecureDataMessage.newBuilder().withBody(messageText);
135 final List<String> attachments = ns.<String>getList("attachment");
136 if (attachments != null) {
137 List<TextSecureAttachment> textSecureAttachments = new ArrayList<TextSecureAttachment>(attachments.size());
138 for (String attachment : attachments) {
139 try {
140 File attachmentFile = new File(attachment);
141 InputStream attachmentStream = new FileInputStream(attachmentFile);
142 final long attachmentSize = attachmentFile.length();
143 String mime = Files.probeContentType(Paths.get(attachment));
144 textSecureAttachments.add(new TextSecureAttachmentStream(attachmentStream, mime, attachmentSize, null));
145 } catch (IOException e) {
146 System.out.println("Failed to add attachment \"" + attachment + "\": " + e.getMessage());
147 System.exit(1);
148 }
149 }
150 messageBuilder.withAttachments(textSecureAttachments);
151 }
152 TextSecureDataMessage message = messageBuilder.build();
153 for (String recipient : ns.<String>getList("recipient")) {
154 try {
155 messageSender.sendMessage(new TextSecureAddress(recipient), message);
156 } catch (UntrustedIdentityException | IOException e) {
157 System.out.println("Send message: " + e.getMessage());
158 }
159 }
160 break;
161 case "receive":
162 if (!m.isRegistered()) {
163 System.out.println("User is not registered.");
164 System.exit(1);
165 }
166 try {
167 m.receiveMessages(new Manager.ReceiveMessageHandler() {
168 @Override
169 public void handleMessage(TextSecureEnvelope envelope) {
170 System.out.println("Envelope from: " + envelope.getSource());
171 System.out.println("Timestamp: " + envelope.getTimestamp());
172
173 if (envelope.isReceipt()) {
174 System.out.println("Got receipt.");
175 } else if (envelope.isWhisperMessage() | envelope.isPreKeyWhisperMessage()) {
176 TextSecureContent content = m.decryptMessage(envelope);
177
178 if (content == null) {
179 System.out.println("Failed to decrypt message.");
180 } else {
181 if (content.getDataMessage().isPresent()) {
182 TextSecureDataMessage message = content.getDataMessage().get();
183
184 System.out.println("Body: " + message.getBody().get());
185 if (message.getAttachments().isPresent()) {
186 System.out.println("Attachments: ");
187 for (TextSecureAttachment attachment : message.getAttachments().get()) {
188 System.out.println("- " + attachment.getContentType() + " (" + (attachment.isPointer() ? "Pointer" : "") + (attachment.isStream() ? "Stream" : "") + ")");
189 if (attachment.isPointer()) {
190 System.out.println(" Id: " + attachment.asPointer().getId() + " Key length: " + attachment.asPointer().getKey().length + (attachment.asPointer().getRelay().isPresent() ? " Relay: " + attachment.asPointer().getRelay().get() : ""));
191 }
192 }
193 }
194 }
195 if (content.getSyncMessage().isPresent()) {
196 TextSecureSyncMessage syncMessage = content.getSyncMessage().get();
197 System.out.println("Received sync message");
198 }
199 }
200 } else {
201 System.out.println("Unknown message received.");
202 }
203 System.out.println();
204 }
205 });
206 } catch (IOException e) {
207 System.out.println("Error while receiving message: " + e.getMessage());
208 }
209 break;
210 }
211 m.save();
212 }
213 }