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