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
;
94 public Manager(String username
, String settingsPath
) {
95 this.username
= username
;
96 this.settingsPath
= settingsPath
;
97 this.dataPath
= this.settingsPath
+ "/data";
98 this.attachmentsPath
= this.settingsPath
+ "/attachments";
100 jsonProcessot
.setVisibility(PropertyAccessor
.ALL
, JsonAutoDetect
.Visibility
.NONE
); // disable autodetect
101 jsonProcessot
.enable(SerializationFeature
.INDENT_OUTPUT
); // for pretty print, you can disable it.
102 jsonProcessot
.enable(SerializationFeature
.WRITE_NULL_MAP_VALUES
);
103 jsonProcessot
.disable(DeserializationFeature
.FAIL_ON_UNKNOWN_PROPERTIES
);
106 public String
getUsername() {
110 public int getDeviceId() {
114 public String
getFileName() {
115 new File(dataPath
).mkdirs();
116 return dataPath
+ "/" + username
;
119 public boolean userExists() {
120 if (username
== null) {
123 File f
= new File(getFileName());
124 return !(!f
.exists() || f
.isDirectory());
127 public boolean userHasKeys() {
128 return signalProtocolStore
!= null;
131 private JsonNode
getNotNullNode(JsonNode parent
, String name
) throws InvalidObjectException
{
132 JsonNode node
= parent
.get(name
);
134 throw new InvalidObjectException(String
.format("Incorrect file format: expected parameter %s not found ", name
));
140 public void load() throws IOException
, InvalidKeyException
{
141 JsonNode rootNode
= jsonProcessot
.readTree(new File(getFileName()));
143 JsonNode node
= rootNode
.get("deviceId");
145 deviceId
= node
.asInt();
147 username
= getNotNullNode(rootNode
, "username").asText();
148 password
= getNotNullNode(rootNode
, "password").asText();
149 if (rootNode
.has("signalingKey")) {
150 signalingKey
= getNotNullNode(rootNode
, "signalingKey").asText();
152 if (rootNode
.has("preKeyIdOffset")) {
153 preKeyIdOffset
= getNotNullNode(rootNode
, "preKeyIdOffset").asInt(0);
157 if (rootNode
.has("nextSignedPreKeyId")) {
158 nextSignedPreKeyId
= getNotNullNode(rootNode
, "nextSignedPreKeyId").asInt();
160 nextSignedPreKeyId
= 0;
162 signalProtocolStore
= jsonProcessot
.convertValue(getNotNullNode(rootNode
, "axolotlStore"), JsonSignalProtocolStore
.class);
163 registered
= getNotNullNode(rootNode
, "registered").asBoolean();
164 JsonNode groupStoreNode
= rootNode
.get("groupStore");
165 if (groupStoreNode
!= null) {
166 groupStore
= jsonProcessot
.convertValue(groupStoreNode
, JsonGroupStore
.class);
168 if (groupStore
== null) {
169 groupStore
= new JsonGroupStore();
171 accountManager
= new SignalServiceAccountManager(URL
, TRUST_STORE
, username
, password
, deviceId
, USER_AGENT
);
173 if (registered
&& accountManager
.getPreKeysCount() < PREKEY_MINIMUM_COUNT
) {
177 } catch (AuthorizationFailedException e
) {
178 System
.err
.println("Authorization failed, was the number registered elsewhere?");
182 private void save() {
183 ObjectNode rootNode
= jsonProcessot
.createObjectNode();
184 rootNode
.put("username", username
)
185 .put("deviceId", deviceId
)
186 .put("password", password
)
187 .put("signalingKey", signalingKey
)
188 .put("preKeyIdOffset", preKeyIdOffset
)
189 .put("nextSignedPreKeyId", nextSignedPreKeyId
)
190 .put("registered", registered
)
191 .putPOJO("axolotlStore", signalProtocolStore
)
192 .putPOJO("groupStore", groupStore
)
195 jsonProcessot
.writeValue(new File(getFileName()), rootNode
);
196 } catch (Exception e
) {
197 System
.err
.println(String
.format("Error saving file: %s", e
.getMessage()));
201 public void createNewIdentity() {
202 IdentityKeyPair identityKey
= KeyHelper
.generateIdentityKeyPair();
203 int registrationId
= KeyHelper
.generateRegistrationId(false);
204 signalProtocolStore
= new JsonSignalProtocolStore(identityKey
, registrationId
);
205 groupStore
= new JsonGroupStore();
210 public boolean isRegistered() {
214 public void register(boolean voiceVerication
) throws IOException
{
215 password
= Util
.getSecret(18);
217 accountManager
= new SignalServiceAccountManager(URL
, TRUST_STORE
, username
, password
, USER_AGENT
);
220 accountManager
.requestVoiceVerificationCode();
222 accountManager
.requestSmsVerificationCode();
228 public URI
getDeviceLinkUri() throws TimeoutException
, IOException
{
229 password
= Util
.getSecret(18);
231 accountManager
= new SignalServiceAccountManager(URL
, TRUST_STORE
, username
, password
, USER_AGENT
);
232 String uuid
= accountManager
.getNewDeviceUuid();
236 return new URI("tsdevice:/?uuid=" + URLEncoder
.encode(uuid
, "utf-8") + "&pub_key=" + URLEncoder
.encode(Base64
.encodeBytesWithoutPadding(signalProtocolStore
.getIdentityKeyPair().getPublicKey().serialize()), "utf-8"));
237 } catch (URISyntaxException e
) {
243 public void finishDeviceLink(String deviceName
) throws IOException
, InvalidKeyException
, TimeoutException
, UserAlreadyExists
{
244 signalingKey
= Util
.getSecret(52);
245 SignalServiceAccountManager
.NewDeviceRegistrationReturn ret
= accountManager
.finishNewDeviceRegistration(signalProtocolStore
.getIdentityKeyPair(), signalingKey
, false, true, signalProtocolStore
.getLocalRegistrationId(), deviceName
);
246 deviceId
= ret
.getDeviceId();
247 username
= ret
.getNumber();
248 // TODO do this check before actually registering
250 throw new UserAlreadyExists(username
, getFileName());
252 signalProtocolStore
= new JsonSignalProtocolStore(ret
.getIdentity(), signalProtocolStore
.getLocalRegistrationId());
258 requestSyncContacts();
263 public List
<DeviceInfo
> getLinkedDevices() throws IOException
{
264 return accountManager
.getDevices();
267 public static Map
<String
, String
> getQueryMap(String query
) {
268 String
[] params
= query
.split("&");
269 Map
<String
, String
> map
= new HashMap
<>();
270 for (String param
: params
) {
273 name
= URLDecoder
.decode(param
.split("=")[0], "utf-8");
274 } catch (UnsupportedEncodingException e
) {
279 value
= URLDecoder
.decode(param
.split("=")[1], "utf-8");
280 } catch (UnsupportedEncodingException e
) {
283 map
.put(name
, value
);
288 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
289 Map
<String
, String
> query
= getQueryMap(linkUri
.getQuery());
290 String deviceIdentifier
= query
.get("uuid");
291 String publicKeyEncoded
= query
.get("pub_key");
293 if (TextUtils
.isEmpty(deviceIdentifier
) || TextUtils
.isEmpty(publicKeyEncoded
)) {
294 throw new RuntimeException("Invalid device link uri");
297 ECPublicKey deviceKey
= Curve
.decodePoint(Base64
.decode(publicKeyEncoded
), 0);
299 addDeviceLink(deviceIdentifier
, deviceKey
);
302 private void addDeviceLink(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
303 IdentityKeyPair identityKeyPair
= signalProtocolStore
.getIdentityKeyPair();
304 String verificationCode
= accountManager
.getNewDeviceVerificationCode();
306 accountManager
.addDevice(deviceIdentifier
, deviceKey
, identityKeyPair
, verificationCode
);
309 private List
<PreKeyRecord
> generatePreKeys() {
310 List
<PreKeyRecord
> records
= new LinkedList
<>();
312 for (int i
= 0; i
< PREKEY_BATCH_SIZE
; i
++) {
313 int preKeyId
= (preKeyIdOffset
+ i
) % Medium
.MAX_VALUE
;
314 ECKeyPair keyPair
= Curve
.generateKeyPair();
315 PreKeyRecord
record = new PreKeyRecord(preKeyId
, keyPair
);
317 signalProtocolStore
.storePreKey(preKeyId
, record);
321 preKeyIdOffset
= (preKeyIdOffset
+ PREKEY_BATCH_SIZE
+ 1) % Medium
.MAX_VALUE
;
327 private PreKeyRecord
getOrGenerateLastResortPreKey() {
328 if (signalProtocolStore
.containsPreKey(Medium
.MAX_VALUE
)) {
330 return signalProtocolStore
.loadPreKey(Medium
.MAX_VALUE
);
331 } catch (InvalidKeyIdException e
) {
332 signalProtocolStore
.removePreKey(Medium
.MAX_VALUE
);
336 ECKeyPair keyPair
= Curve
.generateKeyPair();
337 PreKeyRecord
record = new PreKeyRecord(Medium
.MAX_VALUE
, keyPair
);
339 signalProtocolStore
.storePreKey(Medium
.MAX_VALUE
, record);
345 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
347 ECKeyPair keyPair
= Curve
.generateKeyPair();
348 byte[] signature
= Curve
.calculateSignature(identityKeyPair
.getPrivateKey(), keyPair
.getPublicKey().serialize());
349 SignedPreKeyRecord
record = new SignedPreKeyRecord(nextSignedPreKeyId
, System
.currentTimeMillis(), keyPair
, signature
);
351 signalProtocolStore
.storeSignedPreKey(nextSignedPreKeyId
, record);
352 nextSignedPreKeyId
= (nextSignedPreKeyId
+ 1) % Medium
.MAX_VALUE
;
356 } catch (InvalidKeyException e
) {
357 throw new AssertionError(e
);
361 public void verifyAccount(String verificationCode
) throws IOException
{
362 verificationCode
= verificationCode
.replace("-", "");
363 signalingKey
= Util
.getSecret(52);
364 accountManager
.verifyAccountWithCode(verificationCode
, signalingKey
, signalProtocolStore
.getLocalRegistrationId(), false, true);
366 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
373 private void refreshPreKeys() throws IOException
{
374 List
<PreKeyRecord
> oneTimePreKeys
= generatePreKeys();
375 PreKeyRecord lastResortKey
= getOrGenerateLastResortPreKey();
376 SignedPreKeyRecord signedPreKeyRecord
= generateSignedPreKey(signalProtocolStore
.getIdentityKeyPair());
378 accountManager
.setPreKeys(signalProtocolStore
.getIdentityKeyPair().getPublicKey(), lastResortKey
, signedPreKeyRecord
, oneTimePreKeys
);
382 private static List
<SignalServiceAttachment
> getSignalServiceAttachments(List
<String
> attachments
) throws AttachmentInvalidException
{
383 List
<SignalServiceAttachment
> SignalServiceAttachments
= null;
384 if (attachments
!= null) {
385 SignalServiceAttachments
= new ArrayList
<>(attachments
.size());
386 for (String attachment
: attachments
) {
388 SignalServiceAttachments
.add(createAttachment(attachment
));
389 } catch (IOException e
) {
390 throw new AttachmentInvalidException(attachment
, e
);
394 return SignalServiceAttachments
;
397 private static SignalServiceAttachment
createAttachment(String attachment
) throws IOException
{
398 File attachmentFile
= new File(attachment
);
399 InputStream attachmentStream
= new FileInputStream(attachmentFile
);
400 final long attachmentSize
= attachmentFile
.length();
401 String mime
= Files
.probeContentType(Paths
.get(attachment
));
402 return new SignalServiceAttachmentStream(attachmentStream
, mime
, attachmentSize
, null);
406 public void sendGroupMessage(String messageText
, List
<String
> attachments
,
408 throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
, UntrustedIdentityException
{
409 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
410 if (attachments
!= null) {
411 messageBuilder
.withAttachments(getSignalServiceAttachments(attachments
));
413 if (groupId
!= null) {
414 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.DELIVER
)
417 messageBuilder
.asGroupMessage(group
);
419 SignalServiceDataMessage message
= messageBuilder
.build();
421 Set
<String
> members
= groupStore
.getGroup(groupId
).members
;
422 members
.remove(this.username
);
423 sendMessage(message
, members
);
426 public void sendQuitGroupMessage(byte[] groupId
) throws GroupNotFoundException
, IOException
, EncapsulatedExceptions
, UntrustedIdentityException
{
427 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
)
431 SignalServiceDataMessage message
= SignalServiceDataMessage
.newBuilder()
432 .asGroupMessage(group
)
435 final GroupInfo g
= groupStore
.getGroup(groupId
);
436 g
.members
.remove(this.username
);
437 groupStore
.updateGroup(g
);
439 sendMessage(message
, g
.members
);
442 public byte[] sendUpdateGroupMessage(byte[] groupId
, String name
, Collection
<String
> members
, String avatarFile
) throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
, UntrustedIdentityException
{
444 if (groupId
== null) {
446 g
= new GroupInfo(Util
.getSecretBytes(16));
447 g
.members
.add(username
);
449 g
= groupStore
.getGroup(groupId
);
456 if (members
!= null) {
457 for (String member
: members
) {
459 g
.members
.add(canonicalizeNumber(member
));
460 } catch (InvalidNumberException e
) {
461 System
.err
.println("Failed to add member \"" + member
+ "\" to group: " + e
.getMessage());
462 System
.err
.println("Aborting…");
468 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
471 .withMembers(new ArrayList
<>(g
.members
));
473 if (avatarFile
!= null) {
475 group
.withAvatar(createAttachment(avatarFile
));
478 } catch (IOException e
) {
479 throw new AttachmentInvalidException(avatarFile
, e
);
483 groupStore
.updateGroup(g
);
485 SignalServiceDataMessage message
= SignalServiceDataMessage
.newBuilder()
486 .asGroupMessage(group
.build())
489 final Set
<String
> membersSend
= g
.members
;
490 membersSend
.remove(this.username
);
491 sendMessage(message
, membersSend
);
496 public void sendMessage(String message
, List
<String
> attachments
, String recipient
)
497 throws EncapsulatedExceptions
, AttachmentInvalidException
, IOException
, UntrustedIdentityException
{
498 List
<String
> recipients
= new ArrayList
<>(1);
499 recipients
.add(recipient
);
500 sendMessage(message
, attachments
, recipients
);
504 public void sendMessage(String messageText
, List
<String
> attachments
,
505 List
<String
> recipients
)
506 throws IOException
, EncapsulatedExceptions
, AttachmentInvalidException
, UntrustedIdentityException
{
507 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
508 if (attachments
!= null) {
509 messageBuilder
.withAttachments(getSignalServiceAttachments(attachments
));
511 SignalServiceDataMessage message
= messageBuilder
.build();
513 sendMessage(message
, recipients
);
517 public void sendEndSessionMessage(List
<String
> recipients
) throws IOException
, EncapsulatedExceptions
, UntrustedIdentityException
{
518 SignalServiceDataMessage message
= SignalServiceDataMessage
.newBuilder()
519 .asEndSessionMessage()
522 sendMessage(message
, recipients
);
525 private void requestSyncGroups() throws IOException
{
526 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
).build();
527 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
529 sendMessage(message
);
530 } catch (EncapsulatedExceptions encapsulatedExceptions
) {
531 encapsulatedExceptions
.printStackTrace();
532 } catch (UntrustedIdentityException e
) {
537 private void requestSyncContacts() throws IOException
{
538 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
).build();
539 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
541 sendMessage(message
);
542 } catch (EncapsulatedExceptions encapsulatedExceptions
) {
543 encapsulatedExceptions
.printStackTrace();
544 } catch (UntrustedIdentityException e
) {
549 private void sendMessage(SignalServiceSyncMessage message
)
550 throws IOException
, EncapsulatedExceptions
, UntrustedIdentityException
{
551 SignalServiceMessageSender messageSender
= new SignalServiceMessageSender(URL
, TRUST_STORE
, username
, password
,
552 deviceId
, signalProtocolStore
, USER_AGENT
, Optional
.<SignalServiceMessageSender
.EventListener
>absent());
553 messageSender
.sendMessage(message
);
556 private void sendMessage(SignalServiceDataMessage message
, Collection
<String
> recipients
)
557 throws IOException
, EncapsulatedExceptions
, UntrustedIdentityException
{
559 SignalServiceMessageSender messageSender
= new SignalServiceMessageSender(URL
, TRUST_STORE
, username
, password
,
560 deviceId
, signalProtocolStore
, USER_AGENT
, Optional
.<SignalServiceMessageSender
.EventListener
>absent());
562 Set
<SignalServiceAddress
> recipientsTS
= new HashSet
<>(recipients
.size());
563 for (String recipient
: recipients
) {
565 recipientsTS
.add(getPushAddress(recipient
));
566 } catch (InvalidNumberException e
) {
567 System
.err
.println("Failed to add recipient \"" + recipient
+ "\": " + e
.getMessage());
568 System
.err
.println("Aborting sending.");
574 if (message
.getGroupInfo().isPresent()) {
575 messageSender
.sendMessage(new ArrayList
<>(recipientsTS
), message
);
577 // Send to all individually, so sync messages are sent correctly
578 for (SignalServiceAddress address
: recipientsTS
) {
579 messageSender
.sendMessage(address
, message
);
583 if (message
.isEndSession()) {
584 for (SignalServiceAddress recipient
: recipientsTS
) {
585 handleEndSession(recipient
.getNumber());
593 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) {
594 SignalServiceCipher cipher
= new SignalServiceCipher(new SignalServiceAddress(username
), signalProtocolStore
);
596 return cipher
.decrypt(envelope
);
597 } catch (Exception e
) {
598 // TODO handle all exceptions
604 private void handleEndSession(String source
) {
605 signalProtocolStore
.deleteAllSessions(source
);
608 public interface ReceiveMessageHandler
{
609 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, GroupInfo group
);
612 private GroupInfo
handleSignalServiceDataMessage(SignalServiceDataMessage message
, boolean isSync
, String source
, String destination
) {
613 GroupInfo group
= null;
614 if (message
.getGroupInfo().isPresent()) {
615 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
616 switch (groupInfo
.getType()) {
619 group
= groupStore
.getGroup(groupInfo
.getGroupId());
620 } catch (GroupNotFoundException e
) {
621 group
= new GroupInfo(groupInfo
.getGroupId());
624 if (groupInfo
.getAvatar().isPresent()) {
625 SignalServiceAttachment avatar
= groupInfo
.getAvatar().get();
626 if (avatar
.isPointer()) {
627 long avatarId
= avatar
.asPointer().getId();
629 retrieveAttachment(avatar
.asPointer());
630 // TODO store group avatar in /avatar/groups folder
631 group
.avatarId
= avatarId
;
632 } catch (IOException
| InvalidMessageException e
) {
633 System
.err
.println("Failed to retrieve group avatar (" + avatarId
+ "): " + e
.getMessage());
638 if (groupInfo
.getName().isPresent()) {
639 group
.name
= groupInfo
.getName().get();
642 if (groupInfo
.getMembers().isPresent()) {
643 group
.members
.addAll(groupInfo
.getMembers().get());
646 groupStore
.updateGroup(group
);
650 group
= groupStore
.getGroup(groupInfo
.getGroupId());
651 } catch (GroupNotFoundException e
) {
656 group
= groupStore
.getGroup(groupInfo
.getGroupId());
657 group
.members
.remove(source
);
658 groupStore
.updateGroup(group
);
659 } catch (GroupNotFoundException e
) {
664 if (message
.isEndSession()) {
665 handleEndSession(isSync ? destination
: source
);
667 if (message
.getAttachments().isPresent()) {
668 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
669 if (attachment
.isPointer()) {
671 retrieveAttachment(attachment
.asPointer());
672 } catch (IOException
| InvalidMessageException e
) {
673 System
.err
.println("Failed to retrieve attachment (" + attachment
.asPointer().getId() + "): " + e
.getMessage());
681 public void receiveMessages(int timeoutSeconds
, boolean returnOnTimeout
, ReceiveMessageHandler handler
) throws IOException
{
682 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(URL
, TRUST_STORE
, username
, password
, deviceId
, signalingKey
, USER_AGENT
);
683 SignalServiceMessagePipe messagePipe
= null;
686 messagePipe
= messageReceiver
.createMessagePipe();
689 SignalServiceEnvelope envelope
;
690 SignalServiceContent content
= null;
691 GroupInfo group
= null;
693 envelope
= messagePipe
.read(timeoutSeconds
, TimeUnit
.SECONDS
);
694 if (!envelope
.isReceipt()) {
695 content
= decryptMessage(envelope
);
696 if (content
!= null) {
697 if (content
.getDataMessage().isPresent()) {
698 SignalServiceDataMessage message
= content
.getDataMessage().get();
699 group
= handleSignalServiceDataMessage(message
, false, envelope
.getSource(), username
);
701 if (content
.getSyncMessage().isPresent()) {
702 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
703 if (syncMessage
.getSent().isPresent()) {
704 SignalServiceDataMessage message
= syncMessage
.getSent().get().getMessage();
705 group
= handleSignalServiceDataMessage(message
, true, envelope
.getSource(), syncMessage
.getSent().get().getDestination().get());
707 if (syncMessage
.getRequest().isPresent()) {
708 RequestMessage rm
= syncMessage
.getRequest().get();
709 if (rm
.isContactsRequest()) {
710 // TODO implement when we have contacts
712 if (rm
.isGroupsRequest()) {
715 } catch (EncapsulatedExceptions encapsulatedExceptions
) {
716 encapsulatedExceptions
.printStackTrace();
717 } catch (UntrustedIdentityException e
) {
722 if (syncMessage
.getGroups().isPresent()) {
724 DeviceGroupsInputStream s
= new DeviceGroupsInputStream(retrieveAttachmentAsStream(syncMessage
.getGroups().get().asPointer()));
726 while ((g
= s
.read()) != null) {
729 syncGroup
= groupStore
.getGroup(g
.getId());
730 } catch (GroupNotFoundException e
) {
731 syncGroup
= new GroupInfo(g
.getId());
733 if (g
.getName().isPresent()) {
734 syncGroup
.name
= g
.getName().get();
736 syncGroup
.members
.addAll(g
.getMembers());
737 syncGroup
.active
= g
.isActive();
739 if (g
.getAvatar().isPresent()) {
740 byte[] ava
= new byte[(int) g
.getAvatar().get().getLength()];
741 org
.whispersystems
.signalservice
.internal
.util
.Util
.readFully(g
.getAvatar().get().getInputStream(), ava
);
742 // TODO store group avatar in /avatar/groups folder
744 groupStore
.updateGroup(syncGroup
);
746 } catch (Exception e
) {
750 if (syncMessage
.getContacts().isPresent()) {
752 DeviceContactsInputStream s
= new DeviceContactsInputStream(retrieveAttachmentAsStream(syncMessage
.getContacts().get().asPointer()));
754 while ((c
= s
.read()) != null) {
755 // TODO implement when we have contact storage
756 if (c
.getName().isPresent()) {
761 if (c
.getAvatar().isPresent()) {
762 byte[] ava
= new byte[(int) c
.getAvatar().get().getLength()];
763 org
.whispersystems
.signalservice
.internal
.util
.Util
.readFully(c
.getAvatar().get().getInputStream(), ava
);
764 // TODO store contact avatar in /avatar/contacts folder
767 } catch (Exception e
) {
775 handler
.handleMessage(envelope
, content
, group
);
776 } catch (TimeoutException e
) {
779 } catch (InvalidVersionException e
) {
780 System
.err
.println("Ignoring error: " + e
.getMessage());
784 if (messagePipe
!= null)
785 messagePipe
.shutdown();
789 public File
getAttachmentFile(long attachmentId
) {
790 return new File(attachmentsPath
, attachmentId
+ "");
793 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
) throws IOException
, InvalidMessageException
{
794 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(URL
, TRUST_STORE
, username
, password
, deviceId
, signalingKey
, USER_AGENT
);
796 File tmpFile
= File
.createTempFile("ts_attach_" + pointer
.getId(), ".tmp");
797 InputStream input
= messageReceiver
.retrieveAttachment(pointer
, tmpFile
);
799 new File(attachmentsPath
).mkdirs();
800 File outputFile
= getAttachmentFile(pointer
.getId());
801 OutputStream output
= null;
803 output
= new FileOutputStream(outputFile
);
804 byte[] buffer
= new byte[4096];
807 while ((read
= input
.read(buffer
)) != -1) {
808 output
.write(buffer
, 0, read
);
810 } catch (FileNotFoundException e
) {
814 if (output
!= null) {
818 if (!tmpFile
.delete()) {
819 System
.err
.println("Failed to delete temp file: " + tmpFile
);
822 if (pointer
.getPreview().isPresent()) {
823 File previewFile
= new File(outputFile
+ ".preview");
825 output
= new FileOutputStream(previewFile
);
826 byte[] preview
= pointer
.getPreview().get();
827 output
.write(preview
, 0, preview
.length
);
828 } catch (FileNotFoundException e
) {
832 if (output
!= null) {
840 private InputStream
retrieveAttachmentAsStream(SignalServiceAttachmentPointer pointer
) throws IOException
, InvalidMessageException
{
841 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(URL
, TRUST_STORE
, username
, password
, deviceId
, signalingKey
, USER_AGENT
);
842 File file
= File
.createTempFile("ts_tmp", "tmp");
845 return messageReceiver
.retrieveAttachment(pointer
, file
);
848 private String
canonicalizeNumber(String number
) throws InvalidNumberException
{
849 String localNumber
= username
;
850 return PhoneNumberFormatter
.formatNumber(number
, localNumber
);
853 private SignalServiceAddress
getPushAddress(String number
) throws InvalidNumberException
{
854 String e164number
= canonicalizeNumber(number
);
855 return new SignalServiceAddress(e164number
);
859 public boolean isRemote() {
863 private void sendGroups() throws IOException
, EncapsulatedExceptions
, UntrustedIdentityException
{
864 File contactsFile
= File
.createTempFile("multidevice-contact-update", ".tmp");
867 DeviceGroupsOutputStream out
= new DeviceGroupsOutputStream(new FileOutputStream(contactsFile
));
869 for (GroupInfo
record : groupStore
.getGroups()) {
870 out
.write(new DeviceGroup(record.groupId
, Optional
.fromNullable(record.name
),
871 new ArrayList
<>(record.members
), Optional
.of(new SignalServiceAttachmentStream(new FileInputStream("/home/sebastian/Bilder/00026_150512_14-00-18.JPG"), "octet", new File("/home/sebastian/Bilder/00026_150512_14-00-18.JPG").length(), null)),
878 if (contactsFile
.exists() && contactsFile
.length() > 0) {
879 FileInputStream contactsFileStream
= new FileInputStream(contactsFile
);
880 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
881 .withStream(contactsFileStream
)
882 .withContentType("application/octet-stream")
883 .withLength(contactsFile
.length())
886 sendMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
889 if (contactsFile
!= null) contactsFile
.delete();