]> nmode's Git Repositories - signal-cli/blob - lib/src/main/java/org/asamk/signal/manager/Manager.java
Request message resend if incoming message can't be decrypted
[signal-cli] / lib / src / main / java / org / asamk / signal / manager / Manager.java
1 /*
2 Copyright (C) 2015-2021 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.manager.actions.HandleAction;
20 import org.asamk.signal.manager.api.Device;
21 import org.asamk.signal.manager.api.Message;
22 import org.asamk.signal.manager.api.RecipientIdentifier;
23 import org.asamk.signal.manager.api.SendGroupMessageResults;
24 import org.asamk.signal.manager.api.SendMessageResults;
25 import org.asamk.signal.manager.api.TypingAction;
26 import org.asamk.signal.manager.config.ServiceConfig;
27 import org.asamk.signal.manager.config.ServiceEnvironment;
28 import org.asamk.signal.manager.config.ServiceEnvironmentConfig;
29 import org.asamk.signal.manager.groups.GroupId;
30 import org.asamk.signal.manager.groups.GroupInviteLinkUrl;
31 import org.asamk.signal.manager.groups.GroupLinkState;
32 import org.asamk.signal.manager.groups.GroupNotFoundException;
33 import org.asamk.signal.manager.groups.GroupPermission;
34 import org.asamk.signal.manager.groups.GroupSendingNotAllowedException;
35 import org.asamk.signal.manager.groups.LastGroupAdminException;
36 import org.asamk.signal.manager.groups.NotAGroupMemberException;
37 import org.asamk.signal.manager.helper.AttachmentHelper;
38 import org.asamk.signal.manager.helper.ContactHelper;
39 import org.asamk.signal.manager.helper.GroupHelper;
40 import org.asamk.signal.manager.helper.GroupV2Helper;
41 import org.asamk.signal.manager.helper.IncomingMessageHandler;
42 import org.asamk.signal.manager.helper.PinHelper;
43 import org.asamk.signal.manager.helper.PreKeyHelper;
44 import org.asamk.signal.manager.helper.ProfileHelper;
45 import org.asamk.signal.manager.helper.SendHelper;
46 import org.asamk.signal.manager.helper.StorageHelper;
47 import org.asamk.signal.manager.helper.SyncHelper;
48 import org.asamk.signal.manager.helper.UnidentifiedAccessHelper;
49 import org.asamk.signal.manager.jobs.Context;
50 import org.asamk.signal.manager.storage.SignalAccount;
51 import org.asamk.signal.manager.storage.groups.GroupInfo;
52 import org.asamk.signal.manager.storage.identities.IdentityInfo;
53 import org.asamk.signal.manager.storage.identities.TrustNewIdentity;
54 import org.asamk.signal.manager.storage.messageCache.CachedMessage;
55 import org.asamk.signal.manager.storage.recipients.Contact;
56 import org.asamk.signal.manager.storage.recipients.Profile;
57 import org.asamk.signal.manager.storage.recipients.RecipientId;
58 import org.asamk.signal.manager.storage.stickers.Sticker;
59 import org.asamk.signal.manager.storage.stickers.StickerPackId;
60 import org.asamk.signal.manager.util.KeyUtils;
61 import org.asamk.signal.manager.util.StickerUtils;
62 import org.asamk.signal.manager.util.Utils;
63 import org.slf4j.Logger;
64 import org.slf4j.LoggerFactory;
65 import org.whispersystems.libsignal.IdentityKey;
66 import org.whispersystems.libsignal.InvalidKeyException;
67 import org.whispersystems.libsignal.ecc.ECPublicKey;
68 import org.whispersystems.libsignal.fingerprint.Fingerprint;
69 import org.whispersystems.libsignal.fingerprint.FingerprintParsingException;
70 import org.whispersystems.libsignal.fingerprint.FingerprintVersionMismatchException;
71 import org.whispersystems.libsignal.util.Pair;
72 import org.whispersystems.libsignal.util.guava.Optional;
73 import org.whispersystems.signalservice.api.SignalSessionLock;
74 import org.whispersystems.signalservice.api.groupsv2.GroupLinkNotActiveException;
75 import org.whispersystems.signalservice.api.messages.SendMessageResult;
76 import org.whispersystems.signalservice.api.messages.SignalServiceAttachmentRemoteId;
77 import org.whispersystems.signalservice.api.messages.SignalServiceContent;
78 import org.whispersystems.signalservice.api.messages.SignalServiceDataMessage;
79 import org.whispersystems.signalservice.api.messages.SignalServiceEnvelope;
80 import org.whispersystems.signalservice.api.messages.SignalServiceReceiptMessage;
81 import org.whispersystems.signalservice.api.messages.SignalServiceTypingMessage;
82 import org.whispersystems.signalservice.api.push.SignalServiceAddress;
83 import org.whispersystems.signalservice.api.push.exceptions.UnregisteredUserException;
84 import org.whispersystems.signalservice.api.util.DeviceNameUtil;
85 import org.whispersystems.signalservice.api.util.InvalidNumberException;
86 import org.whispersystems.signalservice.api.util.PhoneNumberFormatter;
87 import org.whispersystems.signalservice.api.websocket.WebSocketUnavailableException;
88 import org.whispersystems.signalservice.internal.contacts.crypto.Quote;
89 import org.whispersystems.signalservice.internal.contacts.crypto.UnauthenticatedQuoteException;
90 import org.whispersystems.signalservice.internal.contacts.crypto.UnauthenticatedResponseException;
91 import org.whispersystems.signalservice.internal.util.DynamicCredentialsProvider;
92 import org.whispersystems.signalservice.internal.util.Hex;
93 import org.whispersystems.signalservice.internal.util.Util;
94
95 import java.io.Closeable;
96 import java.io.File;
97 import java.io.IOException;
98 import java.net.URI;
99 import java.net.URISyntaxException;
100 import java.net.URLEncoder;
101 import java.nio.charset.StandardCharsets;
102 import java.security.SignatureException;
103 import java.util.Arrays;
104 import java.util.Collection;
105 import java.util.Date;
106 import java.util.HashMap;
107 import java.util.HashSet;
108 import java.util.List;
109 import java.util.Map;
110 import java.util.Set;
111 import java.util.UUID;
112 import java.util.concurrent.ExecutorService;
113 import java.util.concurrent.Executors;
114 import java.util.concurrent.TimeUnit;
115 import java.util.concurrent.TimeoutException;
116 import java.util.concurrent.locks.ReentrantLock;
117 import java.util.function.Function;
118 import java.util.stream.Collectors;
119
120 import static org.asamk.signal.manager.config.ServiceConfig.capabilities;
121
122 public class Manager implements Closeable {
123
124 private final static Logger logger = LoggerFactory.getLogger(Manager.class);
125
126 private final ServiceEnvironmentConfig serviceEnvironmentConfig;
127 private final SignalDependencies dependencies;
128
129 private SignalAccount account;
130
131 private final ExecutorService executor = Executors.newCachedThreadPool();
132
133 private final ProfileHelper profileHelper;
134 private final PinHelper pinHelper;
135 private final StorageHelper storageHelper;
136 private final SendHelper sendHelper;
137 private final SyncHelper syncHelper;
138 private final AttachmentHelper attachmentHelper;
139 private final GroupHelper groupHelper;
140 private final ContactHelper contactHelper;
141 private final IncomingMessageHandler incomingMessageHandler;
142 private final PreKeyHelper preKeyHelper;
143
144 private final Context context;
145 private boolean hasCaughtUpWithOldMessages = false;
146
147 Manager(
148 SignalAccount account,
149 PathConfig pathConfig,
150 ServiceEnvironmentConfig serviceEnvironmentConfig,
151 String userAgent
152 ) {
153 this.account = account;
154 this.serviceEnvironmentConfig = serviceEnvironmentConfig;
155
156 final var credentialsProvider = new DynamicCredentialsProvider(account.getUuid(),
157 account.getUsername(),
158 account.getPassword(),
159 account.getDeviceId());
160 final var sessionLock = new SignalSessionLock() {
161 private final ReentrantLock LEGACY_LOCK = new ReentrantLock();
162
163 @Override
164 public Lock acquire() {
165 LEGACY_LOCK.lock();
166 return LEGACY_LOCK::unlock;
167 }
168 };
169 this.dependencies = new SignalDependencies(serviceEnvironmentConfig,
170 userAgent,
171 credentialsProvider,
172 account.getSignalProtocolStore(),
173 executor,
174 sessionLock);
175 final var avatarStore = new AvatarStore(pathConfig.getAvatarsPath());
176 final var attachmentStore = new AttachmentStore(pathConfig.getAttachmentsPath());
177 final var stickerPackStore = new StickerPackStore(pathConfig.getStickerPacksPath());
178
179 this.attachmentHelper = new AttachmentHelper(dependencies, attachmentStore);
180 this.pinHelper = new PinHelper(dependencies.getKeyBackupService());
181 final var unidentifiedAccessHelper = new UnidentifiedAccessHelper(account::getProfileKey,
182 account.getProfileStore()::getProfileKey,
183 this::getRecipientProfile,
184 this::getSenderCertificate);
185 this.profileHelper = new ProfileHelper(account,
186 dependencies,
187 avatarStore,
188 account.getProfileStore()::getProfileKey,
189 unidentifiedAccessHelper::getAccessFor,
190 this::resolveSignalServiceAddress);
191 final GroupV2Helper groupV2Helper = new GroupV2Helper(profileHelper::getRecipientProfileKeyCredential,
192 this::getRecipientProfile,
193 account::getSelfRecipientId,
194 dependencies.getGroupsV2Operations(),
195 dependencies.getGroupsV2Api(),
196 this::resolveSignalServiceAddress);
197 this.sendHelper = new SendHelper(account,
198 dependencies,
199 unidentifiedAccessHelper,
200 this::resolveSignalServiceAddress,
201 account.getRecipientStore(),
202 this::handleIdentityFailure,
203 this::getGroup,
204 this::refreshRegisteredUser);
205 this.groupHelper = new GroupHelper(account,
206 dependencies,
207 attachmentHelper,
208 sendHelper,
209 groupV2Helper,
210 avatarStore,
211 this::resolveSignalServiceAddress,
212 account.getRecipientStore());
213 this.storageHelper = new StorageHelper(account, dependencies, groupHelper);
214 this.contactHelper = new ContactHelper(account);
215 this.syncHelper = new SyncHelper(account,
216 attachmentHelper,
217 sendHelper,
218 groupHelper,
219 avatarStore,
220 this::resolveSignalServiceAddress);
221 preKeyHelper = new PreKeyHelper(account, dependencies);
222
223 this.context = new Context(account,
224 dependencies,
225 stickerPackStore,
226 sendHelper,
227 groupHelper,
228 syncHelper,
229 profileHelper,
230 storageHelper,
231 preKeyHelper);
232 var jobExecutor = new JobExecutor(context);
233
234 this.incomingMessageHandler = new IncomingMessageHandler(account,
235 dependencies,
236 account.getRecipientStore(),
237 this::resolveSignalServiceAddress,
238 groupHelper,
239 contactHelper,
240 attachmentHelper,
241 syncHelper,
242 this::getRecipientProfile,
243 jobExecutor);
244 }
245
246 public String getUsername() {
247 return account.getUsername();
248 }
249
250 public RecipientId getSelfRecipientId() {
251 return account.getSelfRecipientId();
252 }
253
254 public int getDeviceId() {
255 return account.getDeviceId();
256 }
257
258 public static Manager init(
259 String username,
260 File settingsPath,
261 ServiceEnvironment serviceEnvironment,
262 String userAgent,
263 final TrustNewIdentity trustNewIdentity
264 ) throws IOException, NotRegisteredException {
265 var pathConfig = PathConfig.createDefault(settingsPath);
266
267 if (!SignalAccount.userExists(pathConfig.getDataPath(), username)) {
268 throw new NotRegisteredException();
269 }
270
271 var account = SignalAccount.load(pathConfig.getDataPath(), username, true, trustNewIdentity);
272
273 if (!account.isRegistered()) {
274 throw new NotRegisteredException();
275 }
276
277 final var serviceEnvironmentConfig = ServiceConfig.getServiceEnvironmentConfig(serviceEnvironment, userAgent);
278
279 return new Manager(account, pathConfig, serviceEnvironmentConfig, userAgent);
280 }
281
282 public static List<String> getAllLocalUsernames(File settingsPath) {
283 var pathConfig = PathConfig.createDefault(settingsPath);
284 final var dataPath = pathConfig.getDataPath();
285 final var files = dataPath.listFiles();
286
287 if (files == null) {
288 return List.of();
289 }
290
291 return Arrays.stream(files)
292 .filter(File::isFile)
293 .map(File::getName)
294 .filter(file -> PhoneNumberFormatter.isValidNumber(file, null))
295 .collect(Collectors.toList());
296 }
297
298 public void checkAccountState() throws IOException {
299 if (account.getLastReceiveTimestamp() == 0) {
300 logger.info("The Signal protocol expects that incoming messages are regularly received.");
301 } else {
302 var diffInMilliseconds = System.currentTimeMillis() - account.getLastReceiveTimestamp();
303 long days = TimeUnit.DAYS.convert(diffInMilliseconds, TimeUnit.MILLISECONDS);
304 if (days > 7) {
305 logger.warn(
306 "Messages have been last received {} days ago. The Signal protocol expects that incoming messages are regularly received.",
307 days);
308 }
309 }
310 preKeyHelper.refreshPreKeysIfNecessary();
311 if (account.getUuid() == null) {
312 account.setUuid(dependencies.getAccountManager().getOwnUuid());
313 }
314 updateAccountAttributes(null);
315 }
316
317 /**
318 * This is used for checking a set of phone numbers for registration on Signal
319 *
320 * @param numbers The set of phone number in question
321 * @return A map of numbers to canonicalized number and uuid. If a number is not registered the uuid is null.
322 * @throws IOException if its unable to get the contacts to check if they're registered
323 */
324 public Map<String, Pair<String, UUID>> areUsersRegistered(Set<String> numbers) throws IOException {
325 Map<String, String> canonicalizedNumbers = numbers.stream().collect(Collectors.toMap(n -> n, n -> {
326 try {
327 return PhoneNumberFormatter.formatNumber(n, account.getUsername());
328 } catch (InvalidNumberException e) {
329 return "";
330 }
331 }));
332
333 // Note "registeredUsers" has no optionals. It only gives us info on users who are registered
334 var registeredUsers = getRegisteredUsers(canonicalizedNumbers.values()
335 .stream()
336 .filter(s -> !s.isEmpty())
337 .collect(Collectors.toSet()));
338
339 return numbers.stream().collect(Collectors.toMap(n -> n, n -> {
340 final var number = canonicalizedNumbers.get(n);
341 final var uuid = registeredUsers.get(number);
342 return new Pair<>(number.isEmpty() ? null : number, uuid);
343 }));
344 }
345
346 public void updateAccountAttributes(String deviceName) throws IOException {
347 final String encryptedDeviceName;
348 if (deviceName == null) {
349 encryptedDeviceName = account.getEncryptedDeviceName();
350 } else {
351 final var privateKey = account.getIdentityKeyPair().getPrivateKey();
352 encryptedDeviceName = DeviceNameUtil.encryptDeviceName(deviceName, privateKey);
353 account.setEncryptedDeviceName(encryptedDeviceName);
354 }
355 dependencies.getAccountManager()
356 .setAccountAttributes(encryptedDeviceName,
357 null,
358 account.getLocalRegistrationId(),
359 true,
360 null,
361 account.getPinMasterKey() == null ? null : account.getPinMasterKey().deriveRegistrationLock(),
362 account.getSelfUnidentifiedAccessKey(),
363 account.isUnrestrictedUnidentifiedAccess(),
364 capabilities,
365 account.isDiscoverableByPhoneNumber());
366 }
367
368 /**
369 * @param givenName if null, the previous givenName will be kept
370 * @param familyName if null, the previous familyName will be kept
371 * @param about if null, the previous about text will be kept
372 * @param aboutEmoji if null, the previous about emoji will be kept
373 * @param avatar if avatar is null the image from the local avatar store is used (if present),
374 */
375 public void setProfile(
376 String givenName, final String familyName, String about, String aboutEmoji, Optional<File> avatar
377 ) throws IOException {
378 profileHelper.setProfile(givenName, familyName, about, aboutEmoji, avatar);
379 syncHelper.sendSyncFetchProfileMessage();
380 }
381
382 public void unregister() throws IOException {
383 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
384 // If this is the master device, other users can't send messages to this number anymore.
385 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
386 dependencies.getAccountManager().setGcmId(Optional.absent());
387
388 account.setRegistered(false);
389 }
390
391 public void deleteAccount() throws IOException {
392 try {
393 pinHelper.removeRegistrationLockPin();
394 } catch (UnauthenticatedResponseException e) {
395 logger.warn("Failed to remove registration lock pin");
396 }
397 account.setRegistrationLockPin(null, null);
398
399 dependencies.getAccountManager().deleteAccount();
400
401 account.setRegistered(false);
402 }
403
404 public void submitRateLimitRecaptchaChallenge(String challenge, String captcha) throws IOException {
405 dependencies.getAccountManager().submitRateLimitRecaptchaChallenge(challenge, captcha);
406 }
407
408 public List<Device> getLinkedDevices() throws IOException {
409 var devices = dependencies.getAccountManager().getDevices();
410 account.setMultiDevice(devices.size() > 1);
411 var identityKey = account.getIdentityKeyPair().getPrivateKey();
412 return devices.stream().map(d -> {
413 String deviceName = d.getName();
414 if (deviceName != null) {
415 try {
416 deviceName = DeviceNameUtil.decryptDeviceName(deviceName, identityKey);
417 } catch (IOException e) {
418 logger.debug("Failed to decrypt device name, maybe plain text?", e);
419 }
420 }
421 return new Device(d.getId(), deviceName, d.getCreated(), d.getLastSeen());
422 }).collect(Collectors.toList());
423 }
424
425 public void removeLinkedDevices(int deviceId) throws IOException {
426 dependencies.getAccountManager().removeDevice(deviceId);
427 var devices = dependencies.getAccountManager().getDevices();
428 account.setMultiDevice(devices.size() > 1);
429 }
430
431 public void addDeviceLink(URI linkUri) throws IOException, InvalidKeyException {
432 var info = DeviceLinkInfo.parseDeviceLinkUri(linkUri);
433
434 addDevice(info.deviceIdentifier, info.deviceKey);
435 }
436
437 private void addDevice(String deviceIdentifier, ECPublicKey deviceKey) throws IOException, InvalidKeyException {
438 var identityKeyPair = account.getIdentityKeyPair();
439 var verificationCode = dependencies.getAccountManager().getNewDeviceVerificationCode();
440
441 dependencies.getAccountManager()
442 .addDevice(deviceIdentifier,
443 deviceKey,
444 identityKeyPair,
445 Optional.of(account.getProfileKey().serialize()),
446 verificationCode);
447 account.setMultiDevice(true);
448 }
449
450 public void setRegistrationLockPin(Optional<String> pin) throws IOException, UnauthenticatedResponseException {
451 if (!account.isMasterDevice()) {
452 throw new RuntimeException("Only master device can set a PIN");
453 }
454 if (pin.isPresent()) {
455 final var masterKey = account.getPinMasterKey() != null
456 ? account.getPinMasterKey()
457 : KeyUtils.createMasterKey();
458
459 pinHelper.setRegistrationLockPin(pin.get(), masterKey);
460
461 account.setRegistrationLockPin(pin.get(), masterKey);
462 } else {
463 // Remove KBS Pin
464 pinHelper.removeRegistrationLockPin();
465
466 account.setRegistrationLockPin(null, null);
467 }
468 }
469
470 void refreshPreKeys() throws IOException {
471 preKeyHelper.refreshPreKeys();
472 }
473
474 public Profile getRecipientProfile(RecipientId recipientId) {
475 return profileHelper.getRecipientProfile(recipientId);
476 }
477
478 public List<GroupInfo> getGroups() {
479 return account.getGroupStore().getGroups();
480 }
481
482 public SendGroupMessageResults quitGroup(
483 GroupId groupId, Set<RecipientIdentifier.Single> groupAdmins
484 ) throws GroupNotFoundException, IOException, NotAGroupMemberException, LastGroupAdminException {
485 final var newAdmins = resolveRecipients(groupAdmins);
486 return groupHelper.quitGroup(groupId, newAdmins);
487 }
488
489 public void deleteGroup(GroupId groupId) throws IOException {
490 groupHelper.deleteGroup(groupId);
491 }
492
493 public Pair<GroupId, SendGroupMessageResults> createGroup(
494 String name, Set<RecipientIdentifier.Single> members, File avatarFile
495 ) throws IOException, AttachmentInvalidException {
496 return groupHelper.createGroup(name, members == null ? null : resolveRecipients(members), avatarFile);
497 }
498
499 public SendGroupMessageResults updateGroup(
500 GroupId groupId,
501 String name,
502 String description,
503 Set<RecipientIdentifier.Single> members,
504 Set<RecipientIdentifier.Single> removeMembers,
505 Set<RecipientIdentifier.Single> admins,
506 Set<RecipientIdentifier.Single> removeAdmins,
507 boolean resetGroupLink,
508 GroupLinkState groupLinkState,
509 GroupPermission addMemberPermission,
510 GroupPermission editDetailsPermission,
511 File avatarFile,
512 Integer expirationTimer,
513 Boolean isAnnouncementGroup
514 ) throws IOException, GroupNotFoundException, AttachmentInvalidException, NotAGroupMemberException, GroupSendingNotAllowedException {
515 return groupHelper.updateGroup(groupId,
516 name,
517 description,
518 members == null ? null : resolveRecipients(members),
519 removeMembers == null ? null : resolveRecipients(removeMembers),
520 admins == null ? null : resolveRecipients(admins),
521 removeAdmins == null ? null : resolveRecipients(removeAdmins),
522 resetGroupLink,
523 groupLinkState,
524 addMemberPermission,
525 editDetailsPermission,
526 avatarFile,
527 expirationTimer,
528 isAnnouncementGroup);
529 }
530
531 public Pair<GroupId, SendGroupMessageResults> joinGroup(
532 GroupInviteLinkUrl inviteLinkUrl
533 ) throws IOException, GroupLinkNotActiveException {
534 return groupHelper.joinGroup(inviteLinkUrl);
535 }
536
537 public SendMessageResults sendMessage(
538 SignalServiceDataMessage.Builder messageBuilder, Set<RecipientIdentifier> recipients
539 ) throws IOException, NotAGroupMemberException, GroupNotFoundException, GroupSendingNotAllowedException {
540 var results = new HashMap<RecipientIdentifier, List<SendMessageResult>>();
541 long timestamp = System.currentTimeMillis();
542 messageBuilder.withTimestamp(timestamp);
543 for (final var recipient : recipients) {
544 if (recipient instanceof RecipientIdentifier.Single) {
545 final var recipientId = resolveRecipient((RecipientIdentifier.Single) recipient);
546 final var result = sendHelper.sendMessage(messageBuilder, recipientId);
547 results.put(recipient, List.of(result));
548 } else if (recipient instanceof RecipientIdentifier.NoteToSelf) {
549 final var result = sendHelper.sendSelfMessage(messageBuilder);
550 results.put(recipient, List.of(result));
551 } else if (recipient instanceof RecipientIdentifier.Group) {
552 final var groupId = ((RecipientIdentifier.Group) recipient).groupId;
553 final var result = sendHelper.sendAsGroupMessage(messageBuilder, groupId);
554 results.put(recipient, result);
555 }
556 }
557 return new SendMessageResults(timestamp, results);
558 }
559
560 public void sendTypingMessage(
561 SignalServiceTypingMessage.Action action, Set<RecipientIdentifier> recipients
562 ) throws IOException, UntrustedIdentityException, NotAGroupMemberException, GroupNotFoundException, GroupSendingNotAllowedException {
563 final var timestamp = System.currentTimeMillis();
564 for (var recipient : recipients) {
565 if (recipient instanceof RecipientIdentifier.Single) {
566 final var message = new SignalServiceTypingMessage(action, timestamp, Optional.absent());
567 final var recipientId = resolveRecipient((RecipientIdentifier.Single) recipient);
568 sendHelper.sendTypingMessage(message, recipientId);
569 } else if (recipient instanceof RecipientIdentifier.Group) {
570 final var groupId = ((RecipientIdentifier.Group) recipient).groupId;
571 final var message = new SignalServiceTypingMessage(action, timestamp, Optional.of(groupId.serialize()));
572 sendHelper.sendGroupTypingMessage(message, groupId);
573 }
574 }
575 }
576
577 public void sendReadReceipt(
578 RecipientIdentifier.Single sender, List<Long> messageIds
579 ) throws IOException, UntrustedIdentityException {
580 var receiptMessage = new SignalServiceReceiptMessage(SignalServiceReceiptMessage.Type.READ,
581 messageIds,
582 System.currentTimeMillis());
583
584 sendHelper.sendReceiptMessage(receiptMessage, resolveRecipient(sender));
585 }
586
587 public void sendViewedReceipt(
588 RecipientIdentifier.Single sender, List<Long> messageIds
589 ) throws IOException, UntrustedIdentityException {
590 var receiptMessage = new SignalServiceReceiptMessage(SignalServiceReceiptMessage.Type.VIEWED,
591 messageIds,
592 System.currentTimeMillis());
593
594 sendHelper.sendReceiptMessage(receiptMessage, resolveRecipient(sender));
595 }
596
597 public SendMessageResults sendMessage(
598 Message message, Set<RecipientIdentifier> recipients
599 ) throws IOException, AttachmentInvalidException, NotAGroupMemberException, GroupNotFoundException, GroupSendingNotAllowedException {
600 final var messageBuilder = SignalServiceDataMessage.newBuilder();
601 applyMessage(messageBuilder, message);
602 return sendMessage(messageBuilder, recipients);
603 }
604
605 private void applyMessage(
606 final SignalServiceDataMessage.Builder messageBuilder, final Message message
607 ) throws AttachmentInvalidException, IOException {
608 messageBuilder.withBody(message.getMessageText());
609 final var attachments = message.getAttachments();
610 if (attachments != null) {
611 messageBuilder.withAttachments(attachmentHelper.uploadAttachments(attachments));
612 }
613 }
614
615 public SendMessageResults sendRemoteDeleteMessage(
616 long targetSentTimestamp, Set<RecipientIdentifier> recipients
617 ) throws IOException, NotAGroupMemberException, GroupNotFoundException, GroupSendingNotAllowedException {
618 var delete = new SignalServiceDataMessage.RemoteDelete(targetSentTimestamp);
619 final var messageBuilder = SignalServiceDataMessage.newBuilder().withRemoteDelete(delete);
620 return sendMessage(messageBuilder, recipients);
621 }
622
623 public SendMessageResults sendMessageReaction(
624 String emoji,
625 boolean remove,
626 RecipientIdentifier.Single targetAuthor,
627 long targetSentTimestamp,
628 Set<RecipientIdentifier> recipients
629 ) throws IOException, NotAGroupMemberException, GroupNotFoundException, GroupSendingNotAllowedException {
630 var targetAuthorRecipientId = resolveRecipient(targetAuthor);
631 var reaction = new SignalServiceDataMessage.Reaction(emoji,
632 remove,
633 resolveSignalServiceAddress(targetAuthorRecipientId),
634 targetSentTimestamp);
635 final var messageBuilder = SignalServiceDataMessage.newBuilder().withReaction(reaction);
636 return sendMessage(messageBuilder, recipients);
637 }
638
639 public SendMessageResults sendEndSessionMessage(Set<RecipientIdentifier.Single> recipients) throws IOException {
640 var messageBuilder = SignalServiceDataMessage.newBuilder().asEndSessionMessage();
641
642 try {
643 return sendMessage(messageBuilder,
644 recipients.stream().map(RecipientIdentifier.class::cast).collect(Collectors.toSet()));
645 } catch (GroupNotFoundException | NotAGroupMemberException | GroupSendingNotAllowedException e) {
646 throw new AssertionError(e);
647 } finally {
648 for (var recipient : recipients) {
649 final var recipientId = resolveRecipient(recipient);
650 account.getSessionStore().deleteAllSessions(recipientId);
651 }
652 }
653 }
654
655 public void setContactName(
656 RecipientIdentifier.Single recipient, String name
657 ) throws NotMasterDeviceException, UnregisteredUserException {
658 if (!account.isMasterDevice()) {
659 throw new NotMasterDeviceException();
660 }
661 contactHelper.setContactName(resolveRecipient(recipient), name);
662 }
663
664 public void setContactBlocked(
665 RecipientIdentifier.Single recipient, boolean blocked
666 ) throws NotMasterDeviceException, IOException {
667 if (!account.isMasterDevice()) {
668 throw new NotMasterDeviceException();
669 }
670 contactHelper.setContactBlocked(resolveRecipient(recipient), blocked);
671 // TODO cycle our profile key
672 syncHelper.sendBlockedList();
673 }
674
675 public void setGroupBlocked(
676 final GroupId groupId, final boolean blocked
677 ) throws GroupNotFoundException, IOException {
678 groupHelper.setGroupBlocked(groupId, blocked);
679 // TODO cycle our profile key
680 syncHelper.sendBlockedList();
681 }
682
683 /**
684 * Change the expiration timer for a contact
685 */
686 public void setExpirationTimer(
687 RecipientIdentifier.Single recipient, int messageExpirationTimer
688 ) throws IOException {
689 var recipientId = resolveRecipient(recipient);
690 contactHelper.setExpirationTimer(recipientId, messageExpirationTimer);
691 final var messageBuilder = SignalServiceDataMessage.newBuilder().asExpirationUpdate();
692 try {
693 sendMessage(messageBuilder, Set.of(recipient));
694 } catch (NotAGroupMemberException | GroupNotFoundException | GroupSendingNotAllowedException e) {
695 throw new AssertionError(e);
696 }
697 }
698
699 /**
700 * Upload the sticker pack from path.
701 *
702 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
703 * @return if successful, returns the URL to install the sticker pack in the signal app
704 */
705 public URI uploadStickerPack(File path) throws IOException, StickerPackInvalidException {
706 var manifest = StickerUtils.getSignalServiceStickerManifestUpload(path);
707
708 var messageSender = dependencies.getMessageSender();
709
710 var packKey = KeyUtils.createStickerUploadKey();
711 var packIdString = messageSender.uploadStickerManifest(manifest, packKey);
712 var packId = StickerPackId.deserialize(Hex.fromStringCondensed(packIdString));
713
714 var sticker = new Sticker(packId, packKey);
715 account.getStickerStore().updateSticker(sticker);
716
717 try {
718 return new URI("https",
719 "signal.art",
720 "/addstickers/",
721 "pack_id="
722 + URLEncoder.encode(Hex.toStringCondensed(packId.serialize()), StandardCharsets.UTF_8)
723 + "&pack_key="
724 + URLEncoder.encode(Hex.toStringCondensed(packKey), StandardCharsets.UTF_8));
725 } catch (URISyntaxException e) {
726 throw new AssertionError(e);
727 }
728 }
729
730 public void requestAllSyncData() throws IOException {
731 syncHelper.requestAllSyncData();
732 retrieveRemoteStorage();
733 }
734
735 void retrieveRemoteStorage() throws IOException {
736 if (account.getStorageKey() != null) {
737 storageHelper.readDataFromStorage();
738 }
739 }
740
741 private byte[] getSenderCertificate() {
742 byte[] certificate;
743 try {
744 if (account.isPhoneNumberShared()) {
745 certificate = dependencies.getAccountManager().getSenderCertificate();
746 } else {
747 certificate = dependencies.getAccountManager().getSenderCertificateForPhoneNumberPrivacy();
748 }
749 } catch (IOException e) {
750 logger.warn("Failed to get sender certificate, ignoring: {}", e.getMessage());
751 return null;
752 }
753 // TODO cache for a day
754 return certificate;
755 }
756
757 private RecipientId refreshRegisteredUser(RecipientId recipientId) throws IOException {
758 final var address = resolveSignalServiceAddress(recipientId);
759 if (!address.getNumber().isPresent()) {
760 return recipientId;
761 }
762 final var number = address.getNumber().get();
763 final var uuid = getRegisteredUser(number);
764 return resolveRecipientTrusted(new SignalServiceAddress(uuid, number));
765 }
766
767 private UUID getRegisteredUser(final String number) throws IOException {
768 final Map<String, UUID> uuidMap;
769 try {
770 uuidMap = getRegisteredUsers(Set.of(number));
771 } catch (NumberFormatException e) {
772 throw new UnregisteredUserException(number, e);
773 }
774 final var uuid = uuidMap.get(number);
775 if (uuid == null) {
776 throw new UnregisteredUserException(number, null);
777 }
778 return uuid;
779 }
780
781 private Map<String, UUID> getRegisteredUsers(final Set<String> numbers) throws IOException {
782 final Map<String, UUID> registeredUsers;
783 try {
784 registeredUsers = dependencies.getAccountManager()
785 .getRegisteredUsers(ServiceConfig.getIasKeyStore(),
786 numbers,
787 serviceEnvironmentConfig.getCdsMrenclave());
788 } catch (Quote.InvalidQuoteFormatException | UnauthenticatedQuoteException | SignatureException | UnauthenticatedResponseException | InvalidKeyException e) {
789 throw new IOException(e);
790 }
791
792 // Store numbers as recipients so we have the number/uuid association
793 registeredUsers.forEach((number, uuid) -> resolveRecipientTrusted(new SignalServiceAddress(uuid, number)));
794
795 return registeredUsers;
796 }
797
798 public void sendTypingMessage(
799 TypingAction action, Set<RecipientIdentifier> recipients
800 ) throws IOException, UntrustedIdentityException, NotAGroupMemberException, GroupNotFoundException, GroupSendingNotAllowedException {
801 sendTypingMessage(action.toSignalService(), recipients);
802 }
803
804 private void retryFailedReceivedMessages(ReceiveMessageHandler handler, boolean ignoreAttachments) {
805 Set<HandleAction> queuedActions = new HashSet<>();
806 for (var cachedMessage : account.getMessageCache().getCachedMessages()) {
807 var actions = retryFailedReceivedMessage(handler, ignoreAttachments, cachedMessage);
808 if (actions != null) {
809 queuedActions.addAll(actions);
810 }
811 }
812 handleQueuedActions(queuedActions);
813 }
814
815 private List<HandleAction> retryFailedReceivedMessage(
816 final ReceiveMessageHandler handler, final boolean ignoreAttachments, final CachedMessage cachedMessage
817 ) {
818 var envelope = cachedMessage.loadEnvelope();
819 if (envelope == null) {
820 cachedMessage.delete();
821 return null;
822 }
823
824 final var result = incomingMessageHandler.handleRetryEnvelope(envelope, ignoreAttachments, handler);
825 final var actions = result.first();
826 final var exception = result.second();
827
828 if (exception instanceof UntrustedIdentityException) {
829 if (System.currentTimeMillis() - envelope.getServerDeliveredTimestamp() > 1000L * 60 * 60 * 24 * 30) {
830 // Envelope is more than a month old, cleaning up.
831 cachedMessage.delete();
832 return null;
833 }
834 if (!envelope.hasSourceUuid()) {
835 final var identifier = ((UntrustedIdentityException) exception).getSender();
836 final var recipientId = account.getRecipientStore().resolveRecipient(identifier);
837 try {
838 account.getMessageCache().replaceSender(cachedMessage, recipientId);
839 } catch (IOException ioException) {
840 logger.warn("Failed to move cached message to recipient folder: {}", ioException.getMessage());
841 }
842 }
843 return null;
844 }
845
846 // If successful and for all other errors that are not recoverable, delete the cached message
847 cachedMessage.delete();
848 return actions;
849 }
850
851 public void receiveMessages(
852 long timeout,
853 TimeUnit unit,
854 boolean returnOnTimeout,
855 boolean ignoreAttachments,
856 ReceiveMessageHandler handler
857 ) throws IOException {
858 retryFailedReceivedMessages(handler, ignoreAttachments);
859
860 Set<HandleAction> queuedActions = new HashSet<>();
861
862 final var signalWebSocket = dependencies.getSignalWebSocket();
863 signalWebSocket.connect();
864
865 hasCaughtUpWithOldMessages = false;
866
867 while (!Thread.interrupted()) {
868 SignalServiceEnvelope envelope;
869 final CachedMessage[] cachedMessage = {null};
870 account.setLastReceiveTimestamp(System.currentTimeMillis());
871 logger.debug("Checking for new message from server");
872 try {
873 var result = signalWebSocket.readOrEmpty(unit.toMillis(timeout), envelope1 -> {
874 final var recipientId = envelope1.hasSourceUuid()
875 ? resolveRecipient(envelope1.getSourceAddress())
876 : null;
877 // store message on disk, before acknowledging receipt to the server
878 cachedMessage[0] = account.getMessageCache().cacheMessage(envelope1, recipientId);
879 });
880 if (result.isPresent()) {
881 envelope = result.get();
882 logger.debug("New message received from server");
883 } else {
884 logger.debug("Received indicator that server queue is empty");
885 handleQueuedActions(queuedActions);
886 queuedActions.clear();
887
888 hasCaughtUpWithOldMessages = true;
889 synchronized (this) {
890 this.notifyAll();
891 }
892
893 // Continue to wait another timeout for new messages
894 continue;
895 }
896 } catch (AssertionError e) {
897 if (e.getCause() instanceof InterruptedException) {
898 Thread.currentThread().interrupt();
899 break;
900 } else {
901 throw e;
902 }
903 } catch (WebSocketUnavailableException e) {
904 logger.debug("Pipe unexpectedly unavailable, connecting");
905 signalWebSocket.connect();
906 continue;
907 } catch (TimeoutException e) {
908 if (returnOnTimeout) return;
909 continue;
910 }
911
912 final var result = incomingMessageHandler.handleEnvelope(envelope, ignoreAttachments, handler);
913 queuedActions.addAll(result.first());
914 final var exception = result.second();
915
916 if (hasCaughtUpWithOldMessages) {
917 handleQueuedActions(queuedActions);
918 }
919 if (cachedMessage[0] != null) {
920 if (exception instanceof UntrustedIdentityException) {
921 final var address = ((UntrustedIdentityException) exception).getSender();
922 final var recipientId = resolveRecipient(address);
923 if (!envelope.hasSourceUuid()) {
924 try {
925 cachedMessage[0] = account.getMessageCache().replaceSender(cachedMessage[0], recipientId);
926 } catch (IOException ioException) {
927 logger.warn("Failed to move cached message to recipient folder: {}",
928 ioException.getMessage());
929 }
930 }
931 } else {
932 cachedMessage[0].delete();
933 }
934 }
935 }
936 handleQueuedActions(queuedActions);
937 }
938
939 public boolean hasCaughtUpWithOldMessages() {
940 return hasCaughtUpWithOldMessages;
941 }
942
943 private void handleQueuedActions(final Collection<HandleAction> queuedActions) {
944 var interrupted = false;
945 for (var action : queuedActions) {
946 try {
947 action.execute(context);
948 } catch (Throwable e) {
949 if ((e instanceof AssertionError || e instanceof RuntimeException)
950 && e.getCause() instanceof InterruptedException) {
951 interrupted = true;
952 continue;
953 }
954 logger.warn("Message action failed.", e);
955 }
956 }
957 if (interrupted) {
958 Thread.currentThread().interrupt();
959 }
960 }
961
962 public boolean isContactBlocked(final RecipientIdentifier.Single recipient) {
963 final RecipientId recipientId;
964 try {
965 recipientId = resolveRecipient(recipient);
966 } catch (UnregisteredUserException e) {
967 return false;
968 }
969 return contactHelper.isContactBlocked(recipientId);
970 }
971
972 public File getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId) {
973 return attachmentHelper.getAttachmentFile(attachmentId);
974 }
975
976 public void sendContacts() throws IOException {
977 syncHelper.sendContacts();
978 }
979
980 public List<Pair<RecipientId, Contact>> getContacts() {
981 return account.getContactStore().getContacts();
982 }
983
984 public String getContactOrProfileName(RecipientIdentifier.Single recipientIdentifier) {
985 final RecipientId recipientId;
986 try {
987 recipientId = resolveRecipient(recipientIdentifier);
988 } catch (UnregisteredUserException e) {
989 return null;
990 }
991
992 final var contact = account.getContactStore().getContact(recipientId);
993 if (contact != null && !Util.isEmpty(contact.getName())) {
994 return contact.getName();
995 }
996
997 final var profile = getRecipientProfile(recipientId);
998 if (profile != null) {
999 return profile.getDisplayName();
1000 }
1001
1002 return null;
1003 }
1004
1005 public GroupInfo getGroup(GroupId groupId) {
1006 return groupHelper.getGroup(groupId);
1007 }
1008
1009 public List<IdentityInfo> getIdentities() {
1010 return account.getIdentityKeyStore().getIdentities();
1011 }
1012
1013 public List<IdentityInfo> getIdentities(RecipientIdentifier.Single recipient) {
1014 IdentityInfo identity;
1015 try {
1016 identity = account.getIdentityKeyStore().getIdentity(resolveRecipient(recipient));
1017 } catch (UnregisteredUserException e) {
1018 identity = null;
1019 }
1020 return identity == null ? List.of() : List.of(identity);
1021 }
1022
1023 /**
1024 * Trust this the identity with this fingerprint
1025 *
1026 * @param recipient username of the identity
1027 * @param fingerprint Fingerprint
1028 */
1029 public boolean trustIdentityVerified(RecipientIdentifier.Single recipient, byte[] fingerprint) {
1030 RecipientId recipientId;
1031 try {
1032 recipientId = resolveRecipient(recipient);
1033 } catch (UnregisteredUserException e) {
1034 return false;
1035 }
1036 return trustIdentity(recipientId,
1037 identityKey -> Arrays.equals(identityKey.serialize(), fingerprint),
1038 TrustLevel.TRUSTED_VERIFIED);
1039 }
1040
1041 /**
1042 * Trust this the identity with this safety number
1043 *
1044 * @param recipient username of the identity
1045 * @param safetyNumber Safety number
1046 */
1047 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier.Single recipient, String safetyNumber) {
1048 RecipientId recipientId;
1049 try {
1050 recipientId = resolveRecipient(recipient);
1051 } catch (UnregisteredUserException e) {
1052 return false;
1053 }
1054 var address = resolveSignalServiceAddress(recipientId);
1055 return trustIdentity(recipientId,
1056 identityKey -> safetyNumber.equals(computeSafetyNumber(address, identityKey)),
1057 TrustLevel.TRUSTED_VERIFIED);
1058 }
1059
1060 /**
1061 * Trust this the identity with this scannable safety number
1062 *
1063 * @param recipient username of the identity
1064 * @param safetyNumber Scannable safety number
1065 */
1066 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier.Single recipient, byte[] safetyNumber) {
1067 RecipientId recipientId;
1068 try {
1069 recipientId = resolveRecipient(recipient);
1070 } catch (UnregisteredUserException e) {
1071 return false;
1072 }
1073 var address = resolveSignalServiceAddress(recipientId);
1074 return trustIdentity(recipientId, identityKey -> {
1075 final var fingerprint = computeSafetyNumberFingerprint(address, identityKey);
1076 try {
1077 return fingerprint != null && fingerprint.getScannableFingerprint().compareTo(safetyNumber);
1078 } catch (FingerprintVersionMismatchException | FingerprintParsingException e) {
1079 return false;
1080 }
1081 }, TrustLevel.TRUSTED_VERIFIED);
1082 }
1083
1084 /**
1085 * Trust all keys of this identity without verification
1086 *
1087 * @param recipient username of the identity
1088 */
1089 public boolean trustIdentityAllKeys(RecipientIdentifier.Single recipient) {
1090 RecipientId recipientId;
1091 try {
1092 recipientId = resolveRecipient(recipient);
1093 } catch (UnregisteredUserException e) {
1094 return false;
1095 }
1096 return trustIdentity(recipientId, identityKey -> true, TrustLevel.TRUSTED_UNVERIFIED);
1097 }
1098
1099 private boolean trustIdentity(
1100 RecipientId recipientId, Function<IdentityKey, Boolean> verifier, TrustLevel trustLevel
1101 ) {
1102 var identity = account.getIdentityKeyStore().getIdentity(recipientId);
1103 if (identity == null) {
1104 return false;
1105 }
1106
1107 if (!verifier.apply(identity.getIdentityKey())) {
1108 return false;
1109 }
1110
1111 account.getIdentityKeyStore().setIdentityTrustLevel(recipientId, identity.getIdentityKey(), trustLevel);
1112 try {
1113 var address = resolveSignalServiceAddress(recipientId);
1114 syncHelper.sendVerifiedMessage(address, identity.getIdentityKey(), trustLevel);
1115 } catch (IOException e) {
1116 logger.warn("Failed to send verification sync message: {}", e.getMessage());
1117 }
1118
1119 return true;
1120 }
1121
1122 private void handleIdentityFailure(
1123 final RecipientId recipientId, final SendMessageResult.IdentityFailure identityFailure
1124 ) {
1125 final var identityKey = identityFailure.getIdentityKey();
1126 if (identityKey != null) {
1127 final var newIdentity = account.getIdentityKeyStore().saveIdentity(recipientId, identityKey, new Date());
1128 if (newIdentity) {
1129 account.getSessionStore().archiveSessions(recipientId);
1130 }
1131 } else {
1132 // Retrieve profile to get the current identity key from the server
1133 profileHelper.refreshRecipientProfile(recipientId);
1134 }
1135 }
1136
1137 public String computeSafetyNumber(SignalServiceAddress theirAddress, IdentityKey theirIdentityKey) {
1138 final Fingerprint fingerprint = computeSafetyNumberFingerprint(theirAddress, theirIdentityKey);
1139 return fingerprint == null ? null : fingerprint.getDisplayableFingerprint().getDisplayText();
1140 }
1141
1142 public byte[] computeSafetyNumberForScanning(SignalServiceAddress theirAddress, IdentityKey theirIdentityKey) {
1143 final Fingerprint fingerprint = computeSafetyNumberFingerprint(theirAddress, theirIdentityKey);
1144 return fingerprint == null ? null : fingerprint.getScannableFingerprint().getSerialized();
1145 }
1146
1147 private Fingerprint computeSafetyNumberFingerprint(
1148 final SignalServiceAddress theirAddress, final IdentityKey theirIdentityKey
1149 ) {
1150 return Utils.computeSafetyNumber(capabilities.isUuid(),
1151 account.getSelfAddress(),
1152 account.getIdentityKeyPair().getPublicKey(),
1153 theirAddress,
1154 theirIdentityKey);
1155 }
1156
1157 public SignalServiceAddress resolveSignalServiceAddress(SignalServiceAddress address) {
1158 return resolveSignalServiceAddress(resolveRecipient(address));
1159 }
1160
1161 public SignalServiceAddress resolveSignalServiceAddress(UUID uuid) {
1162 return resolveSignalServiceAddress(account.getRecipientStore().resolveRecipient(uuid));
1163 }
1164
1165 public SignalServiceAddress resolveSignalServiceAddress(RecipientId recipientId) {
1166 final var address = account.getRecipientStore().resolveRecipientAddress(recipientId);
1167 if (address.getUuid().isPresent()) {
1168 return address.toSignalServiceAddress();
1169 }
1170
1171 // Address in recipient store doesn't have a uuid, this shouldn't happen
1172 // Try to retrieve the uuid from the server
1173 final var number = address.getNumber().get();
1174 try {
1175 return resolveSignalServiceAddress(getRegisteredUser(number));
1176 } catch (IOException e) {
1177 logger.warn("Failed to get uuid for e164 number: {}", number, e);
1178 // Return SignalServiceAddress with unknown UUID
1179 return address.toSignalServiceAddress();
1180 }
1181 }
1182
1183 private Set<RecipientId> resolveRecipients(Collection<RecipientIdentifier.Single> recipients) throws UnregisteredUserException {
1184 final var recipientIds = new HashSet<RecipientId>(recipients.size());
1185 for (var number : recipients) {
1186 final var recipientId = resolveRecipient(number);
1187 recipientIds.add(recipientId);
1188 }
1189 return recipientIds;
1190 }
1191
1192 private RecipientId resolveRecipient(final RecipientIdentifier.Single recipient) throws UnregisteredUserException {
1193 if (recipient instanceof RecipientIdentifier.Uuid) {
1194 return account.getRecipientStore().resolveRecipient(((RecipientIdentifier.Uuid) recipient).uuid);
1195 } else {
1196 final var number = ((RecipientIdentifier.Number) recipient).number;
1197 return account.getRecipientStore().resolveRecipient(number, () -> {
1198 try {
1199 return getRegisteredUser(number);
1200 } catch (IOException e) {
1201 return null;
1202 }
1203 });
1204 }
1205 }
1206
1207 private RecipientId resolveRecipient(SignalServiceAddress address) {
1208 return account.getRecipientStore().resolveRecipient(address);
1209 }
1210
1211 private RecipientId resolveRecipientTrusted(SignalServiceAddress address) {
1212 return account.getRecipientStore().resolveRecipientTrusted(address);
1213 }
1214
1215 @Override
1216 public void close() throws IOException {
1217 close(true);
1218 }
1219
1220 private void close(boolean closeAccount) throws IOException {
1221 executor.shutdown();
1222
1223 dependencies.getSignalWebSocket().disconnect();
1224
1225 if (closeAccount && account != null) {
1226 account.close();
1227 }
1228 account = null;
1229 }
1230
1231 public interface ReceiveMessageHandler {
1232
1233 void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent decryptedContent, Throwable e);
1234 }
1235 }