2 * Copyright (C) 2015 AsamK
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.
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.
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/>.
17 package org
.asamk
.signal
;
19 import com
.fasterxml
.jackson
.annotation
.JsonAutoDetect
;
20 import com
.fasterxml
.jackson
.annotation
.PropertyAccessor
;
21 import com
.fasterxml
.jackson
.databind
.DeserializationFeature
;
22 import com
.fasterxml
.jackson
.databind
.JsonNode
;
23 import com
.fasterxml
.jackson
.databind
.ObjectMapper
;
24 import com
.fasterxml
.jackson
.databind
.SerializationFeature
;
25 import com
.fasterxml
.jackson
.databind
.node
.ObjectNode
;
26 import org
.apache
.http
.util
.TextUtils
;
27 import org
.asamk
.Signal
;
28 import org
.whispersystems
.libsignal
.*;
29 import org
.whispersystems
.libsignal
.ecc
.Curve
;
30 import org
.whispersystems
.libsignal
.ecc
.ECKeyPair
;
31 import org
.whispersystems
.libsignal
.ecc
.ECPublicKey
;
32 import org
.whispersystems
.libsignal
.state
.PreKeyRecord
;
33 import org
.whispersystems
.libsignal
.state
.SignalProtocolStore
;
34 import org
.whispersystems
.libsignal
.state
.SignedPreKeyRecord
;
35 import org
.whispersystems
.libsignal
.util
.KeyHelper
;
36 import org
.whispersystems
.libsignal
.util
.Medium
;
37 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
38 import org
.whispersystems
.signalservice
.api
.SignalServiceAccountManager
;
39 import org
.whispersystems
.signalservice
.api
.SignalServiceMessagePipe
;
40 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageReceiver
;
41 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageSender
;
42 import org
.whispersystems
.signalservice
.api
.crypto
.*;
43 import org
.whispersystems
.signalservice
.api
.crypto
.UntrustedIdentityException
;
44 import org
.whispersystems
.signalservice
.api
.messages
.*;
45 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.RequestMessage
;
46 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SignalServiceSyncMessage
;
47 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
48 import org
.whispersystems
.signalservice
.api
.push
.TrustStore
;
49 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.AuthorizationFailedException
;
50 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.EncapsulatedExceptions
;
51 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
52 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
53 import org
.whispersystems
.signalservice
.internal
.push
.SignalServiceProtos
;
57 import java
.net
.URISyntaxException
;
58 import java
.net
.URLDecoder
;
59 import java
.net
.URLEncoder
;
60 import java
.nio
.file
.Files
;
61 import java
.nio
.file
.Paths
;
63 import java
.util
.concurrent
.TimeUnit
;
64 import java
.util
.concurrent
.TimeoutException
;
66 class Manager
implements Signal
{
67 private final static String URL
= "https://textsecure-service.whispersystems.org";
68 private final static TrustStore TRUST_STORE
= new WhisperTrustStore();
70 public final static String PROJECT_NAME
= Manager
.class.getPackage().getImplementationTitle();
71 public final static String PROJECT_VERSION
= Manager
.class.getPackage().getImplementationVersion();
72 private final static String USER_AGENT
= PROJECT_NAME
== null ?
null : PROJECT_NAME
+ " " + PROJECT_VERSION
;
74 private final static int PREKEY_MINIMUM_COUNT
= 20;
75 private static final int PREKEY_BATCH_SIZE
= 100;
77 private final String settingsPath
;
78 private final String dataPath
;
79 private final String attachmentsPath
;
81 private final ObjectMapper jsonProcessot
= new ObjectMapper();
82 private String username
;
83 int deviceId
= SignalServiceAddress
.DEFAULT_DEVICE_ID
;
84 private String password
;
85 private String signalingKey
;
86 private int preKeyIdOffset
;
87 private int nextSignedPreKeyId
;
89 private boolean registered
= false;
91 private SignalProtocolStore signalProtocolStore
;
92 private SignalServiceAccountManager accountManager
;
93 private JsonGroupStore groupStore
;
95 public Manager(String username
, String settingsPath
) {
96 this.username
= username
;
97 this.settingsPath
= settingsPath
;
98 this.dataPath
= this.settingsPath
+ "/data";
99 this.attachmentsPath
= this.settingsPath
+ "/attachments";
101 jsonProcessot
.setVisibility(PropertyAccessor
.ALL
, JsonAutoDetect
.Visibility
.NONE
); // disable autodetect
102 jsonProcessot
.enable(SerializationFeature
.INDENT_OUTPUT
); // for pretty print, you can disable it.
103 jsonProcessot
.enable(SerializationFeature
.WRITE_NULL_MAP_VALUES
);
104 jsonProcessot
.disable(DeserializationFeature
.FAIL_ON_UNKNOWN_PROPERTIES
);
107 public String
getUsername() {
111 public String
getFileName() {
112 new File(dataPath
).mkdirs();
113 return dataPath
+ "/" + username
;
116 public boolean userExists() {
117 if (username
== null) {
120 File f
= new File(getFileName());
121 return !(!f
.exists() || f
.isDirectory());
124 public boolean userHasKeys() {
125 return signalProtocolStore
!= null;
128 private JsonNode
getNotNullNode(JsonNode parent
, String name
) throws InvalidObjectException
{
129 JsonNode node
= parent
.get(name
);
131 throw new InvalidObjectException(String
.format("Incorrect file format: expected parameter %s not found ", name
));
137 public void load() throws IOException
, InvalidKeyException
{
138 JsonNode rootNode
= jsonProcessot
.readTree(new File(getFileName()));
140 JsonNode node
= rootNode
.get("deviceId");
142 deviceId
= node
.asInt();
144 username
= getNotNullNode(rootNode
, "username").asText();
145 password
= getNotNullNode(rootNode
, "password").asText();
146 if (rootNode
.has("signalingKey")) {
147 signalingKey
= getNotNullNode(rootNode
, "signalingKey").asText();
149 if (rootNode
.has("preKeyIdOffset")) {
150 preKeyIdOffset
= getNotNullNode(rootNode
, "preKeyIdOffset").asInt(0);
154 if (rootNode
.has("nextSignedPreKeyId")) {
155 nextSignedPreKeyId
= getNotNullNode(rootNode
, "nextSignedPreKeyId").asInt();
157 nextSignedPreKeyId
= 0;
159 signalProtocolStore
= jsonProcessot
.convertValue(getNotNullNode(rootNode
, "axolotlStore"), JsonSignalProtocolStore
.class);
160 registered
= getNotNullNode(rootNode
, "registered").asBoolean();
161 JsonNode groupStoreNode
= rootNode
.get("groupStore");
162 if (groupStoreNode
!= null) {
163 groupStore
= jsonProcessot
.convertValue(groupStoreNode
, JsonGroupStore
.class);
165 if (groupStore
== null) {
166 groupStore
= new JsonGroupStore();
168 accountManager
= new SignalServiceAccountManager(URL
, TRUST_STORE
, username
, password
, deviceId
, USER_AGENT
);
170 if (registered
&& accountManager
.getPreKeysCount() < PREKEY_MINIMUM_COUNT
) {
174 } catch (AuthorizationFailedException e
) {
175 System
.err
.println("Authorization failed, was the number registered elsewhere?");
179 private void save() {
180 ObjectNode rootNode
= jsonProcessot
.createObjectNode();
181 rootNode
.put("username", username
)
182 .put("deviceId", deviceId
)
183 .put("password", password
)
184 .put("signalingKey", signalingKey
)
185 .put("preKeyIdOffset", preKeyIdOffset
)
186 .put("nextSignedPreKeyId", nextSignedPreKeyId
)
187 .put("registered", registered
)
188 .putPOJO("axolotlStore", signalProtocolStore
)
189 .putPOJO("groupStore", groupStore
)
192 jsonProcessot
.writeValue(new File(getFileName()), rootNode
);
193 } catch (Exception e
) {
194 System
.err
.println(String
.format("Error saving file: %s", e
.getMessage()));
198 public void createNewIdentity() {
199 IdentityKeyPair identityKey
= KeyHelper
.generateIdentityKeyPair();
200 int registrationId
= KeyHelper
.generateRegistrationId(false);
201 signalProtocolStore
= new JsonSignalProtocolStore(identityKey
, registrationId
);
202 groupStore
= new JsonGroupStore();
207 public boolean isRegistered() {
211 public void register(boolean voiceVerication
) throws IOException
{
212 password
= Util
.getSecret(18);
214 accountManager
= new SignalServiceAccountManager(URL
, TRUST_STORE
, username
, password
, USER_AGENT
);
217 accountManager
.requestVoiceVerificationCode();
219 accountManager
.requestSmsVerificationCode();
225 public URI
getDeviceLinkUri() throws TimeoutException
, IOException
{
226 password
= Util
.getSecret(18);
228 accountManager
= new SignalServiceAccountManager(URL
, TRUST_STORE
, username
, password
, USER_AGENT
);
229 String uuid
= accountManager
.getNewDeviceUuid();
233 return new URI("tsdevice:/?uuid=" + URLEncoder
.encode(uuid
, "utf-8") + "&pub_key=" + URLEncoder
.encode(Base64
.encodeBytesWithoutPadding(signalProtocolStore
.getIdentityKeyPair().getPublicKey().serialize()), "utf-8"));
234 } catch (URISyntaxException e
) {
240 public void finishDeviceLink(String deviceName
) throws IOException
, InvalidKeyException
, TimeoutException
, UserAlreadyExists
{
241 signalingKey
= Util
.getSecret(52);
242 SignalServiceAccountManager
.NewDeviceRegistrationReturn ret
= accountManager
.finishNewDeviceRegistration(signalProtocolStore
.getIdentityKeyPair(), signalingKey
, false, true, signalProtocolStore
.getLocalRegistrationId(), deviceName
);
243 deviceId
= ret
.getDeviceId();
244 username
= ret
.getNumber();
245 // TODO do this check before actually registering
247 throw new UserAlreadyExists(username
, getFileName());
249 signalProtocolStore
= new JsonSignalProtocolStore(ret
.getIdentity(), signalProtocolStore
.getLocalRegistrationId());
257 public static Map
<String
, String
> getQueryMap(String query
) {
258 String
[] params
= query
.split("&");
259 Map
<String
, String
> map
= new HashMap
<>();
260 for (String param
: params
) {
263 name
= URLDecoder
.decode(param
.split("=")[0], "utf-8");
264 } catch (UnsupportedEncodingException e
) {
269 value
= URLDecoder
.decode(param
.split("=")[1], "utf-8");
270 } catch (UnsupportedEncodingException e
) {
273 map
.put(name
, value
);
278 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
279 Map
<String
, String
> query
= getQueryMap(linkUri
.getQuery());
280 String deviceIdentifier
= query
.get("uuid");
281 String publicKeyEncoded
= query
.get("pub_key");
283 if (TextUtils
.isEmpty(deviceIdentifier
) || TextUtils
.isEmpty(publicKeyEncoded
)) {
284 throw new RuntimeException("Invalid device link uri");
287 ECPublicKey deviceKey
= Curve
.decodePoint(Base64
.decode(publicKeyEncoded
), 0);
289 addDeviceLink(deviceIdentifier
, deviceKey
);
292 private void addDeviceLink(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
293 IdentityKeyPair identityKeyPair
= signalProtocolStore
.getIdentityKeyPair();
294 String verificationCode
= accountManager
.getNewDeviceVerificationCode();
296 accountManager
.addDevice(deviceIdentifier
, deviceKey
, identityKeyPair
, verificationCode
);
299 private List
<PreKeyRecord
> generatePreKeys() {
300 List
<PreKeyRecord
> records
= new LinkedList
<>();
302 for (int i
= 0; i
< PREKEY_BATCH_SIZE
; i
++) {
303 int preKeyId
= (preKeyIdOffset
+ i
) % Medium
.MAX_VALUE
;
304 ECKeyPair keyPair
= Curve
.generateKeyPair();
305 PreKeyRecord
record = new PreKeyRecord(preKeyId
, keyPair
);
307 signalProtocolStore
.storePreKey(preKeyId
, record);
311 preKeyIdOffset
= (preKeyIdOffset
+ PREKEY_BATCH_SIZE
+ 1) % Medium
.MAX_VALUE
;
317 private PreKeyRecord
getOrGenerateLastResortPreKey() {
318 if (signalProtocolStore
.containsPreKey(Medium
.MAX_VALUE
)) {
320 return signalProtocolStore
.loadPreKey(Medium
.MAX_VALUE
);
321 } catch (InvalidKeyIdException e
) {
322 signalProtocolStore
.removePreKey(Medium
.MAX_VALUE
);
326 ECKeyPair keyPair
= Curve
.generateKeyPair();
327 PreKeyRecord
record = new PreKeyRecord(Medium
.MAX_VALUE
, keyPair
);
329 signalProtocolStore
.storePreKey(Medium
.MAX_VALUE
, record);
335 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
337 ECKeyPair keyPair
= Curve
.generateKeyPair();
338 byte[] signature
= Curve
.calculateSignature(identityKeyPair
.getPrivateKey(), keyPair
.getPublicKey().serialize());
339 SignedPreKeyRecord
record = new SignedPreKeyRecord(nextSignedPreKeyId
, System
.currentTimeMillis(), keyPair
, signature
);
341 signalProtocolStore
.storeSignedPreKey(nextSignedPreKeyId
, record);
342 nextSignedPreKeyId
= (nextSignedPreKeyId
+ 1) % Medium
.MAX_VALUE
;
346 } catch (InvalidKeyException e
) {
347 throw new AssertionError(e
);
351 public void verifyAccount(String verificationCode
) throws IOException
{
352 verificationCode
= verificationCode
.replace("-", "");
353 signalingKey
= Util
.getSecret(52);
354 accountManager
.verifyAccountWithCode(verificationCode
, signalingKey
, signalProtocolStore
.getLocalRegistrationId(), false, true);
356 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
363 private void refreshPreKeys() throws IOException
{
364 List
<PreKeyRecord
> oneTimePreKeys
= generatePreKeys();
365 PreKeyRecord lastResortKey
= getOrGenerateLastResortPreKey();
366 SignedPreKeyRecord signedPreKeyRecord
= generateSignedPreKey(signalProtocolStore
.getIdentityKeyPair());
368 accountManager
.setPreKeys(signalProtocolStore
.getIdentityKeyPair().getPublicKey(), lastResortKey
, signedPreKeyRecord
, oneTimePreKeys
);
372 private static List
<SignalServiceAttachment
> getSignalServiceAttachments(List
<String
> attachments
) throws AttachmentInvalidException
{
373 List
<SignalServiceAttachment
> SignalServiceAttachments
= null;
374 if (attachments
!= null) {
375 SignalServiceAttachments
= new ArrayList
<>(attachments
.size());
376 for (String attachment
: attachments
) {
378 SignalServiceAttachments
.add(createAttachment(attachment
));
379 } catch (IOException e
) {
380 throw new AttachmentInvalidException(attachment
, e
);
384 return SignalServiceAttachments
;
387 private static SignalServiceAttachmentStream
createAttachment(String attachment
) throws IOException
{
388 File attachmentFile
= new File(attachment
);
389 InputStream attachmentStream
= new FileInputStream(attachmentFile
);
390 final long attachmentSize
= attachmentFile
.length();
391 String mime
= Files
.probeContentType(Paths
.get(attachment
));
392 return new SignalServiceAttachmentStream(attachmentStream
, mime
, attachmentSize
, null);
396 public void sendGroupMessage(String messageText
, List
<String
> attachments
,
398 throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
, UntrustedIdentityException
{
399 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
400 if (attachments
!= null) {
401 messageBuilder
.withAttachments(getSignalServiceAttachments(attachments
));
403 if (groupId
!= null) {
404 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.DELIVER
)
407 messageBuilder
.asGroupMessage(group
);
409 SignalServiceDataMessage message
= messageBuilder
.build();
411 sendMessage(message
, groupStore
.getGroup(groupId
).members
);
414 public void sendQuitGroupMessage(byte[] groupId
) throws GroupNotFoundException
, IOException
, EncapsulatedExceptions
, UntrustedIdentityException
{
415 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
)
419 SignalServiceDataMessage message
= SignalServiceDataMessage
.newBuilder()
420 .asGroupMessage(group
)
423 sendMessage(message
, groupStore
.getGroup(groupId
).members
);
426 public byte[] sendUpdateGroupMessage(byte[] groupId
, String name
, Collection
<String
> members
, String avatarFile
) throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
, UntrustedIdentityException
{
428 if (groupId
== null) {
430 g
= new GroupInfo(Util
.getSecretBytes(16));
431 g
.members
.add(username
);
433 g
= groupStore
.getGroup(groupId
);
440 if (members
!= null) {
441 for (String member
: members
) {
443 g
.members
.add(canonicalizeNumber(member
));
444 } catch (InvalidNumberException e
) {
445 System
.err
.println("Failed to add member \"" + member
+ "\" to group: " + e
.getMessage());
446 System
.err
.println("Aborting…");
452 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
455 .withMembers(new ArrayList
<>(g
.members
));
457 if (avatarFile
!= null) {
459 group
.withAvatar(createAttachment(avatarFile
));
462 } catch (IOException e
) {
463 throw new AttachmentInvalidException(avatarFile
, e
);
467 groupStore
.updateGroup(g
);
469 SignalServiceDataMessage message
= SignalServiceDataMessage
.newBuilder()
470 .asGroupMessage(group
.build())
473 sendMessage(message
, g
.members
);
478 public void sendMessage(String message
, List
<String
> attachments
, String recipient
)
479 throws EncapsulatedExceptions
, AttachmentInvalidException
, IOException
, UntrustedIdentityException
{
480 List
<String
> recipients
= new ArrayList
<>(1);
481 recipients
.add(recipient
);
482 sendMessage(message
, attachments
, recipients
);
486 public void sendMessage(String messageText
, List
<String
> attachments
,
487 List
<String
> recipients
)
488 throws IOException
, EncapsulatedExceptions
, AttachmentInvalidException
, UntrustedIdentityException
{
489 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
490 if (attachments
!= null) {
491 messageBuilder
.withAttachments(getSignalServiceAttachments(attachments
));
493 SignalServiceDataMessage message
= messageBuilder
.build();
495 sendMessage(message
, recipients
);
499 public void sendEndSessionMessage(List
<String
> recipients
) throws IOException
, EncapsulatedExceptions
, UntrustedIdentityException
{
500 SignalServiceDataMessage message
= SignalServiceDataMessage
.newBuilder()
501 .asEndSessionMessage()
504 sendMessage(message
, recipients
);
507 private void sendMessage(SignalServiceDataMessage message
, Collection
<String
> recipients
)
508 throws IOException
, EncapsulatedExceptions
, UntrustedIdentityException
{
509 SignalServiceMessageSender messageSender
= new SignalServiceMessageSender(URL
, TRUST_STORE
, username
, password
,
510 deviceId
, signalProtocolStore
, USER_AGENT
, Optional
.<SignalServiceMessageSender
.EventListener
>absent());
512 Set
<SignalServiceAddress
> recipientsTS
= new HashSet
<>(recipients
.size());
513 for (String recipient
: recipients
) {
515 recipientsTS
.add(getPushAddress(recipient
));
516 } catch (InvalidNumberException e
) {
517 System
.err
.println("Failed to add recipient \"" + recipient
+ "\": " + e
.getMessage());
518 System
.err
.println("Aborting sending.");
524 if (message
.getGroupInfo().isPresent()) {
525 messageSender
.sendMessage(new ArrayList
<>(recipientsTS
), message
);
527 // Send to all individually, so sync messages are sent correctly
528 for (SignalServiceAddress address
: recipientsTS
) {
529 messageSender
.sendMessage(address
, message
);
533 if (message
.isEndSession()) {
534 for (SignalServiceAddress recipient
: recipientsTS
) {
535 handleEndSession(recipient
.getNumber());
541 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) {
542 SignalServiceCipher cipher
= new SignalServiceCipher(new SignalServiceAddress(username
), signalProtocolStore
);
544 return cipher
.decrypt(envelope
);
545 } catch (Exception e
) {
546 // TODO handle all exceptions
552 private void handleEndSession(String source
) {
553 signalProtocolStore
.deleteAllSessions(source
);
556 public interface ReceiveMessageHandler
{
557 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, GroupInfo group
);
560 private GroupInfo
handleSignalServiceDataMessage(SignalServiceDataMessage message
, boolean isSync
, String source
, String destination
) {
561 GroupInfo group
= null;
562 if (message
.getGroupInfo().isPresent()) {
563 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
564 switch (groupInfo
.getType()) {
567 group
= groupStore
.getGroup(groupInfo
.getGroupId());
568 } catch (GroupNotFoundException e
) {
569 group
= new GroupInfo(groupInfo
.getGroupId());
572 if (groupInfo
.getAvatar().isPresent()) {
573 SignalServiceAttachment avatar
= groupInfo
.getAvatar().get();
574 if (avatar
.isPointer()) {
575 long avatarId
= avatar
.asPointer().getId();
577 retrieveAttachment(avatar
.asPointer());
578 group
.avatarId
= avatarId
;
579 } catch (IOException
| InvalidMessageException e
) {
580 System
.err
.println("Failed to retrieve group avatar (" + avatarId
+ "): " + e
.getMessage());
585 if (groupInfo
.getName().isPresent()) {
586 group
.name
= groupInfo
.getName().get();
589 if (groupInfo
.getMembers().isPresent()) {
590 group
.members
.addAll(groupInfo
.getMembers().get());
593 groupStore
.updateGroup(group
);
597 group
= groupStore
.getGroup(groupInfo
.getGroupId());
598 } catch (GroupNotFoundException e
) {
603 group
= groupStore
.getGroup(groupInfo
.getGroupId());
604 group
.members
.remove(source
);
605 } catch (GroupNotFoundException e
) {
610 if (message
.isEndSession()) {
611 handleEndSession(isSync ? destination
: source
);
613 if (message
.getAttachments().isPresent()) {
614 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
615 if (attachment
.isPointer()) {
617 retrieveAttachment(attachment
.asPointer());
618 } catch (IOException
| InvalidMessageException e
) {
619 System
.err
.println("Failed to retrieve attachment (" + attachment
.asPointer().getId() + "): " + e
.getMessage());
627 public void receiveMessages(int timeoutSeconds
, boolean returnOnTimeout
, ReceiveMessageHandler handler
) throws IOException
{
628 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(URL
, TRUST_STORE
, username
, password
, deviceId
, signalingKey
, USER_AGENT
);
629 SignalServiceMessagePipe messagePipe
= null;
632 messagePipe
= messageReceiver
.createMessagePipe();
635 SignalServiceEnvelope envelope
;
636 SignalServiceContent content
= null;
637 GroupInfo group
= null;
639 envelope
= messagePipe
.read(timeoutSeconds
, TimeUnit
.SECONDS
);
640 if (!envelope
.isReceipt()) {
641 content
= decryptMessage(envelope
);
642 if (content
!= null) {
643 if (content
.getDataMessage().isPresent()) {
644 SignalServiceDataMessage message
= content
.getDataMessage().get();
645 group
= handleSignalServiceDataMessage(message
, false, envelope
.getSource(), username
);
647 if (content
.getSyncMessage().isPresent()) {
648 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
649 if (syncMessage
.getSent().isPresent()) {
650 SignalServiceDataMessage message
= syncMessage
.getSent().get().getMessage();
651 group
= handleSignalServiceDataMessage(message
, true, envelope
.getSource(), syncMessage
.getSent().get().getDestination().get());
653 if (syncMessage
.getRequest().isPresent()) {
656 if (syncMessage
.getGroups().isPresent()) {
663 handler
.handleMessage(envelope
, content
, group
);
664 } catch (TimeoutException e
) {
667 } catch (InvalidVersionException e
) {
668 System
.err
.println("Ignoring error: " + e
.getMessage());
672 if (messagePipe
!= null)
673 messagePipe
.shutdown();
677 public File
getAttachmentFile(long attachmentId
) {
678 return new File(attachmentsPath
, attachmentId
+ "");
681 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
) throws IOException
, InvalidMessageException
{
682 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(URL
, TRUST_STORE
, username
, password
, deviceId
, signalingKey
, USER_AGENT
);
684 File tmpFile
= File
.createTempFile("ts_attach_" + pointer
.getId(), ".tmp");
685 InputStream input
= messageReceiver
.retrieveAttachment(pointer
, tmpFile
);
687 new File(attachmentsPath
).mkdirs();
688 File outputFile
= getAttachmentFile(pointer
.getId());
689 OutputStream output
= null;
691 output
= new FileOutputStream(outputFile
);
692 byte[] buffer
= new byte[4096];
695 while ((read
= input
.read(buffer
)) != -1) {
696 output
.write(buffer
, 0, read
);
698 } catch (FileNotFoundException e
) {
702 if (output
!= null) {
706 if (!tmpFile
.delete()) {
707 System
.err
.println("Failed to delete temp file: " + tmpFile
);
710 if (pointer
.getPreview().isPresent()) {
711 File previewFile
= new File(outputFile
+ ".preview");
713 output
= new FileOutputStream(previewFile
);
714 byte[] preview
= pointer
.getPreview().get();
715 output
.write(preview
, 0, preview
.length
);
716 } catch (FileNotFoundException e
) {
720 if (output
!= null) {
728 private String
canonicalizeNumber(String number
) throws InvalidNumberException
{
729 String localNumber
= username
;
730 return PhoneNumberFormatter
.formatNumber(number
, localNumber
);
733 private SignalServiceAddress
getPushAddress(String number
) throws InvalidNumberException
{
734 String e164number
= canonicalizeNumber(number
);
735 return new SignalServiceAddress(e164number
);
739 public boolean isRemote() {