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