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