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 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 String
getFileName() {
111 new File(dataPath
).mkdirs();
112 return dataPath
+ "/" + username
;
115 public boolean userExists() {
116 if (username
== null) {
119 File f
= new File(getFileName());
120 return !(!f
.exists() || f
.isDirectory());
123 public boolean userHasKeys() {
124 return signalProtocolStore
!= null;
127 private JsonNode
getNotNullNode(JsonNode parent
, String name
) throws InvalidObjectException
{
128 JsonNode node
= parent
.get(name
);
130 throw new InvalidObjectException(String
.format("Incorrect file format: expected parameter %s not found ", name
));
136 public void load() throws IOException
, InvalidKeyException
{
137 JsonNode rootNode
= jsonProcessot
.readTree(new File(getFileName()));
139 JsonNode node
= rootNode
.get("deviceId");
141 deviceId
= node
.asInt();
143 username
= getNotNullNode(rootNode
, "username").asText();
144 password
= getNotNullNode(rootNode
, "password").asText();
145 if (rootNode
.has("signalingKey")) {
146 signalingKey
= getNotNullNode(rootNode
, "signalingKey").asText();
148 if (rootNode
.has("preKeyIdOffset")) {
149 preKeyIdOffset
= getNotNullNode(rootNode
, "preKeyIdOffset").asInt(0);
153 if (rootNode
.has("nextSignedPreKeyId")) {
154 nextSignedPreKeyId
= getNotNullNode(rootNode
, "nextSignedPreKeyId").asInt();
156 nextSignedPreKeyId
= 0;
158 signalProtocolStore
= jsonProcessot
.convertValue(getNotNullNode(rootNode
, "axolotlStore"), JsonSignalProtocolStore
.class);
159 registered
= getNotNullNode(rootNode
, "registered").asBoolean();
160 JsonNode groupStoreNode
= rootNode
.get("groupStore");
161 if (groupStoreNode
!= null) {
162 groupStore
= jsonProcessot
.convertValue(groupStoreNode
, JsonGroupStore
.class);
164 if (groupStore
== null) {
165 groupStore
= new JsonGroupStore();
167 accountManager
= new SignalServiceAccountManager(URL
, TRUST_STORE
, username
, password
, deviceId
, USER_AGENT
);
169 if (registered
&& accountManager
.getPreKeysCount() < PREKEY_MINIMUM_COUNT
) {
173 } catch (AuthorizationFailedException e
) {
174 System
.err
.println("Authorization failed, was the number registered elsewhere?");
178 private void save() {
179 ObjectNode rootNode
= jsonProcessot
.createObjectNode();
180 rootNode
.put("username", username
)
181 .put("deviceId", deviceId
)
182 .put("password", password
)
183 .put("signalingKey", signalingKey
)
184 .put("preKeyIdOffset", preKeyIdOffset
)
185 .put("nextSignedPreKeyId", nextSignedPreKeyId
)
186 .put("registered", registered
)
187 .putPOJO("axolotlStore", signalProtocolStore
)
188 .putPOJO("groupStore", groupStore
)
191 jsonProcessot
.writeValue(new File(getFileName()), rootNode
);
192 } catch (Exception e
) {
193 System
.err
.println(String
.format("Error saving file: %s", e
.getMessage()));
197 public void createNewIdentity() {
198 IdentityKeyPair identityKey
= KeyHelper
.generateIdentityKeyPair();
199 int registrationId
= KeyHelper
.generateRegistrationId(false);
200 signalProtocolStore
= new JsonSignalProtocolStore(identityKey
, registrationId
);
201 groupStore
= new JsonGroupStore();
206 public boolean isRegistered() {
210 public void register(boolean voiceVerication
) throws IOException
{
211 password
= Util
.getSecret(18);
213 accountManager
= new SignalServiceAccountManager(URL
, TRUST_STORE
, username
, password
, USER_AGENT
);
216 accountManager
.requestVoiceVerificationCode();
218 accountManager
.requestSmsVerificationCode();
224 public URI
getDeviceLinkUri() throws TimeoutException
, IOException
{
225 password
= Util
.getSecret(18);
227 accountManager
= new SignalServiceAccountManager(URL
, TRUST_STORE
, username
, password
, USER_AGENT
);
228 String uuid
= accountManager
.getNewDeviceUuid();
232 return new URI("tsdevice:/?uuid=" + URLEncoder
.encode(uuid
, "utf-8") + "&pub_key=" + URLEncoder
.encode(Base64
.encodeBytesWithoutPadding(signalProtocolStore
.getIdentityKeyPair().getPublicKey().serialize()), "utf-8"));
233 } catch (URISyntaxException e
) {
239 public void finishDeviceLink(String deviceName
) throws IOException
, InvalidKeyException
, TimeoutException
, UserAlreadyExists
{
240 signalingKey
= Util
.getSecret(52);
241 SignalServiceAccountManager
.NewDeviceRegistrationReturn ret
= accountManager
.finishNewDeviceRegistration(signalProtocolStore
.getIdentityKeyPair(), signalingKey
, false, true, signalProtocolStore
.getLocalRegistrationId(), deviceName
);
242 deviceId
= ret
.getDeviceId();
243 username
= ret
.getNumber();
244 // TODO do this check before actually registering
246 throw new UserAlreadyExists(username
, getFileName());
248 signalProtocolStore
= new JsonSignalProtocolStore(ret
.getIdentity(), signalProtocolStore
.getLocalRegistrationId());
254 requestSyncContacts();
260 public static Map
<String
, String
> getQueryMap(String query
) {
261 String
[] params
= query
.split("&");
262 Map
<String
, String
> map
= new HashMap
<>();
263 for (String param
: params
) {
266 name
= URLDecoder
.decode(param
.split("=")[0], "utf-8");
267 } catch (UnsupportedEncodingException e
) {
272 value
= URLDecoder
.decode(param
.split("=")[1], "utf-8");
273 } catch (UnsupportedEncodingException e
) {
276 map
.put(name
, value
);
281 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
282 Map
<String
, String
> query
= getQueryMap(linkUri
.getQuery());
283 String deviceIdentifier
= query
.get("uuid");
284 String publicKeyEncoded
= query
.get("pub_key");
286 if (TextUtils
.isEmpty(deviceIdentifier
) || TextUtils
.isEmpty(publicKeyEncoded
)) {
287 throw new RuntimeException("Invalid device link uri");
290 ECPublicKey deviceKey
= Curve
.decodePoint(Base64
.decode(publicKeyEncoded
), 0);
292 addDeviceLink(deviceIdentifier
, deviceKey
);
295 private void addDeviceLink(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
296 IdentityKeyPair identityKeyPair
= signalProtocolStore
.getIdentityKeyPair();
297 String verificationCode
= accountManager
.getNewDeviceVerificationCode();
299 accountManager
.addDevice(deviceIdentifier
, deviceKey
, identityKeyPair
, verificationCode
);
302 private List
<PreKeyRecord
> generatePreKeys() {
303 List
<PreKeyRecord
> records
= new LinkedList
<>();
305 for (int i
= 0; i
< PREKEY_BATCH_SIZE
; i
++) {
306 int preKeyId
= (preKeyIdOffset
+ i
) % Medium
.MAX_VALUE
;
307 ECKeyPair keyPair
= Curve
.generateKeyPair();
308 PreKeyRecord
record = new PreKeyRecord(preKeyId
, keyPair
);
310 signalProtocolStore
.storePreKey(preKeyId
, record);
314 preKeyIdOffset
= (preKeyIdOffset
+ PREKEY_BATCH_SIZE
+ 1) % Medium
.MAX_VALUE
;
320 private PreKeyRecord
getOrGenerateLastResortPreKey() {
321 if (signalProtocolStore
.containsPreKey(Medium
.MAX_VALUE
)) {
323 return signalProtocolStore
.loadPreKey(Medium
.MAX_VALUE
);
324 } catch (InvalidKeyIdException e
) {
325 signalProtocolStore
.removePreKey(Medium
.MAX_VALUE
);
329 ECKeyPair keyPair
= Curve
.generateKeyPair();
330 PreKeyRecord
record = new PreKeyRecord(Medium
.MAX_VALUE
, keyPair
);
332 signalProtocolStore
.storePreKey(Medium
.MAX_VALUE
, record);
338 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
340 ECKeyPair keyPair
= Curve
.generateKeyPair();
341 byte[] signature
= Curve
.calculateSignature(identityKeyPair
.getPrivateKey(), keyPair
.getPublicKey().serialize());
342 SignedPreKeyRecord
record = new SignedPreKeyRecord(nextSignedPreKeyId
, System
.currentTimeMillis(), keyPair
, signature
);
344 signalProtocolStore
.storeSignedPreKey(nextSignedPreKeyId
, record);
345 nextSignedPreKeyId
= (nextSignedPreKeyId
+ 1) % Medium
.MAX_VALUE
;
349 } catch (InvalidKeyException e
) {
350 throw new AssertionError(e
);
354 public void verifyAccount(String verificationCode
) throws IOException
{
355 verificationCode
= verificationCode
.replace("-", "");
356 signalingKey
= Util
.getSecret(52);
357 accountManager
.verifyAccountWithCode(verificationCode
, signalingKey
, signalProtocolStore
.getLocalRegistrationId(), false, true);
359 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
366 private void refreshPreKeys() throws IOException
{
367 List
<PreKeyRecord
> oneTimePreKeys
= generatePreKeys();
368 PreKeyRecord lastResortKey
= getOrGenerateLastResortPreKey();
369 SignedPreKeyRecord signedPreKeyRecord
= generateSignedPreKey(signalProtocolStore
.getIdentityKeyPair());
371 accountManager
.setPreKeys(signalProtocolStore
.getIdentityKeyPair().getPublicKey(), lastResortKey
, signedPreKeyRecord
, oneTimePreKeys
);
375 private static List
<SignalServiceAttachment
> getSignalServiceAttachments(List
<String
> attachments
) throws AttachmentInvalidException
{
376 List
<SignalServiceAttachment
> SignalServiceAttachments
= null;
377 if (attachments
!= null) {
378 SignalServiceAttachments
= new ArrayList
<>(attachments
.size());
379 for (String attachment
: attachments
) {
381 SignalServiceAttachments
.add(createAttachment(attachment
));
382 } catch (IOException e
) {
383 throw new AttachmentInvalidException(attachment
, e
);
387 return SignalServiceAttachments
;
390 private static SignalServiceAttachment
createAttachment(String attachment
) throws IOException
{
391 File attachmentFile
= new File(attachment
);
392 InputStream attachmentStream
= new FileInputStream(attachmentFile
);
393 final long attachmentSize
= attachmentFile
.length();
394 String mime
= Files
.probeContentType(Paths
.get(attachment
));
395 return new SignalServiceAttachmentStream(attachmentStream
, mime
, attachmentSize
, null);
399 public void sendGroupMessage(String messageText
, List
<String
> attachments
,
401 throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
, UntrustedIdentityException
{
402 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
403 if (attachments
!= null) {
404 messageBuilder
.withAttachments(getSignalServiceAttachments(attachments
));
406 if (groupId
!= null) {
407 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.DELIVER
)
410 messageBuilder
.asGroupMessage(group
);
412 SignalServiceDataMessage message
= messageBuilder
.build();
414 Set
<String
> members
= groupStore
.getGroup(groupId
).members
;
415 members
.remove(this.username
);
416 sendMessage(message
, members
);
419 public void sendQuitGroupMessage(byte[] groupId
) throws GroupNotFoundException
, IOException
, EncapsulatedExceptions
, UntrustedIdentityException
{
420 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
)
424 SignalServiceDataMessage message
= SignalServiceDataMessage
.newBuilder()
425 .asGroupMessage(group
)
428 final GroupInfo g
= groupStore
.getGroup(groupId
);
429 g
.members
.remove(this.username
);
430 groupStore
.updateGroup(g
);
432 sendMessage(message
, g
.members
);
435 public byte[] sendUpdateGroupMessage(byte[] groupId
, String name
, Collection
<String
> members
, String avatarFile
) throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
, UntrustedIdentityException
{
437 if (groupId
== null) {
439 g
= new GroupInfo(Util
.getSecretBytes(16));
440 g
.members
.add(username
);
442 g
= groupStore
.getGroup(groupId
);
449 if (members
!= null) {
450 for (String member
: members
) {
452 g
.members
.add(canonicalizeNumber(member
));
453 } catch (InvalidNumberException e
) {
454 System
.err
.println("Failed to add member \"" + member
+ "\" to group: " + e
.getMessage());
455 System
.err
.println("Aborting…");
461 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
464 .withMembers(new ArrayList
<>(g
.members
));
466 if (avatarFile
!= null) {
468 group
.withAvatar(createAttachment(avatarFile
));
471 } catch (IOException e
) {
472 throw new AttachmentInvalidException(avatarFile
, e
);
476 groupStore
.updateGroup(g
);
478 SignalServiceDataMessage message
= SignalServiceDataMessage
.newBuilder()
479 .asGroupMessage(group
.build())
482 final Set
<String
> membersSend
= g
.members
;
483 membersSend
.remove(this.username
);
484 sendMessage(message
, membersSend
);
489 public void sendMessage(String message
, List
<String
> attachments
, String recipient
)
490 throws EncapsulatedExceptions
, AttachmentInvalidException
, IOException
, UntrustedIdentityException
{
491 List
<String
> recipients
= new ArrayList
<>(1);
492 recipients
.add(recipient
);
493 sendMessage(message
, attachments
, recipients
);
497 public void sendMessage(String messageText
, List
<String
> attachments
,
498 List
<String
> recipients
)
499 throws IOException
, EncapsulatedExceptions
, AttachmentInvalidException
, UntrustedIdentityException
{
500 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
501 if (attachments
!= null) {
502 messageBuilder
.withAttachments(getSignalServiceAttachments(attachments
));
504 SignalServiceDataMessage message
= messageBuilder
.build();
506 sendMessage(message
, recipients
);
510 public void sendEndSessionMessage(List
<String
> recipients
) throws IOException
, EncapsulatedExceptions
, UntrustedIdentityException
{
511 SignalServiceDataMessage message
= SignalServiceDataMessage
.newBuilder()
512 .asEndSessionMessage()
515 sendMessage(message
, recipients
);
518 private void requestSyncGroups() throws IOException
{
519 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
).build();
520 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
522 sendMessage(message
);
523 } catch (EncapsulatedExceptions encapsulatedExceptions
) {
524 encapsulatedExceptions
.printStackTrace();
525 } catch (UntrustedIdentityException e
) {
530 private void requestSyncContacts() throws IOException
{
531 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
).build();
532 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
534 sendMessage(message
);
535 } catch (EncapsulatedExceptions encapsulatedExceptions
) {
536 encapsulatedExceptions
.printStackTrace();
537 } catch (UntrustedIdentityException e
) {
542 private void sendMessage(SignalServiceSyncMessage message
)
543 throws IOException
, EncapsulatedExceptions
, UntrustedIdentityException
{
544 SignalServiceMessageSender messageSender
= new SignalServiceMessageSender(URL
, TRUST_STORE
, username
, password
,
545 deviceId
, signalProtocolStore
, USER_AGENT
, Optional
.<SignalServiceMessageSender
.EventListener
>absent());
546 messageSender
.sendMessage(message
);
549 private void sendMessage(SignalServiceDataMessage message
, Collection
<String
> recipients
)
550 throws IOException
, EncapsulatedExceptions
, UntrustedIdentityException
{
551 SignalServiceMessageSender messageSender
= new SignalServiceMessageSender(URL
, TRUST_STORE
, username
, password
,
552 deviceId
, signalProtocolStore
, USER_AGENT
, Optional
.<SignalServiceMessageSender
.EventListener
>absent());
554 Set
<SignalServiceAddress
> recipientsTS
= new HashSet
<>(recipients
.size());
555 for (String recipient
: recipients
) {
557 recipientsTS
.add(getPushAddress(recipient
));
558 } catch (InvalidNumberException e
) {
559 System
.err
.println("Failed to add recipient \"" + recipient
+ "\": " + e
.getMessage());
560 System
.err
.println("Aborting sending.");
566 if (message
.getGroupInfo().isPresent()) {
567 messageSender
.sendMessage(new ArrayList
<>(recipientsTS
), message
);
569 // Send to all individually, so sync messages are sent correctly
570 for (SignalServiceAddress address
: recipientsTS
) {
571 messageSender
.sendMessage(address
, message
);
575 if (message
.isEndSession()) {
576 for (SignalServiceAddress recipient
: recipientsTS
) {
577 handleEndSession(recipient
.getNumber());
583 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) {
584 SignalServiceCipher cipher
= new SignalServiceCipher(new SignalServiceAddress(username
), signalProtocolStore
);
586 return cipher
.decrypt(envelope
);
587 } catch (Exception e
) {
588 // TODO handle all exceptions
594 private void handleEndSession(String source
) {
595 signalProtocolStore
.deleteAllSessions(source
);
598 public interface ReceiveMessageHandler
{
599 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, GroupInfo group
);
602 private GroupInfo
handleSignalServiceDataMessage(SignalServiceDataMessage message
, boolean isSync
, String source
, String destination
) {
603 GroupInfo group
= null;
604 if (message
.getGroupInfo().isPresent()) {
605 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
606 switch (groupInfo
.getType()) {
609 group
= groupStore
.getGroup(groupInfo
.getGroupId());
610 } catch (GroupNotFoundException e
) {
611 group
= new GroupInfo(groupInfo
.getGroupId());
614 if (groupInfo
.getAvatar().isPresent()) {
615 SignalServiceAttachment avatar
= groupInfo
.getAvatar().get();
616 if (avatar
.isPointer()) {
617 long avatarId
= avatar
.asPointer().getId();
619 retrieveAttachment(avatar
.asPointer());
620 // TODO store group avatar in /avatar/groups folder
621 group
.avatarId
= avatarId
;
622 } catch (IOException
| InvalidMessageException e
) {
623 System
.err
.println("Failed to retrieve group avatar (" + avatarId
+ "): " + e
.getMessage());
628 if (groupInfo
.getName().isPresent()) {
629 group
.name
= groupInfo
.getName().get();
632 if (groupInfo
.getMembers().isPresent()) {
633 group
.members
.addAll(groupInfo
.getMembers().get());
636 groupStore
.updateGroup(group
);
640 group
= groupStore
.getGroup(groupInfo
.getGroupId());
641 } catch (GroupNotFoundException e
) {
646 group
= groupStore
.getGroup(groupInfo
.getGroupId());
647 group
.members
.remove(source
);
648 groupStore
.updateGroup(group
);
649 } catch (GroupNotFoundException e
) {
654 if (message
.isEndSession()) {
655 handleEndSession(isSync ? destination
: source
);
657 if (message
.getAttachments().isPresent()) {
658 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
659 if (attachment
.isPointer()) {
661 retrieveAttachment(attachment
.asPointer());
662 } catch (IOException
| InvalidMessageException e
) {
663 System
.err
.println("Failed to retrieve attachment (" + attachment
.asPointer().getId() + "): " + e
.getMessage());
671 public void receiveMessages(int timeoutSeconds
, boolean returnOnTimeout
, ReceiveMessageHandler handler
) throws IOException
{
672 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(URL
, TRUST_STORE
, username
, password
, deviceId
, signalingKey
, USER_AGENT
);
673 SignalServiceMessagePipe messagePipe
= null;
676 messagePipe
= messageReceiver
.createMessagePipe();
679 SignalServiceEnvelope envelope
;
680 SignalServiceContent content
= null;
681 GroupInfo group
= null;
683 envelope
= messagePipe
.read(timeoutSeconds
, TimeUnit
.SECONDS
);
684 if (!envelope
.isReceipt()) {
685 content
= decryptMessage(envelope
);
686 if (content
!= null) {
687 if (content
.getDataMessage().isPresent()) {
688 SignalServiceDataMessage message
= content
.getDataMessage().get();
689 group
= handleSignalServiceDataMessage(message
, false, envelope
.getSource(), username
);
691 if (content
.getSyncMessage().isPresent()) {
692 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
693 if (syncMessage
.getSent().isPresent()) {
694 SignalServiceDataMessage message
= syncMessage
.getSent().get().getMessage();
695 group
= handleSignalServiceDataMessage(message
, true, envelope
.getSource(), syncMessage
.getSent().get().getDestination().get());
697 if (syncMessage
.getRequest().isPresent()) {
698 RequestMessage rm
= syncMessage
.getRequest().get();
699 if (rm
.isContactsRequest()) {
700 // TODO implement when we have contacts
702 if (rm
.isGroupsRequest()) {
705 } catch (EncapsulatedExceptions encapsulatedExceptions
) {
706 encapsulatedExceptions
.printStackTrace();
707 } catch (UntrustedIdentityException e
) {
712 if (syncMessage
.getGroups().isPresent()) {
714 DeviceGroupsInputStream s
= new DeviceGroupsInputStream(retrieveAttachmentAsStream(syncMessage
.getGroups().get().asPointer()));
716 while ((g
= s
.read()) != null) {
719 syncGroup
= groupStore
.getGroup(g
.getId());
720 } catch (GroupNotFoundException e
) {
721 syncGroup
= new GroupInfo(g
.getId());
723 if (g
.getName().isPresent()) {
724 syncGroup
.name
= g
.getName().get();
726 syncGroup
.members
.addAll(g
.getMembers());
727 syncGroup
.active
= g
.isActive();
729 if (g
.getAvatar().isPresent()) {
730 byte[] ava
= new byte[(int) g
.getAvatar().get().getLength()];
731 org
.whispersystems
.signalservice
.internal
.util
.Util
.readFully(g
.getAvatar().get().getInputStream(), ava
);
732 // TODO store group avatar in /avatar/groups folder
734 groupStore
.updateGroup(syncGroup
);
736 } catch (Exception e
) {
740 if (syncMessage
.getContacts().isPresent()) {
742 DeviceContactsInputStream s
= new DeviceContactsInputStream(retrieveAttachmentAsStream(syncMessage
.getContacts().get().asPointer()));
744 while ((c
= s
.read()) != null) {
745 // TODO implement when we have contact storage
746 if (c
.getName().isPresent()) {
751 if (c
.getAvatar().isPresent()) {
752 byte[] ava
= new byte[(int) c
.getAvatar().get().getLength()];
753 org
.whispersystems
.signalservice
.internal
.util
.Util
.readFully(c
.getAvatar().get().getInputStream(), ava
);
754 // TODO store contact avatar in /avatar/contacts folder
757 } catch (Exception e
) {
765 handler
.handleMessage(envelope
, content
, group
);
766 } catch (TimeoutException e
) {
769 } catch (InvalidVersionException e
) {
770 System
.err
.println("Ignoring error: " + e
.getMessage());
774 if (messagePipe
!= null)
775 messagePipe
.shutdown();
779 public File
getAttachmentFile(long attachmentId
) {
780 return new File(attachmentsPath
, attachmentId
+ "");
783 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
) throws IOException
, InvalidMessageException
{
784 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(URL
, TRUST_STORE
, username
, password
, deviceId
, signalingKey
, USER_AGENT
);
786 File tmpFile
= File
.createTempFile("ts_attach_" + pointer
.getId(), ".tmp");
787 InputStream input
= messageReceiver
.retrieveAttachment(pointer
, tmpFile
);
789 new File(attachmentsPath
).mkdirs();
790 File outputFile
= getAttachmentFile(pointer
.getId());
791 OutputStream output
= null;
793 output
= new FileOutputStream(outputFile
);
794 byte[] buffer
= new byte[4096];
797 while ((read
= input
.read(buffer
)) != -1) {
798 output
.write(buffer
, 0, read
);
800 } catch (FileNotFoundException e
) {
804 if (output
!= null) {
808 if (!tmpFile
.delete()) {
809 System
.err
.println("Failed to delete temp file: " + tmpFile
);
812 if (pointer
.getPreview().isPresent()) {
813 File previewFile
= new File(outputFile
+ ".preview");
815 output
= new FileOutputStream(previewFile
);
816 byte[] preview
= pointer
.getPreview().get();
817 output
.write(preview
, 0, preview
.length
);
818 } catch (FileNotFoundException e
) {
822 if (output
!= null) {
830 private InputStream
retrieveAttachmentAsStream(SignalServiceAttachmentPointer pointer
) throws IOException
, InvalidMessageException
{
831 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(URL
, TRUST_STORE
, username
, password
, deviceId
, signalingKey
, USER_AGENT
);
832 File file
= File
.createTempFile("ts_tmp", "tmp");
835 return messageReceiver
.retrieveAttachment(pointer
, file
);
838 private String
canonicalizeNumber(String number
) throws InvalidNumberException
{
839 String localNumber
= username
;
840 return PhoneNumberFormatter
.formatNumber(number
, localNumber
);
843 private SignalServiceAddress
getPushAddress(String number
) throws InvalidNumberException
{
844 String e164number
= canonicalizeNumber(number
);
845 return new SignalServiceAddress(e164number
);
849 public boolean isRemote() {
853 private void sendGroups() throws IOException
, EncapsulatedExceptions
, UntrustedIdentityException
{
854 File contactsFile
= File
.createTempFile("multidevice-contact-update", ".tmp");
857 DeviceGroupsOutputStream out
= new DeviceGroupsOutputStream(new FileOutputStream(contactsFile
));
859 for (GroupInfo
record : groupStore
.getGroups()) {
860 out
.write(new DeviceGroup(record.groupId
, Optional
.fromNullable(record.name
),
861 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)),
868 if (contactsFile
.exists() && contactsFile
.length() > 0) {
869 FileInputStream contactsFileStream
= new FileInputStream(contactsFile
);
870 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
871 .withStream(contactsFileStream
)
872 .withContentType("application/octet-stream")
873 .withLength(contactsFile
.length())
876 sendMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
879 if (contactsFile
!= null) contactsFile
.delete();