]> nmode's Git Repositories - signal-cli/blob - src/main/java/org/asamk/signal/manager/Manager.java
Add command sendReaction for emoji reactions
[signal-cli] / src / main / java / org / asamk / signal / manager / Manager.java
1 /*
2 Copyright (C) 2015-2020 AsamK and contributors
3
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.
8
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.
13
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/>.
16 */
17 package org.asamk.signal.manager;
18
19 import org.asamk.Signal;
20 import org.asamk.signal.AttachmentInvalidException;
21 import org.asamk.signal.GroupNotFoundException;
22 import org.asamk.signal.NotAGroupMemberException;
23 import org.asamk.signal.TrustLevel;
24 import org.asamk.signal.UserAlreadyExists;
25 import org.asamk.signal.storage.SignalAccount;
26 import org.asamk.signal.storage.contacts.ContactInfo;
27 import org.asamk.signal.storage.groups.GroupInfo;
28 import org.asamk.signal.storage.groups.JsonGroupStore;
29 import org.asamk.signal.storage.protocol.JsonIdentityKeyStore;
30 import org.asamk.signal.storage.threads.ThreadInfo;
31 import org.asamk.signal.util.IOUtils;
32 import org.asamk.signal.util.Util;
33 import org.signal.libsignal.metadata.InvalidMetadataMessageException;
34 import org.signal.libsignal.metadata.InvalidMetadataVersionException;
35 import org.signal.libsignal.metadata.ProtocolDuplicateMessageException;
36 import org.signal.libsignal.metadata.ProtocolInvalidKeyException;
37 import org.signal.libsignal.metadata.ProtocolInvalidKeyIdException;
38 import org.signal.libsignal.metadata.ProtocolInvalidMessageException;
39 import org.signal.libsignal.metadata.ProtocolInvalidVersionException;
40 import org.signal.libsignal.metadata.ProtocolLegacyMessageException;
41 import org.signal.libsignal.metadata.ProtocolNoSessionException;
42 import org.signal.libsignal.metadata.ProtocolUntrustedIdentityException;
43 import org.signal.libsignal.metadata.SelfSendException;
44 import org.whispersystems.libsignal.IdentityKey;
45 import org.whispersystems.libsignal.IdentityKeyPair;
46 import org.whispersystems.libsignal.InvalidKeyException;
47 import org.whispersystems.libsignal.InvalidMessageException;
48 import org.whispersystems.libsignal.InvalidVersionException;
49 import org.whispersystems.libsignal.ecc.Curve;
50 import org.whispersystems.libsignal.ecc.ECKeyPair;
51 import org.whispersystems.libsignal.ecc.ECPublicKey;
52 import org.whispersystems.libsignal.state.PreKeyRecord;
53 import org.whispersystems.libsignal.state.SignedPreKeyRecord;
54 import org.whispersystems.libsignal.util.KeyHelper;
55 import org.whispersystems.libsignal.util.Medium;
56 import org.whispersystems.libsignal.util.Pair;
57 import org.whispersystems.libsignal.util.guava.Optional;
58 import org.whispersystems.signalservice.api.SignalServiceAccountManager;
59 import org.whispersystems.signalservice.api.SignalServiceMessagePipe;
60 import org.whispersystems.signalservice.api.SignalServiceMessageReceiver;
61 import org.whispersystems.signalservice.api.SignalServiceMessageSender;
62 import org.whispersystems.signalservice.api.crypto.SignalServiceCipher;
63 import org.whispersystems.signalservice.api.crypto.UnidentifiedAccess;
64 import org.whispersystems.signalservice.api.crypto.UnidentifiedAccessPair;
65 import org.whispersystems.signalservice.api.crypto.UntrustedIdentityException;
66 import org.whispersystems.signalservice.api.messages.SendMessageResult;
67 import org.whispersystems.signalservice.api.messages.SignalServiceAttachment;
68 import org.whispersystems.signalservice.api.messages.SignalServiceAttachmentPointer;
69 import org.whispersystems.signalservice.api.messages.SignalServiceAttachmentStream;
70 import org.whispersystems.signalservice.api.messages.SignalServiceContent;
71 import org.whispersystems.signalservice.api.messages.SignalServiceDataMessage;
72 import org.whispersystems.signalservice.api.messages.SignalServiceEnvelope;
73 import org.whispersystems.signalservice.api.messages.SignalServiceGroup;
74 import org.whispersystems.signalservice.api.messages.multidevice.BlockedListMessage;
75 import org.whispersystems.signalservice.api.messages.multidevice.ContactsMessage;
76 import org.whispersystems.signalservice.api.messages.multidevice.DeviceContact;
77 import org.whispersystems.signalservice.api.messages.multidevice.DeviceContactsInputStream;
78 import org.whispersystems.signalservice.api.messages.multidevice.DeviceContactsOutputStream;
79 import org.whispersystems.signalservice.api.messages.multidevice.DeviceGroup;
80 import org.whispersystems.signalservice.api.messages.multidevice.DeviceGroupsInputStream;
81 import org.whispersystems.signalservice.api.messages.multidevice.DeviceGroupsOutputStream;
82 import org.whispersystems.signalservice.api.messages.multidevice.DeviceInfo;
83 import org.whispersystems.signalservice.api.messages.multidevice.RequestMessage;
84 import org.whispersystems.signalservice.api.messages.multidevice.SentTranscriptMessage;
85 import org.whispersystems.signalservice.api.messages.multidevice.SignalServiceSyncMessage;
86 import org.whispersystems.signalservice.api.messages.multidevice.VerifiedMessage;
87 import org.whispersystems.signalservice.api.push.ContactTokenDetails;
88 import org.whispersystems.signalservice.api.push.SignalServiceAddress;
89 import org.whispersystems.signalservice.api.push.exceptions.AuthorizationFailedException;
90 import org.whispersystems.signalservice.api.push.exceptions.EncapsulatedExceptions;
91 import org.whispersystems.signalservice.api.push.exceptions.NetworkFailureException;
92 import org.whispersystems.signalservice.api.push.exceptions.UnregisteredUserException;
93 import org.whispersystems.signalservice.api.util.InvalidNumberException;
94 import org.whispersystems.signalservice.api.util.SleepTimer;
95 import org.whispersystems.signalservice.api.util.StreamDetails;
96 import org.whispersystems.signalservice.api.util.UptimeSleepTimer;
97 import org.whispersystems.signalservice.internal.push.SignalServiceProtos;
98 import org.whispersystems.signalservice.internal.push.UnsupportedDataMessageException;
99 import org.whispersystems.util.Base64;
100
101 import java.io.File;
102 import java.io.FileInputStream;
103 import java.io.FileNotFoundException;
104 import java.io.FileOutputStream;
105 import java.io.IOException;
106 import java.io.InputStream;
107 import java.io.OutputStream;
108 import java.net.URI;
109 import java.nio.file.Files;
110 import java.nio.file.Paths;
111 import java.nio.file.StandardCopyOption;
112 import java.util.ArrayList;
113 import java.util.Arrays;
114 import java.util.Collection;
115 import java.util.Collections;
116 import java.util.Date;
117 import java.util.HashSet;
118 import java.util.LinkedList;
119 import java.util.List;
120 import java.util.Locale;
121 import java.util.Map;
122 import java.util.Objects;
123 import java.util.Set;
124 import java.util.concurrent.TimeUnit;
125 import java.util.concurrent.TimeoutException;
126
127 public class Manager implements Signal {
128
129 private final String settingsPath;
130 private final String dataPath;
131 private final String attachmentsPath;
132 private final String avatarsPath;
133 private final SleepTimer timer = new UptimeSleepTimer();
134
135 private SignalAccount account;
136 private String username;
137 private SignalServiceAccountManager accountManager;
138 private SignalServiceMessagePipe messagePipe = null;
139 private SignalServiceMessagePipe unidentifiedMessagePipe = null;
140
141 public Manager(String username, String settingsPath) {
142 this.username = username;
143 this.settingsPath = settingsPath;
144 this.dataPath = this.settingsPath + "/data";
145 this.attachmentsPath = this.settingsPath + "/attachments";
146 this.avatarsPath = this.settingsPath + "/avatars";
147
148 }
149
150 public String getUsername() {
151 return username;
152 }
153
154 private SignalServiceAddress getSelfAddress() {
155 return new SignalServiceAddress(null, username);
156 }
157
158 private SignalServiceAccountManager getSignalServiceAccountManager() {
159 return new SignalServiceAccountManager(BaseConfig.serviceConfiguration, null, account.getUsername(), account.getPassword(), account.getDeviceId(), BaseConfig.USER_AGENT, timer);
160 }
161
162 private IdentityKey getIdentity() {
163 return account.getSignalProtocolStore().getIdentityKeyPair().getPublicKey();
164 }
165
166 public int getDeviceId() {
167 return account.getDeviceId();
168 }
169
170 private String getMessageCachePath() {
171 return this.dataPath + "/" + username + ".d/msg-cache";
172 }
173
174 private String getMessageCachePath(String sender) {
175 return getMessageCachePath() + "/" + sender.replace("/", "_");
176 }
177
178 private File getMessageCacheFile(String sender, long now, long timestamp) throws IOException {
179 String cachePath = getMessageCachePath(sender);
180 IOUtils.createPrivateDirectories(cachePath);
181 return new File(cachePath + "/" + now + "_" + timestamp);
182 }
183
184 public boolean userHasKeys() {
185 return account != null && account.getSignalProtocolStore() != null;
186 }
187
188 public void init() throws IOException {
189 if (!SignalAccount.userExists(dataPath, username)) {
190 return;
191 }
192 account = SignalAccount.load(dataPath, username);
193
194 migrateLegacyConfigs();
195
196 accountManager = getSignalServiceAccountManager();
197 try {
198 if (account.isRegistered() && accountManager.getPreKeysCount() < BaseConfig.PREKEY_MINIMUM_COUNT) {
199 refreshPreKeys();
200 account.save();
201 }
202 } catch (AuthorizationFailedException e) {
203 System.err.println("Authorization failed, was the number registered elsewhere?");
204 throw e;
205 }
206 }
207
208 private void migrateLegacyConfigs() {
209 // Copy group avatars that were previously stored in the attachments folder
210 // to the new avatar folder
211 if (JsonGroupStore.groupsWithLegacyAvatarId.size() > 0) {
212 for (GroupInfo g : JsonGroupStore.groupsWithLegacyAvatarId) {
213 File avatarFile = getGroupAvatarFile(g.groupId);
214 File attachmentFile = getAttachmentFile(g.getAvatarId());
215 if (!avatarFile.exists() && attachmentFile.exists()) {
216 try {
217 IOUtils.createPrivateDirectories(avatarsPath);
218 Files.copy(attachmentFile.toPath(), avatarFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
219 } catch (Exception e) {
220 // Ignore
221 }
222 }
223 }
224 JsonGroupStore.groupsWithLegacyAvatarId.clear();
225 account.save();
226 }
227 if (account.getProfileKey() == null) {
228 // Old config file, creating new profile key
229 account.setProfileKey(KeyUtils.createProfileKey());
230 account.save();
231 }
232 }
233
234 private void createNewIdentity() throws IOException {
235 IdentityKeyPair identityKey = KeyHelper.generateIdentityKeyPair();
236 int registrationId = KeyHelper.generateRegistrationId(false);
237 if (username == null) {
238 account = SignalAccount.createTemporaryAccount(identityKey, registrationId);
239 } else {
240 byte[] profileKey = KeyUtils.createProfileKey();
241 account = SignalAccount.create(dataPath, username, identityKey, registrationId, profileKey);
242 account.save();
243 }
244 }
245
246 public boolean isRegistered() {
247 return account != null && account.isRegistered();
248 }
249
250 public void register(boolean voiceVerification) throws IOException {
251 if (account == null) {
252 createNewIdentity();
253 }
254 account.setPassword(KeyUtils.createPassword());
255 accountManager = getSignalServiceAccountManager();
256
257 if (voiceVerification) {
258 accountManager.requestVoiceVerificationCode(Locale.getDefault(), Optional.<String>absent(), Optional.<String>absent());
259 } else {
260 accountManager.requestSmsVerificationCode(false, Optional.<String>absent(), Optional.<String>absent());
261 }
262
263 account.setRegistered(false);
264 account.save();
265 }
266
267 public void updateAccountAttributes() throws IOException {
268 accountManager.setAccountAttributes(account.getSignalingKey(), account.getSignalProtocolStore().getLocalRegistrationId(), true, account.getRegistrationLockPin(), account.getRegistrationLock(), getSelfUnidentifiedAccessKey(), false);
269 }
270
271 public void setProfileName(String name) throws IOException {
272 accountManager.setProfileName(account.getProfileKey(), name);
273 }
274
275 public void setProfileAvatar(File avatar) throws IOException {
276 final StreamDetails streamDetails = Utils.createStreamDetailsFromFile(avatar);
277 accountManager.setProfileAvatar(account.getProfileKey(), streamDetails);
278 streamDetails.getStream().close();
279 }
280
281 public void removeProfileAvatar() throws IOException {
282 accountManager.setProfileAvatar(account.getProfileKey(), null);
283 }
284
285 public void unregister() throws IOException {
286 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
287 // If this is the master device, other users can't send messages to this number anymore.
288 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
289 accountManager.setGcmId(Optional.<String>absent());
290
291 account.setRegistered(false);
292 account.save();
293 }
294
295 public String getDeviceLinkUri() throws TimeoutException, IOException {
296 if (account == null) {
297 createNewIdentity();
298 }
299 account.setPassword(KeyUtils.createPassword());
300 accountManager = getSignalServiceAccountManager();
301 String uuid = accountManager.getNewDeviceUuid();
302
303 return Utils.createDeviceLinkUri(new Utils.DeviceLinkInfo(uuid, getIdentity().getPublicKey()));
304 }
305
306 public void finishDeviceLink(String deviceName) throws IOException, InvalidKeyException, TimeoutException, UserAlreadyExists {
307 account.setSignalingKey(KeyUtils.createSignalingKey());
308 SignalServiceAccountManager.NewDeviceRegistrationReturn ret = accountManager.finishNewDeviceRegistration(account.getSignalProtocolStore().getIdentityKeyPair(), account.getSignalingKey(), false, true, account.getSignalProtocolStore().getLocalRegistrationId(), deviceName);
309
310 username = ret.getNumber();
311 // TODO do this check before actually registering
312 if (SignalAccount.userExists(dataPath, username)) {
313 throw new UserAlreadyExists(username, SignalAccount.getFileName(dataPath, username));
314 }
315
316 // Create new account with the synced identity
317 byte[] profileKey = ret.getProfileKey();
318 if (profileKey == null) {
319 profileKey = KeyUtils.createProfileKey();
320 }
321 account = SignalAccount.createLinkedAccount(dataPath, username, account.getPassword(), ret.getDeviceId(), ret.getIdentity(), account.getSignalProtocolStore().getLocalRegistrationId(), account.getSignalingKey(), profileKey);
322
323 refreshPreKeys();
324
325 requestSyncGroups();
326 requestSyncContacts();
327 requestSyncBlocked();
328 requestSyncConfiguration();
329
330 account.save();
331 }
332
333 public List<DeviceInfo> getLinkedDevices() throws IOException {
334 List<DeviceInfo> devices = accountManager.getDevices();
335 account.setMultiDevice(devices.size() > 1);
336 account.save();
337 return devices;
338 }
339
340 public void removeLinkedDevices(int deviceId) throws IOException {
341 accountManager.removeDevice(deviceId);
342 List<DeviceInfo> devices = accountManager.getDevices();
343 account.setMultiDevice(devices.size() > 1);
344 account.save();
345 }
346
347 public void addDeviceLink(URI linkUri) throws IOException, InvalidKeyException {
348 Utils.DeviceLinkInfo info = Utils.parseDeviceLinkUri(linkUri);
349
350 addDevice(info.deviceIdentifier, info.deviceKey);
351 }
352
353 private void addDevice(String deviceIdentifier, ECPublicKey deviceKey) throws IOException, InvalidKeyException {
354 IdentityKeyPair identityKeyPair = account.getSignalProtocolStore().getIdentityKeyPair();
355 String verificationCode = accountManager.getNewDeviceVerificationCode();
356
357 accountManager.addDevice(deviceIdentifier, deviceKey, identityKeyPair, Optional.of(account.getProfileKey()), verificationCode);
358 account.setMultiDevice(true);
359 account.save();
360 }
361
362 private List<PreKeyRecord> generatePreKeys() {
363 List<PreKeyRecord> records = new ArrayList<>(BaseConfig.PREKEY_BATCH_SIZE);
364
365 final int offset = account.getPreKeyIdOffset();
366 for (int i = 0; i < BaseConfig.PREKEY_BATCH_SIZE; i++) {
367 int preKeyId = (offset + i) % Medium.MAX_VALUE;
368 ECKeyPair keyPair = Curve.generateKeyPair();
369 PreKeyRecord record = new PreKeyRecord(preKeyId, keyPair);
370
371 records.add(record);
372 }
373
374 account.addPreKeys(records);
375 account.save();
376
377 return records;
378 }
379
380 private SignedPreKeyRecord generateSignedPreKey(IdentityKeyPair identityKeyPair) {
381 try {
382 ECKeyPair keyPair = Curve.generateKeyPair();
383 byte[] signature = Curve.calculateSignature(identityKeyPair.getPrivateKey(), keyPair.getPublicKey().serialize());
384 SignedPreKeyRecord record = new SignedPreKeyRecord(account.getNextSignedPreKeyId(), System.currentTimeMillis(), keyPair, signature);
385
386 account.addSignedPreKey(record);
387 account.save();
388
389 return record;
390 } catch (InvalidKeyException e) {
391 throw new AssertionError(e);
392 }
393 }
394
395 public void verifyAccount(String verificationCode, String pin) throws IOException {
396 verificationCode = verificationCode.replace("-", "");
397 account.setSignalingKey(KeyUtils.createSignalingKey());
398 // TODO make unrestricted unidentified access configurable
399 accountManager.verifyAccountWithCode(verificationCode, account.getSignalingKey(), account.getSignalProtocolStore().getLocalRegistrationId(), true, pin, null, getSelfUnidentifiedAccessKey(), false);
400
401 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
402 account.setRegistered(true);
403 account.setRegistrationLockPin(pin);
404
405 refreshPreKeys();
406 account.save();
407 }
408
409 public void setRegistrationLockPin(Optional<String> pin) throws IOException {
410 if (pin.isPresent()) {
411 account.setRegistrationLockPin(pin.get());
412 throw new RuntimeException("Not implemented anymore, will be replaced with KBS");
413 } else {
414 account.setRegistrationLockPin(null);
415 accountManager.removeV1Pin();
416 }
417 account.save();
418 }
419
420 private void refreshPreKeys() throws IOException {
421 List<PreKeyRecord> oneTimePreKeys = generatePreKeys();
422 final IdentityKeyPair identityKeyPair = account.getSignalProtocolStore().getIdentityKeyPair();
423 SignedPreKeyRecord signedPreKeyRecord = generateSignedPreKey(identityKeyPair);
424
425 accountManager.setPreKeys(getIdentity(), signedPreKeyRecord, oneTimePreKeys);
426 }
427
428 private SignalServiceMessageReceiver getMessageReceiver() {
429 return new SignalServiceMessageReceiver(BaseConfig.serviceConfiguration, null, username, account.getPassword(), account.getDeviceId(), account.getSignalingKey(), BaseConfig.USER_AGENT, null, timer);
430 }
431
432 private SignalServiceMessageSender getMessageSender() {
433 return new SignalServiceMessageSender(BaseConfig.serviceConfiguration, null, username, account.getPassword(),
434 account.getDeviceId(), account.getSignalProtocolStore(), BaseConfig.USER_AGENT, account.isMultiDevice(), Optional.fromNullable(messagePipe), Optional.fromNullable(unidentifiedMessagePipe), Optional.<SignalServiceMessageSender.EventListener>absent());
435 }
436
437 private Optional<SignalServiceAttachmentStream> createGroupAvatarAttachment(byte[] groupId) throws IOException {
438 File file = getGroupAvatarFile(groupId);
439 if (!file.exists()) {
440 return Optional.absent();
441 }
442
443 return Optional.of(Utils.createAttachment(file));
444 }
445
446 private Optional<SignalServiceAttachmentStream> createContactAvatarAttachment(String number) throws IOException {
447 File file = getContactAvatarFile(number);
448 if (!file.exists()) {
449 return Optional.absent();
450 }
451
452 return Optional.of(Utils.createAttachment(file));
453 }
454
455 private GroupInfo getGroupForSending(byte[] groupId) throws GroupNotFoundException, NotAGroupMemberException {
456 GroupInfo g = account.getGroupStore().getGroup(groupId);
457 if (g == null) {
458 throw new GroupNotFoundException(groupId);
459 }
460 for (String member : g.members) {
461 if (member.equals(this.username)) {
462 return g;
463 }
464 }
465 throw new NotAGroupMemberException(groupId, g.name);
466 }
467
468 public List<GroupInfo> getGroups() {
469 return account.getGroupStore().getGroups();
470 }
471
472 @Override
473 public void sendGroupMessage(String messageText, List<String> attachments,
474 byte[] groupId)
475 throws IOException, EncapsulatedExceptions, GroupNotFoundException, AttachmentInvalidException {
476 final SignalServiceDataMessage.Builder messageBuilder = SignalServiceDataMessage.newBuilder().withBody(messageText);
477 if (attachments != null) {
478 messageBuilder.withAttachments(Utils.getSignalServiceAttachments(attachments));
479 }
480 if (groupId != null) {
481 SignalServiceGroup group = SignalServiceGroup.newBuilder(SignalServiceGroup.Type.DELIVER)
482 .withId(groupId)
483 .build();
484 messageBuilder.asGroupMessage(group);
485 }
486 ThreadInfo thread = account.getThreadStore().getThread(Base64.encodeBytes(groupId));
487 if (thread != null) {
488 messageBuilder.withExpiration(thread.messageExpirationTime);
489 }
490
491 final GroupInfo g = getGroupForSending(groupId);
492
493 // Don't send group message to ourself
494 final List<String> membersSend = new ArrayList<>(g.members);
495 membersSend.remove(this.username);
496 sendMessageLegacy(messageBuilder, membersSend);
497 }
498
499 public void sendGroupMessageReaction(String emoji, boolean remove, SignalServiceAddress targetAuthor,
500 long targetSentTimestamp, byte[] groupId)
501 throws IOException, EncapsulatedExceptions, AttachmentInvalidException {
502 SignalServiceDataMessage.Reaction reaction = new SignalServiceDataMessage.Reaction(emoji, remove, targetAuthor, targetSentTimestamp);
503 final SignalServiceDataMessage.Builder messageBuilder = SignalServiceDataMessage.newBuilder()
504 .withReaction(reaction)
505 .withProfileKey(account.getProfileKey());
506 if (groupId != null) {
507 SignalServiceGroup group = SignalServiceGroup.newBuilder(SignalServiceGroup.Type.DELIVER)
508 .withId(groupId)
509 .build();
510 messageBuilder.asGroupMessage(group);
511 }
512 final GroupInfo g = getGroupForSending(groupId);
513 // Don't send group message to ourself
514 final List<String> membersSend = new ArrayList<>(g.members);
515 membersSend.remove(this.username);
516 sendMessageLegacy(messageBuilder, membersSend);
517 }
518
519 public void sendQuitGroupMessage(byte[] groupId) throws GroupNotFoundException, IOException, EncapsulatedExceptions {
520 SignalServiceGroup group = SignalServiceGroup.newBuilder(SignalServiceGroup.Type.QUIT)
521 .withId(groupId)
522 .build();
523
524 SignalServiceDataMessage.Builder messageBuilder = SignalServiceDataMessage.newBuilder()
525 .asGroupMessage(group);
526
527 final GroupInfo g = getGroupForSending(groupId);
528 g.members.remove(this.username);
529 account.getGroupStore().updateGroup(g);
530
531 sendMessageLegacy(messageBuilder, g.members);
532 }
533
534 private byte[] sendUpdateGroupMessage(byte[] groupId, String name, Collection<String> members, String avatarFile) throws IOException, EncapsulatedExceptions, GroupNotFoundException, AttachmentInvalidException {
535 GroupInfo g;
536 if (groupId == null) {
537 // Create new group
538 g = new GroupInfo(KeyUtils.createGroupId());
539 g.members.add(username);
540 } else {
541 g = getGroupForSending(groupId);
542 }
543
544 if (name != null) {
545 g.name = name;
546 }
547
548 if (members != null) {
549 Set<String> newMembers = new HashSet<>();
550 for (String member : members) {
551 try {
552 member = Utils.canonicalizeNumber(member, username);
553 } catch (InvalidNumberException e) {
554 System.err.println("Failed to add member \"" + member + "\" to group: " + e.getMessage());
555 System.err.println("Aborting…");
556 System.exit(1);
557 }
558 if (g.members.contains(member)) {
559 continue;
560 }
561 newMembers.add(member);
562 g.members.add(member);
563 }
564 final List<ContactTokenDetails> contacts = accountManager.getContacts(newMembers);
565 if (contacts.size() != newMembers.size()) {
566 // Some of the new members are not registered on Signal
567 for (ContactTokenDetails contact : contacts) {
568 newMembers.remove(contact.getNumber());
569 }
570 System.err.println("Failed to add members " + Util.join(", ", newMembers) + " to group: Not registered on Signal");
571 System.err.println("Aborting…");
572 System.exit(1);
573 }
574 }
575
576 if (avatarFile != null) {
577 IOUtils.createPrivateDirectories(avatarsPath);
578 File aFile = getGroupAvatarFile(g.groupId);
579 Files.copy(Paths.get(avatarFile), aFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
580 }
581
582 account.getGroupStore().updateGroup(g);
583
584 SignalServiceDataMessage.Builder messageBuilder = getGroupUpdateMessageBuilder(g);
585
586 // Don't send group message to ourself
587 final List<String> membersSend = new ArrayList<>(g.members);
588 membersSend.remove(this.username);
589 sendMessageLegacy(messageBuilder, membersSend);
590 return g.groupId;
591 }
592
593 private void sendUpdateGroupMessage(byte[] groupId, String recipient) throws IOException, EncapsulatedExceptions {
594 if (groupId == null) {
595 return;
596 }
597 GroupInfo g = getGroupForSending(groupId);
598
599 if (!g.members.contains(recipient)) {
600 return;
601 }
602
603 SignalServiceDataMessage.Builder messageBuilder = getGroupUpdateMessageBuilder(g);
604
605 // Send group message only to the recipient who requested it
606 final List<String> membersSend = new ArrayList<>();
607 membersSend.add(recipient);
608 sendMessageLegacy(messageBuilder, membersSend);
609 }
610
611 private SignalServiceDataMessage.Builder getGroupUpdateMessageBuilder(GroupInfo g) {
612 SignalServiceGroup.Builder group = SignalServiceGroup.newBuilder(SignalServiceGroup.Type.UPDATE)
613 .withId(g.groupId)
614 .withName(g.name)
615 .withMembers(new ArrayList<>(g.getMembers()));
616
617 File aFile = getGroupAvatarFile(g.groupId);
618 if (aFile.exists()) {
619 try {
620 group.withAvatar(Utils.createAttachment(aFile));
621 } catch (IOException e) {
622 throw new AttachmentInvalidException(aFile.toString(), e);
623 }
624 }
625
626 SignalServiceDataMessage.Builder messageBuilder = SignalServiceDataMessage.newBuilder()
627 .asGroupMessage(group.build());
628
629 ThreadInfo thread = account.getThreadStore().getThread(Base64.encodeBytes(g.groupId));
630 if (thread != null) {
631 messageBuilder.withExpiration(thread.messageExpirationTime);
632 }
633
634 return messageBuilder;
635 }
636
637 private void sendGroupInfoRequest(byte[] groupId, String recipient) throws IOException, EncapsulatedExceptions {
638 if (groupId == null) {
639 return;
640 }
641
642 SignalServiceGroup.Builder group = SignalServiceGroup.newBuilder(SignalServiceGroup.Type.REQUEST_INFO)
643 .withId(groupId);
644
645 SignalServiceDataMessage.Builder messageBuilder = SignalServiceDataMessage.newBuilder()
646 .asGroupMessage(group.build());
647
648 ThreadInfo thread = account.getThreadStore().getThread(Base64.encodeBytes(groupId));
649 if (thread != null) {
650 messageBuilder.withExpiration(thread.messageExpirationTime);
651 }
652
653 // Send group info request message to the recipient who sent us a message with this groupId
654 final List<String> membersSend = new ArrayList<>();
655 membersSend.add(recipient);
656 sendMessageLegacy(messageBuilder, membersSend);
657 }
658
659 @Override
660 public void sendMessage(String message, List<String> attachments, String recipient)
661 throws EncapsulatedExceptions, AttachmentInvalidException, IOException {
662 List<String> recipients = new ArrayList<>(1);
663 recipients.add(recipient);
664 sendMessage(message, attachments, recipients);
665 }
666
667 @Override
668 public void sendMessage(String messageText, List<String> attachments,
669 List<String> recipients)
670 throws IOException, EncapsulatedExceptions, AttachmentInvalidException {
671 final SignalServiceDataMessage.Builder messageBuilder = SignalServiceDataMessage.newBuilder().withBody(messageText);
672 if (attachments != null) {
673 List<SignalServiceAttachment> attachmentStreams = Utils.getSignalServiceAttachments(attachments);
674
675 // Upload attachments here, so we only upload once even for multiple recipients
676 SignalServiceMessageSender messageSender = getMessageSender();
677 List<SignalServiceAttachment> attachmentPointers = new ArrayList<>(attachmentStreams.size());
678 for (SignalServiceAttachment attachment : attachmentStreams) {
679 if (attachment.isStream()) {
680 attachmentPointers.add(messageSender.uploadAttachment(attachment.asStream()));
681 } else if (attachment.isPointer()) {
682 attachmentPointers.add(attachment.asPointer());
683 }
684 }
685
686 messageBuilder.withAttachments(attachmentPointers);
687 }
688 messageBuilder.withProfileKey(account.getProfileKey());
689 sendMessageLegacy(messageBuilder, recipients);
690 }
691
692 public void sendMessageReaction(String emoji, boolean remove, SignalServiceAddress targetAuthor,
693 long targetSentTimestamp, List<String> recipients)
694 throws IOException, EncapsulatedExceptions, AttachmentInvalidException {
695 SignalServiceDataMessage.Reaction reaction = new SignalServiceDataMessage.Reaction(emoji, remove, targetAuthor, targetSentTimestamp);
696 final SignalServiceDataMessage.Builder messageBuilder = SignalServiceDataMessage.newBuilder()
697 .withReaction(reaction)
698 .withProfileKey(account.getProfileKey());
699 sendMessageLegacy(messageBuilder, recipients);
700 }
701
702 @Override
703 public void sendEndSessionMessage(List<String> recipients) throws IOException, EncapsulatedExceptions {
704 SignalServiceDataMessage.Builder messageBuilder = SignalServiceDataMessage.newBuilder()
705 .asEndSessionMessage();
706
707 sendMessageLegacy(messageBuilder, recipients);
708 }
709
710 @Override
711 public String getContactName(String number) throws InvalidNumberException {
712 String canonicalizedNumber = Utils.canonicalizeNumber(number, username);
713 ContactInfo contact = account.getContactStore().getContact(canonicalizedNumber);
714 if (contact == null) {
715 return "";
716 } else {
717 return contact.name;
718 }
719 }
720
721 @Override
722 public void setContactName(String number, String name) throws InvalidNumberException {
723 String canonicalizedNumber = Utils.canonicalizeNumber(number, username);
724 ContactInfo contact = account.getContactStore().getContact(canonicalizedNumber);
725 if (contact == null) {
726 contact = new ContactInfo();
727 contact.number = canonicalizedNumber;
728 System.err.println("Add contact " + canonicalizedNumber + " named " + name);
729 } else {
730 System.err.println("Updating contact " + canonicalizedNumber + " name " + contact.name + " -> " + name);
731 }
732 contact.name = name;
733 account.getContactStore().updateContact(contact);
734 account.save();
735 }
736
737 @Override
738 public void setContactBlocked(String number, boolean blocked) throws InvalidNumberException {
739 number = Utils.canonicalizeNumber(number, username);
740 ContactInfo contact = account.getContactStore().getContact(number);
741 if (contact == null) {
742 contact = new ContactInfo();
743 contact.number = number;
744 System.err.println("Adding and " + (blocked ? "blocking" : "unblocking") + " contact " + number);
745 } else {
746 System.err.println((blocked ? "Blocking" : "Unblocking") + " contact " + number);
747 }
748 contact.blocked = blocked;
749 account.getContactStore().updateContact(contact);
750 account.save();
751 }
752
753 @Override
754 public void setGroupBlocked(final byte[] groupId, final boolean blocked) throws GroupNotFoundException {
755 GroupInfo group = getGroup(groupId);
756 if (group == null) {
757 throw new GroupNotFoundException(groupId);
758 } else {
759 System.err.println((blocked ? "Blocking" : "Unblocking") + " group " + Base64.encodeBytes(groupId));
760 group.blocked = blocked;
761 account.getGroupStore().updateGroup(group);
762 account.save();
763 }
764 }
765
766 @Override
767 public List<byte[]> getGroupIds() {
768 List<GroupInfo> groups = getGroups();
769 List<byte[]> ids = new ArrayList<>(groups.size());
770 for (GroupInfo group : groups) {
771 ids.add(group.groupId);
772 }
773 return ids;
774 }
775
776 @Override
777 public String getGroupName(byte[] groupId) {
778 GroupInfo group = getGroup(groupId);
779 if (group == null) {
780 return "";
781 } else {
782 return group.name;
783 }
784 }
785
786 @Override
787 public List<String> getGroupMembers(byte[] groupId) {
788 GroupInfo group = getGroup(groupId);
789 if (group == null) {
790 return new ArrayList<>();
791 } else {
792 return new ArrayList<>(group.members);
793 }
794 }
795
796 @Override
797 public byte[] updateGroup(byte[] groupId, String name, List<String> members, String avatar) throws IOException, EncapsulatedExceptions, GroupNotFoundException, AttachmentInvalidException {
798 if (groupId.length == 0) {
799 groupId = null;
800 }
801 if (name.isEmpty()) {
802 name = null;
803 }
804 if (members.size() == 0) {
805 members = null;
806 }
807 if (avatar.isEmpty()) {
808 avatar = null;
809 }
810 return sendUpdateGroupMessage(groupId, name, members, avatar);
811 }
812
813 /**
814 * Change the expiration timer for a thread (number of groupId)
815 *
816 * @param numberOrGroupId
817 * @param messageExpirationTimer
818 */
819 public void setExpirationTimer(String numberOrGroupId, int messageExpirationTimer) {
820 ThreadInfo thread = account.getThreadStore().getThread(numberOrGroupId);
821 thread.messageExpirationTime = messageExpirationTimer;
822 account.getThreadStore().updateThread(thread);
823 }
824
825 private void requestSyncGroups() throws IOException {
826 SignalServiceProtos.SyncMessage.Request r = SignalServiceProtos.SyncMessage.Request.newBuilder().setType(SignalServiceProtos.SyncMessage.Request.Type.GROUPS).build();
827 SignalServiceSyncMessage message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
828 try {
829 sendSyncMessage(message);
830 } catch (UntrustedIdentityException e) {
831 e.printStackTrace();
832 }
833 }
834
835 private void requestSyncContacts() throws IOException {
836 SignalServiceProtos.SyncMessage.Request r = SignalServiceProtos.SyncMessage.Request.newBuilder().setType(SignalServiceProtos.SyncMessage.Request.Type.CONTACTS).build();
837 SignalServiceSyncMessage message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
838 try {
839 sendSyncMessage(message);
840 } catch (UntrustedIdentityException e) {
841 e.printStackTrace();
842 }
843 }
844
845 private void requestSyncBlocked() throws IOException {
846 SignalServiceProtos.SyncMessage.Request r = SignalServiceProtos.SyncMessage.Request.newBuilder().setType(SignalServiceProtos.SyncMessage.Request.Type.BLOCKED).build();
847 SignalServiceSyncMessage message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
848 try {
849 sendSyncMessage(message);
850 } catch (UntrustedIdentityException e) {
851 e.printStackTrace();
852 }
853 }
854
855 private void requestSyncConfiguration() throws IOException {
856 SignalServiceProtos.SyncMessage.Request r = SignalServiceProtos.SyncMessage.Request.newBuilder().setType(SignalServiceProtos.SyncMessage.Request.Type.CONFIGURATION).build();
857 SignalServiceSyncMessage message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
858 try {
859 sendSyncMessage(message);
860 } catch (UntrustedIdentityException e) {
861 e.printStackTrace();
862 }
863 }
864
865 private byte[] getSelfUnidentifiedAccessKey() {
866 return UnidentifiedAccess.deriveAccessKeyFrom(account.getProfileKey());
867 }
868
869 private byte[] getTargetUnidentifiedAccessKey(SignalServiceAddress recipient) {
870 // TODO implement
871 return null;
872 }
873
874 private Optional<UnidentifiedAccessPair> getAccessForSync() {
875 // TODO implement
876 return Optional.absent();
877 }
878
879 private List<Optional<UnidentifiedAccessPair>> getAccessFor(Collection<SignalServiceAddress> recipients) {
880 List<Optional<UnidentifiedAccessPair>> result = new ArrayList<>(recipients.size());
881 for (SignalServiceAddress recipient : recipients) {
882 result.add(Optional.<UnidentifiedAccessPair>absent());
883 }
884 return result;
885 }
886
887 private Optional<UnidentifiedAccessPair> getAccessFor(SignalServiceAddress recipient) {
888 // TODO implement
889 return Optional.absent();
890 }
891
892 private void sendSyncMessage(SignalServiceSyncMessage message)
893 throws IOException, UntrustedIdentityException {
894 SignalServiceMessageSender messageSender = getMessageSender();
895 try {
896 messageSender.sendMessage(message, getAccessForSync());
897 } catch (UntrustedIdentityException e) {
898 account.getSignalProtocolStore().saveIdentity(e.getIdentifier(), e.getIdentityKey(), TrustLevel.UNTRUSTED);
899 throw e;
900 }
901 }
902
903 /**
904 * This method throws an EncapsulatedExceptions exception instead of returning a list of SendMessageResult.
905 */
906 private void sendMessageLegacy(SignalServiceDataMessage.Builder messageBuilder, Collection<String> recipients)
907 throws EncapsulatedExceptions, IOException {
908 List<SendMessageResult> results = sendMessage(messageBuilder, recipients);
909
910 List<UntrustedIdentityException> untrustedIdentities = new LinkedList<>();
911 List<UnregisteredUserException> unregisteredUsers = new LinkedList<>();
912 List<NetworkFailureException> networkExceptions = new LinkedList<>();
913
914 for (SendMessageResult result : results) {
915 if (result.isUnregisteredFailure()) {
916 unregisteredUsers.add(new UnregisteredUserException(result.getAddress().getNumber().get(), null));
917 } else if (result.isNetworkFailure()) {
918 networkExceptions.add(new NetworkFailureException(result.getAddress().getNumber().get(), null));
919 } else if (result.getIdentityFailure() != null) {
920 untrustedIdentities.add(new UntrustedIdentityException("Untrusted", result.getAddress().getNumber().get(), result.getIdentityFailure().getIdentityKey()));
921 }
922 }
923 if (!untrustedIdentities.isEmpty() || !unregisteredUsers.isEmpty() || !networkExceptions.isEmpty()) {
924 throw new EncapsulatedExceptions(untrustedIdentities, unregisteredUsers, networkExceptions);
925 }
926 }
927
928 private List<SendMessageResult> sendMessage(SignalServiceDataMessage.Builder messageBuilder, Collection<String> recipients)
929 throws IOException {
930 Set<SignalServiceAddress> recipientsTS = Utils.getSignalServiceAddresses(recipients, username);
931 if (recipientsTS == null) {
932 account.save();
933 return Collections.emptyList();
934 }
935
936 SignalServiceDataMessage message = null;
937 try {
938 SignalServiceMessageSender messageSender = getMessageSender();
939
940 message = messageBuilder.build();
941 if (message.getGroupInfo().isPresent()) {
942 try {
943 final boolean isRecipientUpdate = false;
944 List<SendMessageResult> result = messageSender.sendMessage(new ArrayList<>(recipientsTS), getAccessFor(recipientsTS), isRecipientUpdate, message);
945 for (SendMessageResult r : result) {
946 if (r.getIdentityFailure() != null) {
947 account.getSignalProtocolStore().saveIdentity(r.getAddress().getNumber().get(), r.getIdentityFailure().getIdentityKey(), TrustLevel.UNTRUSTED);
948 }
949 }
950 return result;
951 } catch (UntrustedIdentityException e) {
952 account.getSignalProtocolStore().saveIdentity(e.getIdentifier(), e.getIdentityKey(), TrustLevel.UNTRUSTED);
953 return Collections.emptyList();
954 }
955 } else if (recipientsTS.size() == 1 && recipientsTS.contains(getSelfAddress())) {
956 SignalServiceAddress recipient = getSelfAddress();
957 final Optional<UnidentifiedAccessPair> unidentifiedAccess = getAccessFor(recipient);
958 SentTranscriptMessage transcript = new SentTranscriptMessage(Optional.of(recipient),
959 message.getTimestamp(),
960 message,
961 message.getExpiresInSeconds(),
962 Collections.singletonMap(recipient, unidentifiedAccess.isPresent()),
963 false);
964 SignalServiceSyncMessage syncMessage = SignalServiceSyncMessage.forSentTranscript(transcript);
965
966 List<SendMessageResult> results = new ArrayList<>(recipientsTS.size());
967 try {
968 messageSender.sendMessage(syncMessage, unidentifiedAccess);
969 } catch (UntrustedIdentityException e) {
970 account.getSignalProtocolStore().saveIdentity(e.getIdentifier(), e.getIdentityKey(), TrustLevel.UNTRUSTED);
971 results.add(SendMessageResult.identityFailure(recipient, e.getIdentityKey()));
972 }
973 return results;
974 } else {
975 // Send to all individually, so sync messages are sent correctly
976 List<SendMessageResult> results = new ArrayList<>(recipientsTS.size());
977 for (SignalServiceAddress address : recipientsTS) {
978 ThreadInfo thread = account.getThreadStore().getThread(address.getNumber().get());
979 if (thread != null) {
980 messageBuilder.withExpiration(thread.messageExpirationTime);
981 } else {
982 messageBuilder.withExpiration(0);
983 }
984 message = messageBuilder.build();
985 try {
986 SendMessageResult result = messageSender.sendMessage(address, getAccessFor(address), message);
987 results.add(result);
988 } catch (UntrustedIdentityException e) {
989 account.getSignalProtocolStore().saveIdentity(e.getIdentifier(), e.getIdentityKey(), TrustLevel.UNTRUSTED);
990 results.add(SendMessageResult.identityFailure(address, e.getIdentityKey()));
991 }
992 }
993 return results;
994 }
995 } finally {
996 if (message != null && message.isEndSession()) {
997 for (SignalServiceAddress recipient : recipientsTS) {
998 handleEndSession(recipient.getNumber().get());
999 }
1000 }
1001 account.save();
1002 }
1003 }
1004
1005 private SignalServiceContent decryptMessage(SignalServiceEnvelope envelope) throws InvalidMetadataMessageException, ProtocolInvalidMessageException, ProtocolDuplicateMessageException, ProtocolLegacyMessageException, ProtocolInvalidKeyIdException, InvalidMetadataVersionException, ProtocolInvalidVersionException, ProtocolNoSessionException, ProtocolInvalidKeyException, ProtocolUntrustedIdentityException, SelfSendException, UnsupportedDataMessageException {
1006 SignalServiceCipher cipher = new SignalServiceCipher(getSelfAddress(), account.getSignalProtocolStore(), Utils.getCertificateValidator());
1007 try {
1008 return cipher.decrypt(envelope);
1009 } catch (ProtocolUntrustedIdentityException e) {
1010 // TODO We don't get the new untrusted identity from ProtocolUntrustedIdentityException anymore ... we need to get it from somewhere else
1011 // account.getSignalProtocolStore().saveIdentity(e.getSender(), e.getUntrustedIdentity(), TrustLevel.UNTRUSTED);
1012 throw e;
1013 }
1014 }
1015
1016 private void handleEndSession(String source) {
1017 account.getSignalProtocolStore().deleteAllSessions(source);
1018 }
1019
1020 private void handleSignalServiceDataMessage(SignalServiceDataMessage message, boolean isSync, String source, SignalServiceAddress destination, boolean ignoreAttachments) {
1021 String threadId;
1022 if (message.getGroupInfo().isPresent()) {
1023 SignalServiceGroup groupInfo = message.getGroupInfo().get();
1024 threadId = Base64.encodeBytes(groupInfo.getGroupId());
1025 GroupInfo group = account.getGroupStore().getGroup(groupInfo.getGroupId());
1026 switch (groupInfo.getType()) {
1027 case UPDATE:
1028 if (group == null) {
1029 group = new GroupInfo(groupInfo.getGroupId());
1030 }
1031
1032 if (groupInfo.getAvatar().isPresent()) {
1033 SignalServiceAttachment avatar = groupInfo.getAvatar().get();
1034 if (avatar.isPointer()) {
1035 try {
1036 retrieveGroupAvatarAttachment(avatar.asPointer(), group.groupId);
1037 } catch (IOException | InvalidMessageException e) {
1038 System.err.println("Failed to retrieve group avatar (" + avatar.asPointer().getId() + "): " + e.getMessage());
1039 }
1040 }
1041 }
1042
1043 if (groupInfo.getName().isPresent()) {
1044 group.name = groupInfo.getName().get();
1045 }
1046
1047 if (groupInfo.getMembers().isPresent()) {
1048 group.addMembers(groupInfo.getMembers().get());
1049 }
1050
1051 account.getGroupStore().updateGroup(group);
1052 break;
1053 case DELIVER:
1054 if (group == null) {
1055 try {
1056 sendGroupInfoRequest(groupInfo.getGroupId(), source);
1057 } catch (IOException | EncapsulatedExceptions e) {
1058 e.printStackTrace();
1059 }
1060 }
1061 break;
1062 case QUIT:
1063 if (group == null) {
1064 try {
1065 sendGroupInfoRequest(groupInfo.getGroupId(), source);
1066 } catch (IOException | EncapsulatedExceptions e) {
1067 e.printStackTrace();
1068 }
1069 } else {
1070 group.members.remove(source);
1071 account.getGroupStore().updateGroup(group);
1072 }
1073 break;
1074 case REQUEST_INFO:
1075 if (group != null) {
1076 try {
1077 sendUpdateGroupMessage(groupInfo.getGroupId(), source);
1078 } catch (IOException | EncapsulatedExceptions e) {
1079 e.printStackTrace();
1080 } catch (NotAGroupMemberException e) {
1081 // We have left this group, so don't send a group update message
1082 }
1083 }
1084 break;
1085 }
1086 } else {
1087 if (isSync) {
1088 threadId = destination.getNumber().get();
1089 } else {
1090 threadId = source;
1091 }
1092 }
1093 if (message.isEndSession()) {
1094 handleEndSession(isSync ? destination.getNumber().get() : source);
1095 }
1096 if (message.isExpirationUpdate() || message.getBody().isPresent()) {
1097 ThreadInfo thread = account.getThreadStore().getThread(threadId);
1098 if (thread == null) {
1099 thread = new ThreadInfo();
1100 thread.id = threadId;
1101 }
1102 if (thread.messageExpirationTime != message.getExpiresInSeconds()) {
1103 thread.messageExpirationTime = message.getExpiresInSeconds();
1104 account.getThreadStore().updateThread(thread);
1105 }
1106 }
1107 if (message.getAttachments().isPresent() && !ignoreAttachments) {
1108 for (SignalServiceAttachment attachment : message.getAttachments().get()) {
1109 if (attachment.isPointer()) {
1110 try {
1111 retrieveAttachment(attachment.asPointer());
1112 } catch (IOException | InvalidMessageException e) {
1113 System.err.println("Failed to retrieve attachment (" + attachment.asPointer().getId() + "): " + e.getMessage());
1114 }
1115 }
1116 }
1117 }
1118 if (message.getProfileKey().isPresent() && message.getProfileKey().get().length == 32) {
1119 if (source.equals(username)) {
1120 this.account.setProfileKey(message.getProfileKey().get());
1121 }
1122 ContactInfo contact = account.getContactStore().getContact(source);
1123 if (contact == null) {
1124 contact = new ContactInfo();
1125 contact.number = source;
1126 }
1127 contact.profileKey = Base64.encodeBytes(message.getProfileKey().get());
1128 }
1129 if (message.getPreviews().isPresent()) {
1130 final List<SignalServiceDataMessage.Preview> previews = message.getPreviews().get();
1131 for (SignalServiceDataMessage.Preview preview : previews) {
1132 if (preview.getImage().isPresent() && preview.getImage().get().isPointer()) {
1133 SignalServiceAttachmentPointer attachment = preview.getImage().get().asPointer();
1134 try {
1135 retrieveAttachment(attachment);
1136 } catch (IOException | InvalidMessageException e) {
1137 System.err.println("Failed to retrieve attachment (" + attachment.getId() + "): " + e.getMessage());
1138 }
1139 }
1140 }
1141 }
1142 }
1143
1144 private void retryFailedReceivedMessages(ReceiveMessageHandler handler, boolean ignoreAttachments) {
1145 final File cachePath = new File(getMessageCachePath());
1146 if (!cachePath.exists()) {
1147 return;
1148 }
1149 for (final File dir : Objects.requireNonNull(cachePath.listFiles())) {
1150 if (!dir.isDirectory()) {
1151 continue;
1152 }
1153
1154 for (final File fileEntry : Objects.requireNonNull(dir.listFiles())) {
1155 if (!fileEntry.isFile()) {
1156 continue;
1157 }
1158 SignalServiceEnvelope envelope;
1159 try {
1160 envelope = Utils.loadEnvelope(fileEntry);
1161 if (envelope == null) {
1162 continue;
1163 }
1164 } catch (IOException e) {
1165 e.printStackTrace();
1166 continue;
1167 }
1168 SignalServiceContent content = null;
1169 if (!envelope.isReceipt()) {
1170 try {
1171 content = decryptMessage(envelope);
1172 } catch (Exception e) {
1173 continue;
1174 }
1175 handleMessage(envelope, content, ignoreAttachments);
1176 }
1177 account.save();
1178 handler.handleMessage(envelope, content, null);
1179 try {
1180 Files.delete(fileEntry.toPath());
1181 } catch (IOException e) {
1182 System.err.println("Failed to delete cached message file “" + fileEntry + "”: " + e.getMessage());
1183 }
1184 }
1185 // Try to delete directory if empty
1186 dir.delete();
1187 }
1188 }
1189
1190 public void receiveMessages(long timeout, TimeUnit unit, boolean returnOnTimeout, boolean ignoreAttachments, ReceiveMessageHandler handler) throws IOException {
1191 retryFailedReceivedMessages(handler, ignoreAttachments);
1192 final SignalServiceMessageReceiver messageReceiver = getMessageReceiver();
1193
1194 try {
1195 if (messagePipe == null) {
1196 messagePipe = messageReceiver.createMessagePipe();
1197 }
1198
1199 while (true) {
1200 SignalServiceEnvelope envelope;
1201 SignalServiceContent content = null;
1202 Exception exception = null;
1203 final long now = new Date().getTime();
1204 try {
1205 envelope = messagePipe.read(timeout, unit, new SignalServiceMessagePipe.MessagePipeCallback() {
1206 @Override
1207 public void onMessage(SignalServiceEnvelope envelope) {
1208 // store message on disk, before acknowledging receipt to the server
1209 try {
1210 File cacheFile = getMessageCacheFile(envelope.getSourceE164().get(), now, envelope.getTimestamp());
1211 Utils.storeEnvelope(envelope, cacheFile);
1212 } catch (IOException e) {
1213 System.err.println("Failed to store encrypted message in disk cache, ignoring: " + e.getMessage());
1214 }
1215 }
1216 });
1217 } catch (TimeoutException e) {
1218 if (returnOnTimeout)
1219 return;
1220 continue;
1221 } catch (InvalidVersionException e) {
1222 System.err.println("Ignoring error: " + e.getMessage());
1223 continue;
1224 }
1225 if (!envelope.isReceipt()) {
1226 try {
1227 content = decryptMessage(envelope);
1228 } catch (Exception e) {
1229 exception = e;
1230 }
1231 handleMessage(envelope, content, ignoreAttachments);
1232 }
1233 account.save();
1234 if (!isMessageBlocked(envelope, content)) {
1235 handler.handleMessage(envelope, content, exception);
1236 }
1237 if (!(exception instanceof ProtocolUntrustedIdentityException)) {
1238 File cacheFile = null;
1239 try {
1240 cacheFile = getMessageCacheFile(envelope.getSourceE164().get(), now, envelope.getTimestamp());
1241 Files.delete(cacheFile.toPath());
1242 // Try to delete directory if empty
1243 new File(getMessageCachePath()).delete();
1244 } catch (IOException e) {
1245 System.err.println("Failed to delete cached message file “" + cacheFile + "”: " + e.getMessage());
1246 }
1247 }
1248 }
1249 } finally {
1250 if (messagePipe != null) {
1251 messagePipe.shutdown();
1252 messagePipe = null;
1253 }
1254 }
1255 }
1256
1257 private boolean isMessageBlocked(SignalServiceEnvelope envelope, SignalServiceContent content) {
1258 SignalServiceAddress source;
1259 if (!envelope.isUnidentifiedSender() && envelope.hasSource()) {
1260 source = envelope.getSourceAddress();
1261 } else if (content != null) {
1262 source = content.getSender();
1263 } else {
1264 return false;
1265 }
1266 ContactInfo sourceContact = getContact(source.getNumber().get());
1267 if (sourceContact != null && sourceContact.blocked) {
1268 return true;
1269 }
1270
1271 if (content != null && content.getDataMessage().isPresent()) {
1272 SignalServiceDataMessage message = content.getDataMessage().get();
1273 if (message.getGroupInfo().isPresent()) {
1274 SignalServiceGroup groupInfo = message.getGroupInfo().get();
1275 GroupInfo group = getGroup(groupInfo.getGroupId());
1276 if (groupInfo.getType() == SignalServiceGroup.Type.DELIVER && group != null && group.blocked) {
1277 return true;
1278 }
1279 }
1280 }
1281 return false;
1282 }
1283
1284 private void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent content, boolean ignoreAttachments) {
1285 if (content != null) {
1286 SignalServiceAddress sender;
1287 if (!envelope.isUnidentifiedSender() && envelope.hasSource()) {
1288 sender = envelope.getSourceAddress();
1289 } else {
1290 sender = content.getSender();
1291 }
1292 if (content.getDataMessage().isPresent()) {
1293 SignalServiceDataMessage message = content.getDataMessage().get();
1294 handleSignalServiceDataMessage(message, false, sender.getNumber().get(), getSelfAddress(), ignoreAttachments);
1295 }
1296 if (content.getSyncMessage().isPresent()) {
1297 account.setMultiDevice(true);
1298 SignalServiceSyncMessage syncMessage = content.getSyncMessage().get();
1299 if (syncMessage.getSent().isPresent()) {
1300 SentTranscriptMessage message = syncMessage.getSent().get();
1301 handleSignalServiceDataMessage(message.getMessage(), true, sender.getNumber().get(), message.getDestination().orNull(), ignoreAttachments);
1302 }
1303 if (syncMessage.getRequest().isPresent()) {
1304 RequestMessage rm = syncMessage.getRequest().get();
1305 if (rm.isContactsRequest()) {
1306 try {
1307 sendContacts();
1308 } catch (UntrustedIdentityException | IOException e) {
1309 e.printStackTrace();
1310 }
1311 }
1312 if (rm.isGroupsRequest()) {
1313 try {
1314 sendGroups();
1315 } catch (UntrustedIdentityException | IOException e) {
1316 e.printStackTrace();
1317 }
1318 }
1319 if (rm.isBlockedListRequest()) {
1320 try {
1321 sendBlockedList();
1322 } catch (UntrustedIdentityException | IOException e) {
1323 e.printStackTrace();
1324 }
1325 }
1326 // TODO Handle rm.isConfigurationRequest();
1327 }
1328 if (syncMessage.getGroups().isPresent()) {
1329 File tmpFile = null;
1330 try {
1331 tmpFile = IOUtils.createTempFile();
1332 try (InputStream attachmentAsStream = retrieveAttachmentAsStream(syncMessage.getGroups().get().asPointer(), tmpFile)) {
1333 DeviceGroupsInputStream s = new DeviceGroupsInputStream(attachmentAsStream);
1334 DeviceGroup g;
1335 while ((g = s.read()) != null) {
1336 GroupInfo syncGroup = account.getGroupStore().getGroup(g.getId());
1337 if (syncGroup == null) {
1338 syncGroup = new GroupInfo(g.getId());
1339 }
1340 if (g.getName().isPresent()) {
1341 syncGroup.name = g.getName().get();
1342 }
1343 syncGroup.addMembers(g.getMembers());
1344 syncGroup.active = g.isActive();
1345 syncGroup.blocked = g.isBlocked();
1346 if (g.getColor().isPresent()) {
1347 syncGroup.color = g.getColor().get();
1348 }
1349
1350 if (g.getAvatar().isPresent()) {
1351 retrieveGroupAvatarAttachment(g.getAvatar().get(), syncGroup.groupId);
1352 }
1353 syncGroup.inboxPosition = g.getInboxPosition().orNull();
1354 syncGroup.archived = g.isArchived();
1355 account.getGroupStore().updateGroup(syncGroup);
1356 }
1357 }
1358 } catch (Exception e) {
1359 e.printStackTrace();
1360 } finally {
1361 if (tmpFile != null) {
1362 try {
1363 Files.delete(tmpFile.toPath());
1364 } catch (IOException e) {
1365 System.err.println("Failed to delete received groups temp file “" + tmpFile + "”: " + e.getMessage());
1366 }
1367 }
1368 }
1369 }
1370 if (syncMessage.getBlockedList().isPresent()) {
1371 final BlockedListMessage blockedListMessage = syncMessage.getBlockedList().get();
1372 for (SignalServiceAddress address : blockedListMessage.getAddresses()) {
1373 if (address.getNumber().isPresent()) {
1374 try {
1375 setContactBlocked(address.getNumber().get(), true);
1376 } catch (InvalidNumberException e) {
1377 e.printStackTrace();
1378 }
1379 }
1380 }
1381 for (byte[] groupId : blockedListMessage.getGroupIds()) {
1382 try {
1383 setGroupBlocked(groupId, true);
1384 } catch (GroupNotFoundException e) {
1385 System.err.println("BlockedListMessage contained groupID that was not found in GroupStore: " + Base64.encodeBytes(groupId));
1386 }
1387 }
1388 }
1389 if (syncMessage.getContacts().isPresent()) {
1390 File tmpFile = null;
1391 try {
1392 tmpFile = IOUtils.createTempFile();
1393 final ContactsMessage contactsMessage = syncMessage.getContacts().get();
1394 try (InputStream attachmentAsStream = retrieveAttachmentAsStream(contactsMessage.getContactsStream().asPointer(), tmpFile)) {
1395 DeviceContactsInputStream s = new DeviceContactsInputStream(attachmentAsStream);
1396 if (contactsMessage.isComplete()) {
1397 account.getContactStore().clear();
1398 }
1399 DeviceContact c;
1400 while ((c = s.read()) != null) {
1401 if (c.getAddress().matches(account.getSelfAddress()) && c.getProfileKey().isPresent()) {
1402 account.setProfileKey(c.getProfileKey().get());
1403 }
1404 ContactInfo contact = account.getContactStore().getContact(c.getAddress().getNumber().get());
1405 if (contact == null) {
1406 contact = new ContactInfo();
1407 contact.number = c.getAddress().getNumber().get();
1408 }
1409 if (c.getName().isPresent()) {
1410 contact.name = c.getName().get();
1411 }
1412 if (c.getColor().isPresent()) {
1413 contact.color = c.getColor().get();
1414 }
1415 if (c.getProfileKey().isPresent()) {
1416 contact.profileKey = Base64.encodeBytes(c.getProfileKey().get());
1417 }
1418 if (c.getVerified().isPresent()) {
1419 final VerifiedMessage verifiedMessage = c.getVerified().get();
1420 account.getSignalProtocolStore().saveIdentity(verifiedMessage.getDestination().getNumber().get(), verifiedMessage.getIdentityKey(), TrustLevel.fromVerifiedState(verifiedMessage.getVerified()));
1421 }
1422 if (c.getExpirationTimer().isPresent()) {
1423 ThreadInfo thread = account.getThreadStore().getThread(c.getAddress().getNumber().get());
1424 if (thread == null) {
1425 thread = new ThreadInfo();
1426 thread.id = c.getAddress().getNumber().get();
1427 }
1428 thread.messageExpirationTime = c.getExpirationTimer().get();
1429 account.getThreadStore().updateThread(thread);
1430 }
1431 contact.blocked = c.isBlocked();
1432 contact.inboxPosition = c.getInboxPosition().orNull();
1433 contact.archived = c.isArchived();
1434 account.getContactStore().updateContact(contact);
1435
1436 if (c.getAvatar().isPresent()) {
1437 retrieveContactAvatarAttachment(c.getAvatar().get(), contact.number);
1438 }
1439 }
1440 }
1441 } catch (Exception e) {
1442 e.printStackTrace();
1443 } finally {
1444 if (tmpFile != null) {
1445 try {
1446 Files.delete(tmpFile.toPath());
1447 } catch (IOException e) {
1448 System.err.println("Failed to delete received contacts temp file “" + tmpFile + "”: " + e.getMessage());
1449 }
1450 }
1451 }
1452 }
1453 if (syncMessage.getVerified().isPresent()) {
1454 final VerifiedMessage verifiedMessage = syncMessage.getVerified().get();
1455 account.getSignalProtocolStore().saveIdentity(verifiedMessage.getDestination().getNumber().get(), verifiedMessage.getIdentityKey(), TrustLevel.fromVerifiedState(verifiedMessage.getVerified()));
1456 }
1457 if (syncMessage.getConfiguration().isPresent()) {
1458 // TODO
1459 }
1460 }
1461 }
1462 }
1463
1464 private File getContactAvatarFile(String number) {
1465 return new File(avatarsPath, "contact-" + number);
1466 }
1467
1468 private File retrieveContactAvatarAttachment(SignalServiceAttachment attachment, String number) throws IOException, InvalidMessageException {
1469 IOUtils.createPrivateDirectories(avatarsPath);
1470 if (attachment.isPointer()) {
1471 SignalServiceAttachmentPointer pointer = attachment.asPointer();
1472 return retrieveAttachment(pointer, getContactAvatarFile(number), false);
1473 } else {
1474 SignalServiceAttachmentStream stream = attachment.asStream();
1475 return Utils.retrieveAttachment(stream, getContactAvatarFile(number));
1476 }
1477 }
1478
1479 private File getGroupAvatarFile(byte[] groupId) {
1480 return new File(avatarsPath, "group-" + Base64.encodeBytes(groupId).replace("/", "_"));
1481 }
1482
1483 private File retrieveGroupAvatarAttachment(SignalServiceAttachment attachment, byte[] groupId) throws IOException, InvalidMessageException {
1484 IOUtils.createPrivateDirectories(avatarsPath);
1485 if (attachment.isPointer()) {
1486 SignalServiceAttachmentPointer pointer = attachment.asPointer();
1487 return retrieveAttachment(pointer, getGroupAvatarFile(groupId), false);
1488 } else {
1489 SignalServiceAttachmentStream stream = attachment.asStream();
1490 return Utils.retrieveAttachment(stream, getGroupAvatarFile(groupId));
1491 }
1492 }
1493
1494 public File getAttachmentFile(long attachmentId) {
1495 return new File(attachmentsPath, attachmentId + "");
1496 }
1497
1498 private File retrieveAttachment(SignalServiceAttachmentPointer pointer) throws IOException, InvalidMessageException {
1499 IOUtils.createPrivateDirectories(attachmentsPath);
1500 return retrieveAttachment(pointer, getAttachmentFile(pointer.getId()), true);
1501 }
1502
1503 private File retrieveAttachment(SignalServiceAttachmentPointer pointer, File outputFile, boolean storePreview) throws IOException, InvalidMessageException {
1504 if (storePreview && pointer.getPreview().isPresent()) {
1505 File previewFile = new File(outputFile + ".preview");
1506 try (OutputStream output = new FileOutputStream(previewFile)) {
1507 byte[] preview = pointer.getPreview().get();
1508 output.write(preview, 0, preview.length);
1509 } catch (FileNotFoundException e) {
1510 e.printStackTrace();
1511 return null;
1512 }
1513 }
1514
1515 final SignalServiceMessageReceiver messageReceiver = getMessageReceiver();
1516
1517 File tmpFile = IOUtils.createTempFile();
1518 try (InputStream input = messageReceiver.retrieveAttachment(pointer, tmpFile, BaseConfig.MAX_ATTACHMENT_SIZE)) {
1519 try (OutputStream output = new FileOutputStream(outputFile)) {
1520 byte[] buffer = new byte[4096];
1521 int read;
1522
1523 while ((read = input.read(buffer)) != -1) {
1524 output.write(buffer, 0, read);
1525 }
1526 } catch (FileNotFoundException e) {
1527 e.printStackTrace();
1528 return null;
1529 }
1530 } finally {
1531 try {
1532 Files.delete(tmpFile.toPath());
1533 } catch (IOException e) {
1534 System.err.println("Failed to delete received attachment temp file “" + tmpFile + "”: " + e.getMessage());
1535 }
1536 }
1537 return outputFile;
1538 }
1539
1540 private InputStream retrieveAttachmentAsStream(SignalServiceAttachmentPointer pointer, File tmpFile) throws IOException, InvalidMessageException {
1541 final SignalServiceMessageReceiver messageReceiver = getMessageReceiver();
1542 return messageReceiver.retrieveAttachment(pointer, tmpFile, BaseConfig.MAX_ATTACHMENT_SIZE);
1543 }
1544
1545 @Override
1546 public boolean isRemote() {
1547 return false;
1548 }
1549
1550 private void sendGroups() throws IOException, UntrustedIdentityException {
1551 File groupsFile = IOUtils.createTempFile();
1552
1553 try {
1554 try (OutputStream fos = new FileOutputStream(groupsFile)) {
1555 DeviceGroupsOutputStream out = new DeviceGroupsOutputStream(fos);
1556 for (GroupInfo record : account.getGroupStore().getGroups()) {
1557 ThreadInfo info = account.getThreadStore().getThread(Base64.encodeBytes(record.groupId));
1558 out.write(new DeviceGroup(record.groupId, Optional.fromNullable(record.name),
1559 new ArrayList<>(record.getMembers()), createGroupAvatarAttachment(record.groupId),
1560 record.active, Optional.fromNullable(info != null ? info.messageExpirationTime : null),
1561 Optional.fromNullable(record.color), record.blocked, Optional.fromNullable(record.inboxPosition), record.archived));
1562 }
1563 }
1564
1565 if (groupsFile.exists() && groupsFile.length() > 0) {
1566 try (FileInputStream groupsFileStream = new FileInputStream(groupsFile)) {
1567 SignalServiceAttachmentStream attachmentStream = SignalServiceAttachment.newStreamBuilder()
1568 .withStream(groupsFileStream)
1569 .withContentType("application/octet-stream")
1570 .withLength(groupsFile.length())
1571 .build();
1572
1573 sendSyncMessage(SignalServiceSyncMessage.forGroups(attachmentStream));
1574 }
1575 }
1576 } finally {
1577 try {
1578 Files.delete(groupsFile.toPath());
1579 } catch (IOException e) {
1580 System.err.println("Failed to delete groups temp file “" + groupsFile + "”: " + e.getMessage());
1581 }
1582 }
1583 }
1584
1585 public void sendContacts() throws IOException, UntrustedIdentityException {
1586 File contactsFile = IOUtils.createTempFile();
1587
1588 try {
1589 try (OutputStream fos = new FileOutputStream(contactsFile)) {
1590 DeviceContactsOutputStream out = new DeviceContactsOutputStream(fos);
1591 for (ContactInfo record : account.getContactStore().getContacts()) {
1592 VerifiedMessage verifiedMessage = null;
1593 ThreadInfo info = account.getThreadStore().getThread(record.number);
1594 if (getIdentities().containsKey(record.number)) {
1595 JsonIdentityKeyStore.Identity currentIdentity = null;
1596 for (JsonIdentityKeyStore.Identity id : getIdentities().get(record.number)) {
1597 if (currentIdentity == null || id.getDateAdded().after(currentIdentity.getDateAdded())) {
1598 currentIdentity = id;
1599 }
1600 }
1601 if (currentIdentity != null) {
1602 verifiedMessage = new VerifiedMessage(record.getAddress(), currentIdentity.getIdentityKey(), currentIdentity.getTrustLevel().toVerifiedState(), currentIdentity.getDateAdded().getTime());
1603 }
1604 }
1605
1606 byte[] profileKey = record.profileKey == null ? null : Base64.decode(record.profileKey);
1607 out.write(new DeviceContact(record.getAddress(), Optional.fromNullable(record.name),
1608 createContactAvatarAttachment(record.number), Optional.fromNullable(record.color),
1609 Optional.fromNullable(verifiedMessage), Optional.fromNullable(profileKey), record.blocked,
1610 Optional.fromNullable(info != null ? info.messageExpirationTime : null),
1611 Optional.fromNullable(record.inboxPosition), record.archived));
1612 }
1613
1614 if (account.getProfileKey() != null) {
1615 // Send our own profile key as well
1616 out.write(new DeviceContact(account.getSelfAddress(),
1617 Optional.<String>absent(), Optional.<SignalServiceAttachmentStream>absent(),
1618 Optional.<String>absent(), Optional.<VerifiedMessage>absent(),
1619 Optional.of(account.getProfileKey()),
1620 false, Optional.<Integer>absent(), Optional.<Integer>absent(), false));
1621 }
1622 }
1623
1624 if (contactsFile.exists() && contactsFile.length() > 0) {
1625 try (FileInputStream contactsFileStream = new FileInputStream(contactsFile)) {
1626 SignalServiceAttachmentStream attachmentStream = SignalServiceAttachment.newStreamBuilder()
1627 .withStream(contactsFileStream)
1628 .withContentType("application/octet-stream")
1629 .withLength(contactsFile.length())
1630 .build();
1631
1632 sendSyncMessage(SignalServiceSyncMessage.forContacts(new ContactsMessage(attachmentStream, true)));
1633 }
1634 }
1635 } finally {
1636 try {
1637 Files.delete(contactsFile.toPath());
1638 } catch (IOException e) {
1639 System.err.println("Failed to delete contacts temp file “" + contactsFile + "”: " + e.getMessage());
1640 }
1641 }
1642 }
1643
1644 private void sendBlockedList() throws IOException, UntrustedIdentityException {
1645 List<SignalServiceAddress> addresses = new ArrayList<>();
1646 for (ContactInfo record : account.getContactStore().getContacts()) {
1647 if (record.blocked) {
1648 addresses.add(record.getAddress());
1649 }
1650 }
1651 List<byte[]> groupIds = new ArrayList<>();
1652 for (GroupInfo record : account.getGroupStore().getGroups()) {
1653 if (record.blocked) {
1654 groupIds.add(record.groupId);
1655 }
1656 }
1657 sendSyncMessage(SignalServiceSyncMessage.forBlocked(new BlockedListMessage(addresses, groupIds)));
1658 }
1659
1660 private void sendVerifiedMessage(SignalServiceAddress destination, IdentityKey identityKey, TrustLevel trustLevel) throws IOException, UntrustedIdentityException {
1661 VerifiedMessage verifiedMessage = new VerifiedMessage(destination, identityKey, trustLevel.toVerifiedState(), System.currentTimeMillis());
1662 sendSyncMessage(SignalServiceSyncMessage.forVerified(verifiedMessage));
1663 }
1664
1665 public List<ContactInfo> getContacts() {
1666 return account.getContactStore().getContacts();
1667 }
1668
1669 public ContactInfo getContact(String number) {
1670 return account.getContactStore().getContact(number);
1671 }
1672
1673 public GroupInfo getGroup(byte[] groupId) {
1674 return account.getGroupStore().getGroup(groupId);
1675 }
1676
1677 public Map<String, List<JsonIdentityKeyStore.Identity>> getIdentities() {
1678 return account.getSignalProtocolStore().getIdentities();
1679 }
1680
1681 public Pair<String, List<JsonIdentityKeyStore.Identity>> getIdentities(String number) throws InvalidNumberException {
1682 String canonicalizedNumber = Utils.canonicalizeNumber(number, username);
1683 return new Pair<>(canonicalizedNumber, account.getSignalProtocolStore().getIdentities(canonicalizedNumber));
1684 }
1685
1686 /**
1687 * Trust this the identity with this fingerprint
1688 *
1689 * @param name username of the identity
1690 * @param fingerprint Fingerprint
1691 */
1692 public boolean trustIdentityVerified(String name, byte[] fingerprint) {
1693 List<JsonIdentityKeyStore.Identity> ids = account.getSignalProtocolStore().getIdentities(name);
1694 if (ids == null) {
1695 return false;
1696 }
1697 for (JsonIdentityKeyStore.Identity id : ids) {
1698 if (!Arrays.equals(id.getIdentityKey().serialize(), fingerprint)) {
1699 continue;
1700 }
1701
1702 account.getSignalProtocolStore().saveIdentity(name, id.getIdentityKey(), TrustLevel.TRUSTED_VERIFIED);
1703 try {
1704 sendVerifiedMessage(new SignalServiceAddress(null, name), id.getIdentityKey(), TrustLevel.TRUSTED_VERIFIED);
1705 } catch (IOException | UntrustedIdentityException e) {
1706 e.printStackTrace();
1707 }
1708 account.save();
1709 return true;
1710 }
1711 return false;
1712 }
1713
1714 /**
1715 * Trust this the identity with this safety number
1716 *
1717 * @param name username of the identity
1718 * @param safetyNumber Safety number
1719 */
1720 public boolean trustIdentityVerifiedSafetyNumber(String name, String safetyNumber) {
1721 List<JsonIdentityKeyStore.Identity> ids = account.getSignalProtocolStore().getIdentities(name);
1722 if (ids == null) {
1723 return false;
1724 }
1725 for (JsonIdentityKeyStore.Identity id : ids) {
1726 if (!safetyNumber.equals(computeSafetyNumber(name, id.getIdentityKey()))) {
1727 continue;
1728 }
1729
1730 account.getSignalProtocolStore().saveIdentity(name, id.getIdentityKey(), TrustLevel.TRUSTED_VERIFIED);
1731 try {
1732 sendVerifiedMessage(new SignalServiceAddress(null, name), id.getIdentityKey(), TrustLevel.TRUSTED_VERIFIED);
1733 } catch (IOException | UntrustedIdentityException e) {
1734 e.printStackTrace();
1735 }
1736 account.save();
1737 return true;
1738 }
1739 return false;
1740 }
1741
1742 /**
1743 * Trust all keys of this identity without verification
1744 *
1745 * @param name username of the identity
1746 */
1747 public boolean trustIdentityAllKeys(String name) {
1748 List<JsonIdentityKeyStore.Identity> ids = account.getSignalProtocolStore().getIdentities(name);
1749 if (ids == null) {
1750 return false;
1751 }
1752 for (JsonIdentityKeyStore.Identity id : ids) {
1753 if (id.getTrustLevel() == TrustLevel.UNTRUSTED) {
1754 account.getSignalProtocolStore().saveIdentity(name, id.getIdentityKey(), TrustLevel.TRUSTED_UNVERIFIED);
1755 try {
1756 sendVerifiedMessage(new SignalServiceAddress(null, name), id.getIdentityKey(), TrustLevel.TRUSTED_UNVERIFIED);
1757 } catch (IOException | UntrustedIdentityException e) {
1758 e.printStackTrace();
1759 }
1760 }
1761 }
1762 account.save();
1763 return true;
1764 }
1765
1766 public String computeSafetyNumber(String theirUsername, IdentityKey theirIdentityKey) {
1767 return Utils.computeSafetyNumber(username, getIdentity(), theirUsername, theirIdentityKey);
1768 }
1769
1770 public interface ReceiveMessageHandler {
1771
1772 void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent decryptedContent, Throwable e);
1773 }
1774 }