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