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 sendMessage(message
, groupStore
.getGroup(groupId
).members
);
417 public void sendQuitGroupMessage(byte[] groupId
) throws GroupNotFoundException
, IOException
, EncapsulatedExceptions
, UntrustedIdentityException
{
418 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
)
422 SignalServiceDataMessage message
= SignalServiceDataMessage
.newBuilder()
423 .asGroupMessage(group
)
426 sendMessage(message
, groupStore
.getGroup(groupId
).members
);
429 public byte[] sendUpdateGroupMessage(byte[] groupId
, String name
, Collection
<String
> members
, String avatarFile
) throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
, UntrustedIdentityException
{
431 if (groupId
== null) {
433 g
= new GroupInfo(Util
.getSecretBytes(16));
434 g
.members
.add(username
);
436 g
= groupStore
.getGroup(groupId
);
443 if (members
!= null) {
444 for (String member
: members
) {
446 g
.members
.add(canonicalizeNumber(member
));
447 } catch (InvalidNumberException e
) {
448 System
.err
.println("Failed to add member \"" + member
+ "\" to group: " + e
.getMessage());
449 System
.err
.println("Aborting…");
455 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
458 .withMembers(new ArrayList
<>(g
.members
));
460 if (avatarFile
!= null) {
462 group
.withAvatar(createAttachment(avatarFile
));
465 } catch (IOException e
) {
466 throw new AttachmentInvalidException(avatarFile
, e
);
470 groupStore
.updateGroup(g
);
472 SignalServiceDataMessage message
= SignalServiceDataMessage
.newBuilder()
473 .asGroupMessage(group
.build())
476 sendMessage(message
, g
.members
);
481 public void sendMessage(String message
, List
<String
> attachments
, String recipient
)
482 throws EncapsulatedExceptions
, AttachmentInvalidException
, IOException
, UntrustedIdentityException
{
483 List
<String
> recipients
= new ArrayList
<>(1);
484 recipients
.add(recipient
);
485 sendMessage(message
, attachments
, recipients
);
489 public void sendMessage(String messageText
, List
<String
> attachments
,
490 List
<String
> recipients
)
491 throws IOException
, EncapsulatedExceptions
, AttachmentInvalidException
, UntrustedIdentityException
{
492 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
493 if (attachments
!= null) {
494 messageBuilder
.withAttachments(getSignalServiceAttachments(attachments
));
496 SignalServiceDataMessage message
= messageBuilder
.build();
498 sendMessage(message
, recipients
);
502 public void sendEndSessionMessage(List
<String
> recipients
) throws IOException
, EncapsulatedExceptions
, UntrustedIdentityException
{
503 SignalServiceDataMessage message
= SignalServiceDataMessage
.newBuilder()
504 .asEndSessionMessage()
507 sendMessage(message
, recipients
);
510 private void requestSyncGroups() throws IOException
{
511 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
).build();
512 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
514 sendMessage(message
);
515 } catch (EncapsulatedExceptions encapsulatedExceptions
) {
516 encapsulatedExceptions
.printStackTrace();
517 } catch (UntrustedIdentityException e
) {
522 private void requestSyncContacts() throws IOException
{
523 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
).build();
524 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
526 sendMessage(message
);
527 } catch (EncapsulatedExceptions encapsulatedExceptions
) {
528 encapsulatedExceptions
.printStackTrace();
529 } catch (UntrustedIdentityException e
) {
534 private void sendMessage(SignalServiceSyncMessage message
)
535 throws IOException
, EncapsulatedExceptions
, UntrustedIdentityException
{
536 SignalServiceMessageSender messageSender
= new SignalServiceMessageSender(URL
, TRUST_STORE
, username
, password
,
537 deviceId
, signalProtocolStore
, USER_AGENT
, Optional
.<SignalServiceMessageSender
.EventListener
>absent());
538 messageSender
.sendMessage(message
);
541 private void sendMessage(SignalServiceDataMessage message
, Collection
<String
> recipients
)
542 throws IOException
, EncapsulatedExceptions
, UntrustedIdentityException
{
543 SignalServiceMessageSender messageSender
= new SignalServiceMessageSender(URL
, TRUST_STORE
, username
, password
,
544 deviceId
, signalProtocolStore
, USER_AGENT
, Optional
.<SignalServiceMessageSender
.EventListener
>absent());
546 Set
<SignalServiceAddress
> recipientsTS
= new HashSet
<>(recipients
.size());
547 for (String recipient
: recipients
) {
549 recipientsTS
.add(getPushAddress(recipient
));
550 } catch (InvalidNumberException e
) {
551 System
.err
.println("Failed to add recipient \"" + recipient
+ "\": " + e
.getMessage());
552 System
.err
.println("Aborting sending.");
558 if (message
.getGroupInfo().isPresent()) {
559 messageSender
.sendMessage(new ArrayList
<>(recipientsTS
), message
);
561 // Send to all individually, so sync messages are sent correctly
562 for (SignalServiceAddress address
: recipientsTS
) {
563 messageSender
.sendMessage(address
, message
);
567 if (message
.isEndSession()) {
568 for (SignalServiceAddress recipient
: recipientsTS
) {
569 handleEndSession(recipient
.getNumber());
575 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) {
576 SignalServiceCipher cipher
= new SignalServiceCipher(new SignalServiceAddress(username
), signalProtocolStore
);
578 return cipher
.decrypt(envelope
);
579 } catch (Exception e
) {
580 // TODO handle all exceptions
586 private void handleEndSession(String source
) {
587 signalProtocolStore
.deleteAllSessions(source
);
590 public interface ReceiveMessageHandler
{
591 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, GroupInfo group
);
594 private GroupInfo
handleSignalServiceDataMessage(SignalServiceDataMessage message
, boolean isSync
, String source
, String destination
) {
595 GroupInfo group
= null;
596 if (message
.getGroupInfo().isPresent()) {
597 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
598 switch (groupInfo
.getType()) {
601 group
= groupStore
.getGroup(groupInfo
.getGroupId());
602 } catch (GroupNotFoundException e
) {
603 group
= new GroupInfo(groupInfo
.getGroupId());
606 if (groupInfo
.getAvatar().isPresent()) {
607 SignalServiceAttachment avatar
= groupInfo
.getAvatar().get();
608 if (avatar
.isPointer()) {
609 long avatarId
= avatar
.asPointer().getId();
611 retrieveAttachment(avatar
.asPointer());
612 // TODO store group avatar in /avatar/groups folder
613 group
.avatarId
= avatarId
;
614 } catch (IOException
| InvalidMessageException e
) {
615 System
.err
.println("Failed to retrieve group avatar (" + avatarId
+ "): " + e
.getMessage());
620 if (groupInfo
.getName().isPresent()) {
621 group
.name
= groupInfo
.getName().get();
624 if (groupInfo
.getMembers().isPresent()) {
625 group
.members
.addAll(groupInfo
.getMembers().get());
628 groupStore
.updateGroup(group
);
632 group
= groupStore
.getGroup(groupInfo
.getGroupId());
633 } catch (GroupNotFoundException e
) {
638 group
= groupStore
.getGroup(groupInfo
.getGroupId());
639 group
.members
.remove(source
);
640 } catch (GroupNotFoundException e
) {
645 if (message
.isEndSession()) {
646 handleEndSession(isSync ? destination
: source
);
648 if (message
.getAttachments().isPresent()) {
649 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
650 if (attachment
.isPointer()) {
652 retrieveAttachment(attachment
.asPointer());
653 } catch (IOException
| InvalidMessageException e
) {
654 System
.err
.println("Failed to retrieve attachment (" + attachment
.asPointer().getId() + "): " + e
.getMessage());
662 public void receiveMessages(int timeoutSeconds
, boolean returnOnTimeout
, ReceiveMessageHandler handler
) throws IOException
{
663 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(URL
, TRUST_STORE
, username
, password
, deviceId
, signalingKey
, USER_AGENT
);
664 SignalServiceMessagePipe messagePipe
= null;
667 messagePipe
= messageReceiver
.createMessagePipe();
670 SignalServiceEnvelope envelope
;
671 SignalServiceContent content
= null;
672 GroupInfo group
= null;
674 envelope
= messagePipe
.read(timeoutSeconds
, TimeUnit
.SECONDS
);
675 if (!envelope
.isReceipt()) {
676 content
= decryptMessage(envelope
);
677 if (content
!= null) {
678 if (content
.getDataMessage().isPresent()) {
679 SignalServiceDataMessage message
= content
.getDataMessage().get();
680 group
= handleSignalServiceDataMessage(message
, false, envelope
.getSource(), username
);
682 if (content
.getSyncMessage().isPresent()) {
683 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
684 if (syncMessage
.getSent().isPresent()) {
685 SignalServiceDataMessage message
= syncMessage
.getSent().get().getMessage();
686 group
= handleSignalServiceDataMessage(message
, true, envelope
.getSource(), syncMessage
.getSent().get().getDestination().get());
688 if (syncMessage
.getRequest().isPresent()) {
689 RequestMessage rm
= syncMessage
.getRequest().get();
690 if (rm
.isContactsRequest()) {
691 // TODO implement when we have contacts
693 if (rm
.isGroupsRequest()) {
696 } catch (EncapsulatedExceptions encapsulatedExceptions
) {
697 encapsulatedExceptions
.printStackTrace();
698 } catch (UntrustedIdentityException e
) {
703 if (syncMessage
.getGroups().isPresent()) {
705 DeviceGroupsInputStream s
= new DeviceGroupsInputStream(retrieveAttachmentAsStream(syncMessage
.getGroups().get().asPointer()));
707 while ((g
= s
.read()) != null) {
710 syncGroup
= groupStore
.getGroup(g
.getId());
711 } catch (GroupNotFoundException e
) {
712 syncGroup
= new GroupInfo(g
.getId());
714 if (g
.getName().isPresent()) {
715 syncGroup
.name
= g
.getName().get();
717 syncGroup
.members
.addAll(g
.getMembers());
718 syncGroup
.active
= g
.isActive();
720 if (g
.getAvatar().isPresent()) {
721 byte[] ava
= new byte[(int) g
.getAvatar().get().getLength()];
722 org
.whispersystems
.signalservice
.internal
.util
.Util
.readFully(g
.getAvatar().get().getInputStream(), ava
);
723 // TODO store group avatar in /avatar/groups folder
725 groupStore
.updateGroup(syncGroup
);
727 } catch (Exception e
) {
731 if (syncMessage
.getContacts().isPresent()) {
733 DeviceContactsInputStream s
= new DeviceContactsInputStream(retrieveAttachmentAsStream(syncMessage
.getContacts().get().asPointer()));
735 while ((c
= s
.read()) != null) {
736 // TODO implement when we have contact storage
737 if (c
.getName().isPresent()) {
742 if (c
.getAvatar().isPresent()) {
743 byte[] ava
= new byte[(int) c
.getAvatar().get().getLength()];
744 org
.whispersystems
.signalservice
.internal
.util
.Util
.readFully(c
.getAvatar().get().getInputStream(), ava
);
745 // TODO store contact avatar in /avatar/contacts folder
748 } catch (Exception e
) {
756 handler
.handleMessage(envelope
, content
, group
);
757 } catch (TimeoutException e
) {
760 } catch (InvalidVersionException e
) {
761 System
.err
.println("Ignoring error: " + e
.getMessage());
765 if (messagePipe
!= null)
766 messagePipe
.shutdown();
770 public File
getAttachmentFile(long attachmentId
) {
771 return new File(attachmentsPath
, attachmentId
+ "");
774 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
) throws IOException
, InvalidMessageException
{
775 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(URL
, TRUST_STORE
, username
, password
, deviceId
, signalingKey
, USER_AGENT
);
777 File tmpFile
= File
.createTempFile("ts_attach_" + pointer
.getId(), ".tmp");
778 InputStream input
= messageReceiver
.retrieveAttachment(pointer
, tmpFile
);
780 new File(attachmentsPath
).mkdirs();
781 File outputFile
= getAttachmentFile(pointer
.getId());
782 OutputStream output
= null;
784 output
= new FileOutputStream(outputFile
);
785 byte[] buffer
= new byte[4096];
788 while ((read
= input
.read(buffer
)) != -1) {
789 output
.write(buffer
, 0, read
);
791 } catch (FileNotFoundException e
) {
795 if (output
!= null) {
799 if (!tmpFile
.delete()) {
800 System
.err
.println("Failed to delete temp file: " + tmpFile
);
803 if (pointer
.getPreview().isPresent()) {
804 File previewFile
= new File(outputFile
+ ".preview");
806 output
= new FileOutputStream(previewFile
);
807 byte[] preview
= pointer
.getPreview().get();
808 output
.write(preview
, 0, preview
.length
);
809 } catch (FileNotFoundException e
) {
813 if (output
!= null) {
821 private InputStream
retrieveAttachmentAsStream(SignalServiceAttachmentPointer pointer
) throws IOException
, InvalidMessageException
{
822 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(URL
, TRUST_STORE
, username
, password
, deviceId
, signalingKey
, USER_AGENT
);
823 File file
= File
.createTempFile("ts_tmp", "tmp");
826 return messageReceiver
.retrieveAttachment(pointer
, file
);
829 private String
canonicalizeNumber(String number
) throws InvalidNumberException
{
830 String localNumber
= username
;
831 return PhoneNumberFormatter
.formatNumber(number
, localNumber
);
834 private SignalServiceAddress
getPushAddress(String number
) throws InvalidNumberException
{
835 String e164number
= canonicalizeNumber(number
);
836 return new SignalServiceAddress(e164number
);
840 public boolean isRemote() {
844 private void sendGroups() throws IOException
, EncapsulatedExceptions
, UntrustedIdentityException
{
845 File contactsFile
= File
.createTempFile("multidevice-contact-update", ".tmp");
848 DeviceGroupsOutputStream out
= new DeviceGroupsOutputStream(new FileOutputStream(contactsFile
));
850 for (GroupInfo
record : groupStore
.getGroups()) {
851 out
.write(new DeviceGroup(record.groupId
, Optional
.fromNullable(record.name
),
852 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)),
859 if (contactsFile
.exists() && contactsFile
.length() > 0) {
860 FileInputStream contactsFileStream
= new FileInputStream(contactsFile
);
861 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
862 .withStream(contactsFileStream
)
863 .withContentType("application/octet-stream")
864 .withLength(contactsFile
.length())
867 sendMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
870 if (contactsFile
!= null) contactsFile
.delete();