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
.SignalServiceCipher
;
43 import org
.whispersystems
.signalservice
.api
.crypto
.UntrustedIdentityException
;
44 import org
.whispersystems
.signalservice
.api
.messages
.*;
45 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.*;
46 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
47 import org
.whispersystems
.signalservice
.api
.push
.TrustStore
;
48 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.AuthorizationFailedException
;
49 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.EncapsulatedExceptions
;
50 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
51 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
52 import org
.whispersystems
.signalservice
.internal
.push
.SignalServiceProtos
;
56 import java
.net
.URISyntaxException
;
57 import java
.net
.URLDecoder
;
58 import java
.net
.URLEncoder
;
59 import java
.nio
.file
.Files
;
60 import java
.nio
.file
.Paths
;
62 import java
.util
.concurrent
.TimeUnit
;
63 import java
.util
.concurrent
.TimeoutException
;
65 class Manager
implements Signal
{
66 private final static String URL
= "https://textsecure-service.whispersystems.org";
67 private final static TrustStore TRUST_STORE
= new WhisperTrustStore();
69 public final static String PROJECT_NAME
= Manager
.class.getPackage().getImplementationTitle();
70 public final static String PROJECT_VERSION
= Manager
.class.getPackage().getImplementationVersion();
71 private final static String USER_AGENT
= PROJECT_NAME
== null ?
null : PROJECT_NAME
+ " " + PROJECT_VERSION
;
73 private final static int PREKEY_MINIMUM_COUNT
= 20;
74 private static final int PREKEY_BATCH_SIZE
= 100;
76 private final String settingsPath
;
77 private final String dataPath
;
78 private final String attachmentsPath
;
80 private final ObjectMapper jsonProcessot
= new ObjectMapper();
81 private String username
;
82 private int deviceId
= SignalServiceAddress
.DEFAULT_DEVICE_ID
;
83 private String password
;
84 private String signalingKey
;
85 private int preKeyIdOffset
;
86 private int nextSignedPreKeyId
;
88 private boolean registered
= false;
90 private SignalProtocolStore signalProtocolStore
;
91 private SignalServiceAccountManager accountManager
;
92 private JsonGroupStore groupStore
;
93 private JsonContactsStore contactStore
;
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 int getDeviceId() {
115 public String
getFileName() {
116 new File(dataPath
).mkdirs();
117 return dataPath
+ "/" + username
;
120 public boolean userExists() {
121 if (username
== null) {
124 File f
= new File(getFileName());
125 return !(!f
.exists() || f
.isDirectory());
128 public boolean userHasKeys() {
129 return signalProtocolStore
!= null;
132 private JsonNode
getNotNullNode(JsonNode parent
, String name
) throws InvalidObjectException
{
133 JsonNode node
= parent
.get(name
);
135 throw new InvalidObjectException(String
.format("Incorrect file format: expected parameter %s not found ", name
));
141 public void load() throws IOException
, InvalidKeyException
{
142 JsonNode rootNode
= jsonProcessot
.readTree(new File(getFileName()));
144 JsonNode node
= rootNode
.get("deviceId");
146 deviceId
= node
.asInt();
148 username
= getNotNullNode(rootNode
, "username").asText();
149 password
= getNotNullNode(rootNode
, "password").asText();
150 if (rootNode
.has("signalingKey")) {
151 signalingKey
= getNotNullNode(rootNode
, "signalingKey").asText();
153 if (rootNode
.has("preKeyIdOffset")) {
154 preKeyIdOffset
= getNotNullNode(rootNode
, "preKeyIdOffset").asInt(0);
158 if (rootNode
.has("nextSignedPreKeyId")) {
159 nextSignedPreKeyId
= getNotNullNode(rootNode
, "nextSignedPreKeyId").asInt();
161 nextSignedPreKeyId
= 0;
163 signalProtocolStore
= jsonProcessot
.convertValue(getNotNullNode(rootNode
, "axolotlStore"), JsonSignalProtocolStore
.class);
164 registered
= getNotNullNode(rootNode
, "registered").asBoolean();
165 JsonNode groupStoreNode
= rootNode
.get("groupStore");
166 if (groupStoreNode
!= null) {
167 groupStore
= jsonProcessot
.convertValue(groupStoreNode
, JsonGroupStore
.class);
169 if (groupStore
== null) {
170 groupStore
= new JsonGroupStore();
172 JsonNode contactStoreNode
= rootNode
.get("contactStore");
173 if (contactStoreNode
!= null) {
174 contactStore
= jsonProcessot
.convertValue(contactStoreNode
, JsonContactsStore
.class);
176 if (contactStore
== null) {
177 contactStore
= new JsonContactsStore();
180 accountManager
= new SignalServiceAccountManager(URL
, TRUST_STORE
, username
, password
, deviceId
, USER_AGENT
);
182 if (registered
&& accountManager
.getPreKeysCount() < PREKEY_MINIMUM_COUNT
) {
186 } catch (AuthorizationFailedException e
) {
187 System
.err
.println("Authorization failed, was the number registered elsewhere?");
191 private void save() {
192 if (username
== null) {
195 ObjectNode rootNode
= jsonProcessot
.createObjectNode();
196 rootNode
.put("username", username
)
197 .put("deviceId", deviceId
)
198 .put("password", password
)
199 .put("signalingKey", signalingKey
)
200 .put("preKeyIdOffset", preKeyIdOffset
)
201 .put("nextSignedPreKeyId", nextSignedPreKeyId
)
202 .put("registered", registered
)
203 .putPOJO("axolotlStore", signalProtocolStore
)
204 .putPOJO("groupStore", groupStore
)
205 .putPOJO("contactStore", contactStore
)
208 jsonProcessot
.writeValue(new File(getFileName()), rootNode
);
209 } catch (Exception e
) {
210 System
.err
.println(String
.format("Error saving file: %s", e
.getMessage()));
214 public void createNewIdentity() {
215 IdentityKeyPair identityKey
= KeyHelper
.generateIdentityKeyPair();
216 int registrationId
= KeyHelper
.generateRegistrationId(false);
217 signalProtocolStore
= new JsonSignalProtocolStore(identityKey
, registrationId
);
218 groupStore
= new JsonGroupStore();
223 public boolean isRegistered() {
227 public void register(boolean voiceVerication
) throws IOException
{
228 password
= Util
.getSecret(18);
230 accountManager
= new SignalServiceAccountManager(URL
, TRUST_STORE
, username
, password
, USER_AGENT
);
233 accountManager
.requestVoiceVerificationCode();
235 accountManager
.requestSmsVerificationCode();
241 public URI
getDeviceLinkUri() throws TimeoutException
, IOException
{
242 password
= Util
.getSecret(18);
244 accountManager
= new SignalServiceAccountManager(URL
, TRUST_STORE
, username
, password
, USER_AGENT
);
245 String uuid
= accountManager
.getNewDeviceUuid();
249 return new URI("tsdevice:/?uuid=" + URLEncoder
.encode(uuid
, "utf-8") + "&pub_key=" + URLEncoder
.encode(Base64
.encodeBytesWithoutPadding(signalProtocolStore
.getIdentityKeyPair().getPublicKey().serialize()), "utf-8"));
250 } catch (URISyntaxException e
) {
256 public void finishDeviceLink(String deviceName
) throws IOException
, InvalidKeyException
, TimeoutException
, UserAlreadyExists
{
257 signalingKey
= Util
.getSecret(52);
258 SignalServiceAccountManager
.NewDeviceRegistrationReturn ret
= accountManager
.finishNewDeviceRegistration(signalProtocolStore
.getIdentityKeyPair(), signalingKey
, false, true, signalProtocolStore
.getLocalRegistrationId(), deviceName
);
259 deviceId
= ret
.getDeviceId();
260 username
= ret
.getNumber();
261 // TODO do this check before actually registering
263 throw new UserAlreadyExists(username
, getFileName());
265 signalProtocolStore
= new JsonSignalProtocolStore(ret
.getIdentity(), signalProtocolStore
.getLocalRegistrationId());
271 requestSyncContacts();
276 public List
<DeviceInfo
> getLinkedDevices() throws IOException
{
277 return accountManager
.getDevices();
280 public void removeLinkedDevices(int deviceId
) throws IOException
{
281 accountManager
.removeDevice(deviceId
);
284 public static Map
<String
, String
> getQueryMap(String query
) {
285 String
[] params
= query
.split("&");
286 Map
<String
, String
> map
= new HashMap
<>();
287 for (String param
: params
) {
290 name
= URLDecoder
.decode(param
.split("=")[0], "utf-8");
291 } catch (UnsupportedEncodingException e
) {
296 value
= URLDecoder
.decode(param
.split("=")[1], "utf-8");
297 } catch (UnsupportedEncodingException e
) {
300 map
.put(name
, value
);
305 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
306 Map
<String
, String
> query
= getQueryMap(linkUri
.getRawQuery());
307 String deviceIdentifier
= query
.get("uuid");
308 String publicKeyEncoded
= query
.get("pub_key");
310 if (TextUtils
.isEmpty(deviceIdentifier
) || TextUtils
.isEmpty(publicKeyEncoded
)) {
311 throw new RuntimeException("Invalid device link uri");
314 ECPublicKey deviceKey
= Curve
.decodePoint(Base64
.decode(publicKeyEncoded
), 0);
316 addDevice(deviceIdentifier
, deviceKey
);
319 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
320 IdentityKeyPair identityKeyPair
= signalProtocolStore
.getIdentityKeyPair();
321 String verificationCode
= accountManager
.getNewDeviceVerificationCode();
323 accountManager
.addDevice(deviceIdentifier
, deviceKey
, identityKeyPair
, verificationCode
);
326 private List
<PreKeyRecord
> generatePreKeys() {
327 List
<PreKeyRecord
> records
= new LinkedList
<>();
329 for (int i
= 0; i
< PREKEY_BATCH_SIZE
; i
++) {
330 int preKeyId
= (preKeyIdOffset
+ i
) % Medium
.MAX_VALUE
;
331 ECKeyPair keyPair
= Curve
.generateKeyPair();
332 PreKeyRecord
record = new PreKeyRecord(preKeyId
, keyPair
);
334 signalProtocolStore
.storePreKey(preKeyId
, record);
338 preKeyIdOffset
= (preKeyIdOffset
+ PREKEY_BATCH_SIZE
+ 1) % Medium
.MAX_VALUE
;
344 private PreKeyRecord
getOrGenerateLastResortPreKey() {
345 if (signalProtocolStore
.containsPreKey(Medium
.MAX_VALUE
)) {
347 return signalProtocolStore
.loadPreKey(Medium
.MAX_VALUE
);
348 } catch (InvalidKeyIdException e
) {
349 signalProtocolStore
.removePreKey(Medium
.MAX_VALUE
);
353 ECKeyPair keyPair
= Curve
.generateKeyPair();
354 PreKeyRecord
record = new PreKeyRecord(Medium
.MAX_VALUE
, keyPair
);
356 signalProtocolStore
.storePreKey(Medium
.MAX_VALUE
, record);
362 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
364 ECKeyPair keyPair
= Curve
.generateKeyPair();
365 byte[] signature
= Curve
.calculateSignature(identityKeyPair
.getPrivateKey(), keyPair
.getPublicKey().serialize());
366 SignedPreKeyRecord
record = new SignedPreKeyRecord(nextSignedPreKeyId
, System
.currentTimeMillis(), keyPair
, signature
);
368 signalProtocolStore
.storeSignedPreKey(nextSignedPreKeyId
, record);
369 nextSignedPreKeyId
= (nextSignedPreKeyId
+ 1) % Medium
.MAX_VALUE
;
373 } catch (InvalidKeyException e
) {
374 throw new AssertionError(e
);
378 public void verifyAccount(String verificationCode
) throws IOException
{
379 verificationCode
= verificationCode
.replace("-", "");
380 signalingKey
= Util
.getSecret(52);
381 accountManager
.verifyAccountWithCode(verificationCode
, signalingKey
, signalProtocolStore
.getLocalRegistrationId(), false, true);
383 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
390 private void refreshPreKeys() throws IOException
{
391 List
<PreKeyRecord
> oneTimePreKeys
= generatePreKeys();
392 PreKeyRecord lastResortKey
= getOrGenerateLastResortPreKey();
393 SignedPreKeyRecord signedPreKeyRecord
= generateSignedPreKey(signalProtocolStore
.getIdentityKeyPair());
395 accountManager
.setPreKeys(signalProtocolStore
.getIdentityKeyPair().getPublicKey(), lastResortKey
, signedPreKeyRecord
, oneTimePreKeys
);
399 private static List
<SignalServiceAttachment
> getSignalServiceAttachments(List
<String
> attachments
) throws AttachmentInvalidException
{
400 List
<SignalServiceAttachment
> SignalServiceAttachments
= null;
401 if (attachments
!= null) {
402 SignalServiceAttachments
= new ArrayList
<>(attachments
.size());
403 for (String attachment
: attachments
) {
405 SignalServiceAttachments
.add(createAttachment(attachment
));
406 } catch (IOException e
) {
407 throw new AttachmentInvalidException(attachment
, e
);
411 return SignalServiceAttachments
;
414 private static SignalServiceAttachment
createAttachment(String attachment
) throws IOException
{
415 File attachmentFile
= new File(attachment
);
416 InputStream attachmentStream
= new FileInputStream(attachmentFile
);
417 final long attachmentSize
= attachmentFile
.length();
418 String mime
= Files
.probeContentType(Paths
.get(attachment
));
419 return new SignalServiceAttachmentStream(attachmentStream
, mime
, attachmentSize
, null);
423 public void sendGroupMessage(String messageText
, List
<String
> attachments
,
425 throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
, UntrustedIdentityException
{
426 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
427 if (attachments
!= null) {
428 messageBuilder
.withAttachments(getSignalServiceAttachments(attachments
));
430 if (groupId
!= null) {
431 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.DELIVER
)
434 messageBuilder
.asGroupMessage(group
);
436 SignalServiceDataMessage message
= messageBuilder
.build();
438 GroupInfo g
= groupStore
.getGroup(groupId
);
440 throw new GroupNotFoundException(groupId
);
442 Set
<String
> members
= g
.members
;
443 members
.remove(this.username
);
444 sendMessage(message
, members
);
447 public void sendQuitGroupMessage(byte[] groupId
) throws GroupNotFoundException
, IOException
, EncapsulatedExceptions
, UntrustedIdentityException
{
448 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
)
452 SignalServiceDataMessage message
= SignalServiceDataMessage
.newBuilder()
453 .asGroupMessage(group
)
456 final GroupInfo g
= groupStore
.getGroup(groupId
);
458 throw new GroupNotFoundException(groupId
);
460 g
.members
.remove(this.username
);
461 groupStore
.updateGroup(g
);
463 sendMessage(message
, g
.members
);
466 public byte[] sendUpdateGroupMessage(byte[] groupId
, String name
, Collection
<String
> members
, String avatarFile
) throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
, UntrustedIdentityException
{
468 if (groupId
== null) {
470 g
= new GroupInfo(Util
.getSecretBytes(16));
471 g
.members
.add(username
);
473 g
= groupStore
.getGroup(groupId
);
475 throw new GroupNotFoundException(groupId
);
483 if (members
!= null) {
484 for (String member
: members
) {
486 g
.members
.add(canonicalizeNumber(member
));
487 } catch (InvalidNumberException e
) {
488 System
.err
.println("Failed to add member \"" + member
+ "\" to group: " + e
.getMessage());
489 System
.err
.println("Aborting…");
495 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
498 .withMembers(new ArrayList
<>(g
.members
));
500 if (avatarFile
!= null) {
502 group
.withAvatar(createAttachment(avatarFile
));
505 } catch (IOException e
) {
506 throw new AttachmentInvalidException(avatarFile
, e
);
510 groupStore
.updateGroup(g
);
512 SignalServiceDataMessage message
= SignalServiceDataMessage
.newBuilder()
513 .asGroupMessage(group
.build())
516 final Set
<String
> membersSend
= g
.members
;
517 membersSend
.remove(this.username
);
518 sendMessage(message
, membersSend
);
523 public void sendMessage(String message
, List
<String
> attachments
, String recipient
)
524 throws EncapsulatedExceptions
, AttachmentInvalidException
, IOException
, UntrustedIdentityException
{
525 List
<String
> recipients
= new ArrayList
<>(1);
526 recipients
.add(recipient
);
527 sendMessage(message
, attachments
, recipients
);
531 public void sendMessage(String messageText
, List
<String
> attachments
,
532 List
<String
> recipients
)
533 throws IOException
, EncapsulatedExceptions
, AttachmentInvalidException
, UntrustedIdentityException
{
534 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
535 if (attachments
!= null) {
536 messageBuilder
.withAttachments(getSignalServiceAttachments(attachments
));
538 SignalServiceDataMessage message
= messageBuilder
.build();
540 sendMessage(message
, recipients
);
544 public void sendEndSessionMessage(List
<String
> recipients
) throws IOException
, EncapsulatedExceptions
, UntrustedIdentityException
{
545 SignalServiceDataMessage message
= SignalServiceDataMessage
.newBuilder()
546 .asEndSessionMessage()
549 sendMessage(message
, recipients
);
552 private void requestSyncGroups() throws IOException
{
553 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
).build();
554 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
556 sendMessage(message
);
557 } catch (EncapsulatedExceptions encapsulatedExceptions
) {
558 encapsulatedExceptions
.printStackTrace();
559 } catch (UntrustedIdentityException e
) {
564 private void requestSyncContacts() throws IOException
{
565 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
).build();
566 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
568 sendMessage(message
);
569 } catch (EncapsulatedExceptions encapsulatedExceptions
) {
570 encapsulatedExceptions
.printStackTrace();
571 } catch (UntrustedIdentityException e
) {
576 private void sendMessage(SignalServiceSyncMessage message
)
577 throws IOException
, EncapsulatedExceptions
, UntrustedIdentityException
{
578 SignalServiceMessageSender messageSender
= new SignalServiceMessageSender(URL
, TRUST_STORE
, username
, password
,
579 deviceId
, signalProtocolStore
, USER_AGENT
, Optional
.<SignalServiceMessageSender
.EventListener
>absent());
580 messageSender
.sendMessage(message
);
583 private void sendMessage(SignalServiceDataMessage message
, Collection
<String
> recipients
)
584 throws IOException
, EncapsulatedExceptions
, UntrustedIdentityException
{
586 SignalServiceMessageSender messageSender
= new SignalServiceMessageSender(URL
, TRUST_STORE
, username
, password
,
587 deviceId
, signalProtocolStore
, USER_AGENT
, Optional
.<SignalServiceMessageSender
.EventListener
>absent());
589 Set
<SignalServiceAddress
> recipientsTS
= new HashSet
<>(recipients
.size());
590 for (String recipient
: recipients
) {
592 recipientsTS
.add(getPushAddress(recipient
));
593 } catch (InvalidNumberException e
) {
594 System
.err
.println("Failed to add recipient \"" + recipient
+ "\": " + e
.getMessage());
595 System
.err
.println("Aborting sending.");
601 if (message
.getGroupInfo().isPresent()) {
602 messageSender
.sendMessage(new ArrayList
<>(recipientsTS
), message
);
604 // Send to all individually, so sync messages are sent correctly
605 for (SignalServiceAddress address
: recipientsTS
) {
606 messageSender
.sendMessage(address
, message
);
610 if (message
.isEndSession()) {
611 for (SignalServiceAddress recipient
: recipientsTS
) {
612 handleEndSession(recipient
.getNumber());
620 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) {
621 SignalServiceCipher cipher
= new SignalServiceCipher(new SignalServiceAddress(username
), signalProtocolStore
);
623 return cipher
.decrypt(envelope
);
624 } catch (Exception e
) {
625 // TODO handle all exceptions
631 private void handleEndSession(String source
) {
632 signalProtocolStore
.deleteAllSessions(source
);
635 public interface ReceiveMessageHandler
{
636 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
);
639 private void handleSignalServiceDataMessage(SignalServiceDataMessage message
, boolean isSync
, String source
, String destination
) {
640 if (message
.getGroupInfo().isPresent()) {
641 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
642 switch (groupInfo
.getType()) {
645 group
= groupStore
.getGroup(groupInfo
.getGroupId());
647 group
= new GroupInfo(groupInfo
.getGroupId());
650 if (groupInfo
.getAvatar().isPresent()) {
651 SignalServiceAttachment avatar
= groupInfo
.getAvatar().get();
652 if (avatar
.isPointer()) {
653 long avatarId
= avatar
.asPointer().getId();
655 retrieveAttachment(avatar
.asPointer());
656 // TODO store group avatar in /avatar/groups folder
657 group
.avatarId
= avatarId
;
658 } catch (IOException
| InvalidMessageException e
) {
659 System
.err
.println("Failed to retrieve group avatar (" + avatarId
+ "): " + e
.getMessage());
664 if (groupInfo
.getName().isPresent()) {
665 group
.name
= groupInfo
.getName().get();
668 if (groupInfo
.getMembers().isPresent()) {
669 group
.members
.addAll(groupInfo
.getMembers().get());
672 groupStore
.updateGroup(group
);
677 group
= groupStore
.getGroup(groupInfo
.getGroupId());
679 group
.members
.remove(source
);
680 groupStore
.updateGroup(group
);
685 if (message
.isEndSession()) {
686 handleEndSession(isSync ? destination
: source
);
688 if (message
.getAttachments().isPresent()) {
689 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
690 if (attachment
.isPointer()) {
692 retrieveAttachment(attachment
.asPointer());
693 } catch (IOException
| InvalidMessageException e
) {
694 System
.err
.println("Failed to retrieve attachment (" + attachment
.asPointer().getId() + "): " + e
.getMessage());
701 public void receiveMessages(int timeoutSeconds
, boolean returnOnTimeout
, ReceiveMessageHandler handler
) throws IOException
{
702 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(URL
, TRUST_STORE
, username
, password
, deviceId
, signalingKey
, USER_AGENT
);
703 SignalServiceMessagePipe messagePipe
= null;
706 messagePipe
= messageReceiver
.createMessagePipe();
709 SignalServiceEnvelope envelope
;
710 SignalServiceContent content
= null;
712 envelope
= messagePipe
.read(timeoutSeconds
, TimeUnit
.SECONDS
);
713 if (!envelope
.isReceipt()) {
714 content
= decryptMessage(envelope
);
715 if (content
!= null) {
716 if (content
.getDataMessage().isPresent()) {
717 SignalServiceDataMessage message
= content
.getDataMessage().get();
718 handleSignalServiceDataMessage(message
, false, envelope
.getSource(), username
);
720 if (content
.getSyncMessage().isPresent()) {
721 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
722 if (syncMessage
.getSent().isPresent()) {
723 SignalServiceDataMessage message
= syncMessage
.getSent().get().getMessage();
724 handleSignalServiceDataMessage(message
, true, envelope
.getSource(), syncMessage
.getSent().get().getDestination().get());
726 if (syncMessage
.getRequest().isPresent()) {
727 RequestMessage rm
= syncMessage
.getRequest().get();
728 if (rm
.isContactsRequest()) {
731 } catch (EncapsulatedExceptions encapsulatedExceptions
) {
732 encapsulatedExceptions
.printStackTrace();
733 } catch (UntrustedIdentityException e
) {
737 if (rm
.isGroupsRequest()) {
740 } catch (EncapsulatedExceptions encapsulatedExceptions
) {
741 encapsulatedExceptions
.printStackTrace();
742 } catch (UntrustedIdentityException e
) {
747 if (syncMessage
.getGroups().isPresent()) {
749 DeviceGroupsInputStream s
= new DeviceGroupsInputStream(retrieveAttachmentAsStream(syncMessage
.getGroups().get().asPointer()));
751 while ((g
= s
.read()) != null) {
752 GroupInfo syncGroup
= groupStore
.getGroup(g
.getId());
753 if (syncGroup
== null) {
754 syncGroup
= new GroupInfo(g
.getId());
756 if (g
.getName().isPresent()) {
757 syncGroup
.name
= g
.getName().get();
759 syncGroup
.members
.addAll(g
.getMembers());
760 syncGroup
.active
= g
.isActive();
762 if (g
.getAvatar().isPresent()) {
763 byte[] ava
= new byte[(int) g
.getAvatar().get().getLength()];
764 org
.whispersystems
.signalservice
.internal
.util
.Util
.readFully(g
.getAvatar().get().getInputStream(), ava
);
765 // TODO store group avatar in /avatar/groups folder
767 groupStore
.updateGroup(syncGroup
);
769 } catch (Exception e
) {
773 if (syncMessage
.getContacts().isPresent()) {
775 DeviceContactsInputStream s
= new DeviceContactsInputStream(retrieveAttachmentAsStream(syncMessage
.getContacts().get().asPointer()));
777 while ((c
= s
.read()) != null) {
778 ContactInfo contact
= new ContactInfo();
779 contact
.number
= c
.getNumber();
780 if (c
.getName().isPresent()) {
781 contact
.name
= c
.getName().get();
783 contactStore
.updateContact(contact
);
785 if (c
.getAvatar().isPresent()) {
786 byte[] ava
= new byte[(int) c
.getAvatar().get().getLength()];
787 org
.whispersystems
.signalservice
.internal
.util
.Util
.readFully(c
.getAvatar().get().getInputStream(), ava
);
788 // TODO store contact avatar in /avatar/contacts folder
791 } catch (Exception e
) {
799 handler
.handleMessage(envelope
, content
);
800 } catch (TimeoutException e
) {
803 } catch (InvalidVersionException e
) {
804 System
.err
.println("Ignoring error: " + e
.getMessage());
808 if (messagePipe
!= null)
809 messagePipe
.shutdown();
813 public File
getAttachmentFile(long attachmentId
) {
814 return new File(attachmentsPath
, attachmentId
+ "");
817 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
) throws IOException
, InvalidMessageException
{
818 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(URL
, TRUST_STORE
, username
, password
, deviceId
, signalingKey
, USER_AGENT
);
820 File tmpFile
= File
.createTempFile("ts_attach_" + pointer
.getId(), ".tmp");
821 InputStream input
= messageReceiver
.retrieveAttachment(pointer
, tmpFile
);
823 new File(attachmentsPath
).mkdirs();
824 File outputFile
= getAttachmentFile(pointer
.getId());
825 OutputStream output
= null;
827 output
= new FileOutputStream(outputFile
);
828 byte[] buffer
= new byte[4096];
831 while ((read
= input
.read(buffer
)) != -1) {
832 output
.write(buffer
, 0, read
);
834 } catch (FileNotFoundException e
) {
838 if (output
!= null) {
842 if (!tmpFile
.delete()) {
843 System
.err
.println("Failed to delete temp file: " + tmpFile
);
846 if (pointer
.getPreview().isPresent()) {
847 File previewFile
= new File(outputFile
+ ".preview");
849 output
= new FileOutputStream(previewFile
);
850 byte[] preview
= pointer
.getPreview().get();
851 output
.write(preview
, 0, preview
.length
);
852 } catch (FileNotFoundException e
) {
856 if (output
!= null) {
864 private InputStream
retrieveAttachmentAsStream(SignalServiceAttachmentPointer pointer
) throws IOException
, InvalidMessageException
{
865 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(URL
, TRUST_STORE
, username
, password
, deviceId
, signalingKey
, USER_AGENT
);
866 File file
= File
.createTempFile("ts_tmp", "tmp");
869 return messageReceiver
.retrieveAttachment(pointer
, file
);
872 private String
canonicalizeNumber(String number
) throws InvalidNumberException
{
873 String localNumber
= username
;
874 return PhoneNumberFormatter
.formatNumber(number
, localNumber
);
877 private SignalServiceAddress
getPushAddress(String number
) throws InvalidNumberException
{
878 String e164number
= canonicalizeNumber(number
);
879 return new SignalServiceAddress(e164number
);
883 public boolean isRemote() {
887 private void sendGroups() throws IOException
, EncapsulatedExceptions
, UntrustedIdentityException
{
888 File groupsFile
= File
.createTempFile("multidevice-group-update", ".tmp");
891 DeviceGroupsOutputStream out
= new DeviceGroupsOutputStream(new FileOutputStream(groupsFile
));
893 for (GroupInfo
record : groupStore
.getGroups()) {
894 out
.write(new DeviceGroup(record.groupId
, Optional
.fromNullable(record.name
),
895 new ArrayList
<>(record.members
), Optional
.<SignalServiceAttachmentStream
>absent(), // TODO add avatar
902 if (groupsFile
.exists() && groupsFile
.length() > 0) {
903 FileInputStream contactsFileStream
= new FileInputStream(groupsFile
);
904 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
905 .withStream(contactsFileStream
)
906 .withContentType("application/octet-stream")
907 .withLength(groupsFile
.length())
910 sendMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
917 private void sendContacts() throws IOException
, EncapsulatedExceptions
, UntrustedIdentityException
{
918 File contactsFile
= File
.createTempFile("multidevice-contact-update", ".tmp");
921 DeviceContactsOutputStream out
= new DeviceContactsOutputStream(new FileOutputStream(contactsFile
));
923 for (ContactInfo
record : contactStore
.getContacts()) {
924 out
.write(new DeviceContact(record.number
, Optional
.fromNullable(record.name
),
925 Optional
.<SignalServiceAttachmentStream
>absent())); // TODO add avatar
931 if (contactsFile
.exists() && contactsFile
.length() > 0) {
932 FileInputStream contactsFileStream
= new FileInputStream(contactsFile
);
933 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
934 .withStream(contactsFileStream
)
935 .withContentType("application/octet-stream")
936 .withLength(contactsFile
.length())
939 sendMessage(SignalServiceSyncMessage
.forContacts(attachmentStream
));
942 contactsFile
.delete();
946 public ContactInfo
getContact(String number
) {
947 return contactStore
.getContact(number
);
950 public GroupInfo
getGroup(byte[] groupId
) {
951 return groupStore
.getGroup(groupId
);