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