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