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