]> nmode's Git Repositories - signal-cli/blob - lib/src/main/java/org/asamk/signal/manager/Manager.java
Catch ProofRequiredException from getPreKeys request and wrap in SendMessageResult
[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 List<Device> getLinkedDevices() throws IOException {
409 var devices = dependencies.getAccountManager().getDevices();
410 account.setMultiDevice(devices.size() > 1);
411 var identityKey = account.getIdentityKeyPair().getPrivateKey();
412 return devices.stream().map(d -> {
413 String deviceName = d.getName();
414 if (deviceName != null) {
415 try {
416 deviceName = DeviceNameUtil.decryptDeviceName(deviceName, identityKey);
417 } catch (IOException e) {
418 logger.debug("Failed to decrypt device name, maybe plain text?", e);
419 }
420 }
421 return new Device(d.getId(), deviceName, d.getCreated(), d.getLastSeen());
422 }).collect(Collectors.toList());
423 }
424
425 public void removeLinkedDevices(int deviceId) throws IOException {
426 dependencies.getAccountManager().removeDevice(deviceId);
427 var devices = dependencies.getAccountManager().getDevices();
428 account.setMultiDevice(devices.size() > 1);
429 }
430
431 public void addDeviceLink(URI linkUri) throws IOException, InvalidKeyException {
432 var info = DeviceLinkInfo.parseDeviceLinkUri(linkUri);
433
434 addDevice(info.deviceIdentifier, info.deviceKey);
435 }
436
437 private void addDevice(String deviceIdentifier, ECPublicKey deviceKey) throws IOException, InvalidKeyException {
438 var identityKeyPair = getIdentityKeyPair();
439 var verificationCode = dependencies.getAccountManager().getNewDeviceVerificationCode();
440
441 dependencies.getAccountManager()
442 .addDevice(deviceIdentifier,
443 deviceKey,
444 identityKeyPair,
445 Optional.of(account.getProfileKey().serialize()),
446 verificationCode);
447 account.setMultiDevice(true);
448 }
449
450 public void setRegistrationLockPin(Optional<String> pin) throws IOException, UnauthenticatedResponseException {
451 if (!account.isMasterDevice()) {
452 throw new RuntimeException("Only master device can set a PIN");
453 }
454 if (pin.isPresent()) {
455 final var masterKey = account.getPinMasterKey() != null
456 ? account.getPinMasterKey()
457 : KeyUtils.createMasterKey();
458
459 pinHelper.setRegistrationLockPin(pin.get(), masterKey);
460
461 account.setRegistrationLockPin(pin.get(), masterKey);
462 } else {
463 // Remove KBS Pin
464 pinHelper.removeRegistrationLockPin();
465
466 account.setRegistrationLockPin(null, null);
467 }
468 }
469
470 void refreshPreKeys() throws IOException {
471 var oneTimePreKeys = generatePreKeys();
472 final var identityKeyPair = getIdentityKeyPair();
473 var signedPreKeyRecord = generateSignedPreKey(identityKeyPair);
474
475 dependencies.getAccountManager().setPreKeys(identityKeyPair.getPublicKey(), signedPreKeyRecord, oneTimePreKeys);
476 }
477
478 private List<PreKeyRecord> generatePreKeys() {
479 final var offset = account.getPreKeyIdOffset();
480
481 var records = KeyUtils.generatePreKeyRecords(offset, ServiceConfig.PREKEY_BATCH_SIZE);
482 account.addPreKeys(records);
483
484 return records;
485 }
486
487 private SignedPreKeyRecord generateSignedPreKey(IdentityKeyPair identityKeyPair) {
488 final var signedPreKeyId = account.getNextSignedPreKeyId();
489
490 var record = KeyUtils.generateSignedPreKeyRecord(identityKeyPair, signedPreKeyId);
491 account.addSignedPreKey(record);
492
493 return record;
494 }
495
496 public Profile getRecipientProfile(RecipientId recipientId) {
497 return profileHelper.getRecipientProfile(recipientId);
498 }
499
500 public List<GroupInfo> getGroups() {
501 return account.getGroupStore().getGroups();
502 }
503
504 public SendGroupMessageResults quitGroup(
505 GroupId groupId, Set<RecipientIdentifier.Single> groupAdmins
506 ) throws GroupNotFoundException, IOException, NotAGroupMemberException, LastGroupAdminException {
507 final var newAdmins = resolveRecipients(groupAdmins);
508 return groupHelper.quitGroup(groupId, newAdmins);
509 }
510
511 public void deleteGroup(GroupId groupId) throws IOException {
512 groupHelper.deleteGroup(groupId);
513 }
514
515 public Pair<GroupId, SendGroupMessageResults> createGroup(
516 String name, Set<RecipientIdentifier.Single> members, File avatarFile
517 ) throws IOException, AttachmentInvalidException {
518 return groupHelper.createGroup(name, members == null ? null : resolveRecipients(members), avatarFile);
519 }
520
521 public SendGroupMessageResults updateGroup(
522 GroupId groupId,
523 String name,
524 String description,
525 Set<RecipientIdentifier.Single> members,
526 Set<RecipientIdentifier.Single> removeMembers,
527 Set<RecipientIdentifier.Single> admins,
528 Set<RecipientIdentifier.Single> removeAdmins,
529 boolean resetGroupLink,
530 GroupLinkState groupLinkState,
531 GroupPermission addMemberPermission,
532 GroupPermission editDetailsPermission,
533 File avatarFile,
534 Integer expirationTimer,
535 Boolean isAnnouncementGroup
536 ) throws IOException, GroupNotFoundException, AttachmentInvalidException, NotAGroupMemberException, GroupSendingNotAllowedException {
537 return groupHelper.updateGroup(groupId,
538 name,
539 description,
540 members == null ? null : resolveRecipients(members),
541 removeMembers == null ? null : resolveRecipients(removeMembers),
542 admins == null ? null : resolveRecipients(admins),
543 removeAdmins == null ? null : resolveRecipients(removeAdmins),
544 resetGroupLink,
545 groupLinkState,
546 addMemberPermission,
547 editDetailsPermission,
548 avatarFile,
549 expirationTimer,
550 isAnnouncementGroup);
551 }
552
553 public Pair<GroupId, SendGroupMessageResults> joinGroup(
554 GroupInviteLinkUrl inviteLinkUrl
555 ) throws IOException, GroupLinkNotActiveException {
556 return groupHelper.joinGroup(inviteLinkUrl);
557 }
558
559 public SendMessageResults sendMessage(
560 SignalServiceDataMessage.Builder messageBuilder, Set<RecipientIdentifier> recipients
561 ) throws IOException, NotAGroupMemberException, GroupNotFoundException, GroupSendingNotAllowedException {
562 var results = new HashMap<RecipientIdentifier, List<SendMessageResult>>();
563 long timestamp = System.currentTimeMillis();
564 messageBuilder.withTimestamp(timestamp);
565 for (final var recipient : recipients) {
566 if (recipient instanceof RecipientIdentifier.Single) {
567 final var recipientId = resolveRecipient((RecipientIdentifier.Single) recipient);
568 final var result = sendHelper.sendMessage(messageBuilder, recipientId);
569 results.put(recipient, List.of(result));
570 } else if (recipient instanceof RecipientIdentifier.NoteToSelf) {
571 final var result = sendHelper.sendSelfMessage(messageBuilder);
572 results.put(recipient, List.of(result));
573 } else if (recipient instanceof RecipientIdentifier.Group) {
574 final var groupId = ((RecipientIdentifier.Group) recipient).groupId;
575 final var result = sendHelper.sendAsGroupMessage(messageBuilder, groupId);
576 results.put(recipient, result);
577 }
578 }
579 return new SendMessageResults(timestamp, results);
580 }
581
582 public void sendTypingMessage(
583 SignalServiceTypingMessage.Action action, Set<RecipientIdentifier> recipients
584 ) throws IOException, UntrustedIdentityException, NotAGroupMemberException, GroupNotFoundException, GroupSendingNotAllowedException {
585 final var timestamp = System.currentTimeMillis();
586 for (var recipient : recipients) {
587 if (recipient instanceof RecipientIdentifier.Single) {
588 final var message = new SignalServiceTypingMessage(action, timestamp, Optional.absent());
589 final var recipientId = resolveRecipient((RecipientIdentifier.Single) recipient);
590 sendHelper.sendTypingMessage(message, recipientId);
591 } else if (recipient instanceof RecipientIdentifier.Group) {
592 final var groupId = ((RecipientIdentifier.Group) recipient).groupId;
593 final var message = new SignalServiceTypingMessage(action, timestamp, Optional.of(groupId.serialize()));
594 sendHelper.sendGroupTypingMessage(message, groupId);
595 }
596 }
597 }
598
599 public void sendReadReceipt(
600 RecipientIdentifier.Single sender, List<Long> messageIds
601 ) throws IOException, UntrustedIdentityException {
602 var receiptMessage = new SignalServiceReceiptMessage(SignalServiceReceiptMessage.Type.READ,
603 messageIds,
604 System.currentTimeMillis());
605
606 sendHelper.sendReceiptMessage(receiptMessage, resolveRecipient(sender));
607 }
608
609 public void sendViewedReceipt(
610 RecipientIdentifier.Single sender, List<Long> messageIds
611 ) throws IOException, UntrustedIdentityException {
612 var receiptMessage = new SignalServiceReceiptMessage(SignalServiceReceiptMessage.Type.VIEWED,
613 messageIds,
614 System.currentTimeMillis());
615
616 sendHelper.sendReceiptMessage(receiptMessage, resolveRecipient(sender));
617 }
618
619 public SendMessageResults sendMessage(
620 Message message, Set<RecipientIdentifier> recipients
621 ) throws IOException, AttachmentInvalidException, NotAGroupMemberException, GroupNotFoundException, GroupSendingNotAllowedException {
622 final var messageBuilder = SignalServiceDataMessage.newBuilder();
623 applyMessage(messageBuilder, message);
624 return sendMessage(messageBuilder, recipients);
625 }
626
627 private void applyMessage(
628 final SignalServiceDataMessage.Builder messageBuilder, final Message message
629 ) throws AttachmentInvalidException, IOException {
630 messageBuilder.withBody(message.getMessageText());
631 final var attachments = message.getAttachments();
632 if (attachments != null) {
633 messageBuilder.withAttachments(attachmentHelper.uploadAttachments(attachments));
634 }
635 }
636
637 public SendMessageResults sendRemoteDeleteMessage(
638 long targetSentTimestamp, Set<RecipientIdentifier> recipients
639 ) throws IOException, NotAGroupMemberException, GroupNotFoundException, GroupSendingNotAllowedException {
640 var delete = new SignalServiceDataMessage.RemoteDelete(targetSentTimestamp);
641 final var messageBuilder = SignalServiceDataMessage.newBuilder().withRemoteDelete(delete);
642 return sendMessage(messageBuilder, recipients);
643 }
644
645 public SendMessageResults sendMessageReaction(
646 String emoji,
647 boolean remove,
648 RecipientIdentifier.Single targetAuthor,
649 long targetSentTimestamp,
650 Set<RecipientIdentifier> recipients
651 ) throws IOException, NotAGroupMemberException, GroupNotFoundException, GroupSendingNotAllowedException {
652 var targetAuthorRecipientId = resolveRecipient(targetAuthor);
653 var reaction = new SignalServiceDataMessage.Reaction(emoji,
654 remove,
655 resolveSignalServiceAddress(targetAuthorRecipientId),
656 targetSentTimestamp);
657 final var messageBuilder = SignalServiceDataMessage.newBuilder().withReaction(reaction);
658 return sendMessage(messageBuilder, recipients);
659 }
660
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 public void setContactName(
678 RecipientIdentifier.Single recipient, String name
679 ) throws NotMasterDeviceException, UnregisteredUserException {
680 if (!account.isMasterDevice()) {
681 throw new NotMasterDeviceException();
682 }
683 contactHelper.setContactName(resolveRecipient(recipient), name);
684 }
685
686 public void setContactBlocked(
687 RecipientIdentifier.Single recipient, boolean blocked
688 ) throws NotMasterDeviceException, IOException {
689 if (!account.isMasterDevice()) {
690 throw new NotMasterDeviceException();
691 }
692 contactHelper.setContactBlocked(resolveRecipient(recipient), blocked);
693 // TODO cycle our profile key
694 syncHelper.sendBlockedList();
695 }
696
697 public void setGroupBlocked(
698 final GroupId groupId, final boolean blocked
699 ) throws GroupNotFoundException, IOException {
700 groupHelper.setGroupBlocked(groupId, blocked);
701 // TODO cycle our profile key
702 syncHelper.sendBlockedList();
703 }
704
705 /**
706 * Change the expiration timer for a contact
707 */
708 public void setExpirationTimer(
709 RecipientIdentifier.Single recipient, int messageExpirationTimer
710 ) throws IOException {
711 var recipientId = resolveRecipient(recipient);
712 contactHelper.setExpirationTimer(recipientId, messageExpirationTimer);
713 final var messageBuilder = SignalServiceDataMessage.newBuilder().asExpirationUpdate();
714 try {
715 sendMessage(messageBuilder, Set.of(recipient));
716 } catch (NotAGroupMemberException | GroupNotFoundException | GroupSendingNotAllowedException e) {
717 throw new AssertionError(e);
718 }
719 }
720
721 /**
722 * Upload the sticker pack from path.
723 *
724 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
725 * @return if successful, returns the URL to install the sticker pack in the signal app
726 */
727 public URI uploadStickerPack(File path) throws IOException, StickerPackInvalidException {
728 var manifest = StickerUtils.getSignalServiceStickerManifestUpload(path);
729
730 var messageSender = dependencies.getMessageSender();
731
732 var packKey = KeyUtils.createStickerUploadKey();
733 var packIdString = messageSender.uploadStickerManifest(manifest, packKey);
734 var packId = StickerPackId.deserialize(Hex.fromStringCondensed(packIdString));
735
736 var sticker = new Sticker(packId, packKey);
737 account.getStickerStore().updateSticker(sticker);
738
739 try {
740 return new URI("https",
741 "signal.art",
742 "/addstickers/",
743 "pack_id="
744 + URLEncoder.encode(Hex.toStringCondensed(packId.serialize()), StandardCharsets.UTF_8)
745 + "&pack_key="
746 + URLEncoder.encode(Hex.toStringCondensed(packKey), StandardCharsets.UTF_8));
747 } catch (URISyntaxException e) {
748 throw new AssertionError(e);
749 }
750 }
751
752 public void requestAllSyncData() throws IOException {
753 syncHelper.requestAllSyncData();
754 retrieveRemoteStorage();
755 }
756
757 void retrieveRemoteStorage() throws IOException {
758 if (account.getStorageKey() != null) {
759 storageHelper.readDataFromStorage();
760 }
761 }
762
763 private byte[] getSenderCertificate() {
764 byte[] certificate;
765 try {
766 if (account.isPhoneNumberShared()) {
767 certificate = dependencies.getAccountManager().getSenderCertificate();
768 } else {
769 certificate = dependencies.getAccountManager().getSenderCertificateForPhoneNumberPrivacy();
770 }
771 } catch (IOException e) {
772 logger.warn("Failed to get sender certificate, ignoring: {}", e.getMessage());
773 return null;
774 }
775 // TODO cache for a day
776 return certificate;
777 }
778
779 private RecipientId refreshRegisteredUser(RecipientId recipientId) throws IOException {
780 final var address = resolveSignalServiceAddress(recipientId);
781 if (!address.getNumber().isPresent()) {
782 return recipientId;
783 }
784 final var number = address.getNumber().get();
785 final var uuid = getRegisteredUser(number);
786 return resolveRecipientTrusted(new SignalServiceAddress(uuid, number));
787 }
788
789 private UUID getRegisteredUser(final String number) throws IOException {
790 final Map<String, UUID> uuidMap;
791 try {
792 uuidMap = getRegisteredUsers(Set.of(number));
793 } catch (NumberFormatException e) {
794 throw new UnregisteredUserException(number, e);
795 }
796 final var uuid = uuidMap.get(number);
797 if (uuid == null) {
798 throw new UnregisteredUserException(number, null);
799 }
800 return uuid;
801 }
802
803 private Map<String, UUID> getRegisteredUsers(final Set<String> numbers) throws IOException {
804 final Map<String, UUID> registeredUsers;
805 try {
806 registeredUsers = dependencies.getAccountManager()
807 .getRegisteredUsers(ServiceConfig.getIasKeyStore(),
808 numbers,
809 serviceEnvironmentConfig.getCdsMrenclave());
810 } catch (Quote.InvalidQuoteFormatException | UnauthenticatedQuoteException | SignatureException | UnauthenticatedResponseException | InvalidKeyException e) {
811 throw new IOException(e);
812 }
813
814 // Store numbers as recipients so we have the number/uuid association
815 registeredUsers.forEach((number, uuid) -> resolveRecipientTrusted(new SignalServiceAddress(uuid, number)));
816
817 return registeredUsers;
818 }
819
820 public void sendTypingMessage(
821 TypingAction action, Set<RecipientIdentifier> recipients
822 ) throws IOException, UntrustedIdentityException, NotAGroupMemberException, GroupNotFoundException, GroupSendingNotAllowedException {
823 sendTypingMessage(action.toSignalService(), recipients);
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 public void receiveMessages(
874 long timeout,
875 TimeUnit unit,
876 boolean returnOnTimeout,
877 boolean ignoreAttachments,
878 ReceiveMessageHandler handler
879 ) throws IOException {
880 retryFailedReceivedMessages(handler, ignoreAttachments);
881
882 Set<HandleAction> queuedActions = new HashSet<>();
883
884 final var signalWebSocket = dependencies.getSignalWebSocket();
885 signalWebSocket.connect();
886
887 hasCaughtUpWithOldMessages = false;
888
889 while (!Thread.interrupted()) {
890 SignalServiceEnvelope envelope;
891 final CachedMessage[] cachedMessage = {null};
892 account.setLastReceiveTimestamp(System.currentTimeMillis());
893 logger.debug("Checking for new message from server");
894 try {
895 var result = signalWebSocket.readOrEmpty(unit.toMillis(timeout), envelope1 -> {
896 final var recipientId = envelope1.hasSourceUuid()
897 ? resolveRecipient(envelope1.getSourceAddress())
898 : null;
899 // store message on disk, before acknowledging receipt to the server
900 cachedMessage[0] = account.getMessageCache().cacheMessage(envelope1, recipientId);
901 });
902 logger.debug("New message received from server");
903 if (result.isPresent()) {
904 envelope = result.get();
905 } else {
906 // Received indicator that server queue is empty
907 handleQueuedActions(queuedActions);
908 queuedActions.clear();
909
910 hasCaughtUpWithOldMessages = true;
911 synchronized (this) {
912 this.notifyAll();
913 }
914
915 // Continue to wait another timeout for new messages
916 continue;
917 }
918 } catch (AssertionError e) {
919 if (e.getCause() instanceof InterruptedException) {
920 Thread.currentThread().interrupt();
921 break;
922 } else {
923 throw e;
924 }
925 } catch (WebSocketUnavailableException e) {
926 logger.debug("Pipe unexpectedly unavailable, connecting");
927 signalWebSocket.connect();
928 continue;
929 } catch (TimeoutException e) {
930 if (returnOnTimeout) return;
931 continue;
932 }
933
934 final var result = incomingMessageHandler.handleEnvelope(envelope, ignoreAttachments, handler);
935 queuedActions.addAll(result.first());
936 final var exception = result.second();
937
938 if (hasCaughtUpWithOldMessages) {
939 handleQueuedActions(queuedActions);
940 }
941 if (cachedMessage[0] != null) {
942 if (exception instanceof UntrustedIdentityException) {
943 final var address = ((UntrustedIdentityException) exception).getSender();
944 final var recipientId = resolveRecipient(address);
945 if (!envelope.hasSourceUuid()) {
946 try {
947 cachedMessage[0] = account.getMessageCache().replaceSender(cachedMessage[0], recipientId);
948 } catch (IOException ioException) {
949 logger.warn("Failed to move cached message to recipient folder: {}",
950 ioException.getMessage());
951 }
952 }
953 } else {
954 cachedMessage[0].delete();
955 }
956 }
957 }
958 handleQueuedActions(queuedActions);
959 }
960
961 public boolean hasCaughtUpWithOldMessages() {
962 return hasCaughtUpWithOldMessages;
963 }
964
965 private void handleQueuedActions(final Collection<HandleAction> queuedActions) {
966 var interrupted = false;
967 for (var action : queuedActions) {
968 try {
969 action.execute(context);
970 } catch (Throwable e) {
971 if ((e instanceof AssertionError || e instanceof RuntimeException)
972 && e.getCause() instanceof InterruptedException) {
973 interrupted = true;
974 continue;
975 }
976 logger.warn("Message action failed.", e);
977 }
978 }
979 if (interrupted) {
980 Thread.currentThread().interrupt();
981 }
982 }
983
984 public boolean isContactBlocked(final RecipientIdentifier.Single recipient) {
985 final RecipientId recipientId;
986 try {
987 recipientId = resolveRecipient(recipient);
988 } catch (UnregisteredUserException e) {
989 return false;
990 }
991 return contactHelper.isContactBlocked(recipientId);
992 }
993
994 public File getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId) {
995 return attachmentHelper.getAttachmentFile(attachmentId);
996 }
997
998 public void sendContacts() throws IOException {
999 syncHelper.sendContacts();
1000 }
1001
1002 public List<Pair<RecipientId, Contact>> getContacts() {
1003 return account.getContactStore().getContacts();
1004 }
1005
1006 public String getContactOrProfileName(RecipientIdentifier.Single recipientIdentifier) {
1007 final RecipientId recipientId;
1008 try {
1009 recipientId = resolveRecipient(recipientIdentifier);
1010 } catch (UnregisteredUserException e) {
1011 return null;
1012 }
1013
1014 final var contact = account.getContactStore().getContact(recipientId);
1015 if (contact != null && !Util.isEmpty(contact.getName())) {
1016 return contact.getName();
1017 }
1018
1019 final var profile = getRecipientProfile(recipientId);
1020 if (profile != null) {
1021 return profile.getDisplayName();
1022 }
1023
1024 return null;
1025 }
1026
1027 public GroupInfo getGroup(GroupId groupId) {
1028 return groupHelper.getGroup(groupId);
1029 }
1030
1031 public List<IdentityInfo> getIdentities() {
1032 return account.getIdentityKeyStore().getIdentities();
1033 }
1034
1035 public List<IdentityInfo> getIdentities(RecipientIdentifier.Single recipient) {
1036 IdentityInfo identity;
1037 try {
1038 identity = account.getIdentityKeyStore().getIdentity(resolveRecipient(recipient));
1039 } catch (UnregisteredUserException e) {
1040 identity = null;
1041 }
1042 return identity == null ? List.of() : List.of(identity);
1043 }
1044
1045 /**
1046 * Trust this the identity with this fingerprint
1047 *
1048 * @param recipient username of the identity
1049 * @param fingerprint Fingerprint
1050 */
1051 public boolean trustIdentityVerified(RecipientIdentifier.Single recipient, byte[] fingerprint) {
1052 RecipientId recipientId;
1053 try {
1054 recipientId = resolveRecipient(recipient);
1055 } catch (UnregisteredUserException e) {
1056 return false;
1057 }
1058 return trustIdentity(recipientId,
1059 identityKey -> Arrays.equals(identityKey.serialize(), fingerprint),
1060 TrustLevel.TRUSTED_VERIFIED);
1061 }
1062
1063 /**
1064 * Trust this the identity with this safety number
1065 *
1066 * @param recipient username of the identity
1067 * @param safetyNumber Safety number
1068 */
1069 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier.Single recipient, String safetyNumber) {
1070 RecipientId recipientId;
1071 try {
1072 recipientId = resolveRecipient(recipient);
1073 } catch (UnregisteredUserException e) {
1074 return false;
1075 }
1076 var address = resolveSignalServiceAddress(recipientId);
1077 return trustIdentity(recipientId,
1078 identityKey -> safetyNumber.equals(computeSafetyNumber(address, identityKey)),
1079 TrustLevel.TRUSTED_VERIFIED);
1080 }
1081
1082 /**
1083 * Trust this the identity with this scannable safety number
1084 *
1085 * @param recipient username of the identity
1086 * @param safetyNumber Scannable safety number
1087 */
1088 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier.Single recipient, byte[] safetyNumber) {
1089 RecipientId recipientId;
1090 try {
1091 recipientId = resolveRecipient(recipient);
1092 } catch (UnregisteredUserException e) {
1093 return false;
1094 }
1095 var address = resolveSignalServiceAddress(recipientId);
1096 return trustIdentity(recipientId, identityKey -> {
1097 final var fingerprint = computeSafetyNumberFingerprint(address, identityKey);
1098 try {
1099 return fingerprint != null && fingerprint.getScannableFingerprint().compareTo(safetyNumber);
1100 } catch (FingerprintVersionMismatchException | FingerprintParsingException e) {
1101 return false;
1102 }
1103 }, TrustLevel.TRUSTED_VERIFIED);
1104 }
1105
1106 /**
1107 * Trust all keys of this identity without verification
1108 *
1109 * @param recipient username of the identity
1110 */
1111 public boolean trustIdentityAllKeys(RecipientIdentifier.Single recipient) {
1112 RecipientId recipientId;
1113 try {
1114 recipientId = resolveRecipient(recipient);
1115 } catch (UnregisteredUserException e) {
1116 return false;
1117 }
1118 return trustIdentity(recipientId, identityKey -> true, TrustLevel.TRUSTED_UNVERIFIED);
1119 }
1120
1121 private boolean trustIdentity(
1122 RecipientId recipientId, Function<IdentityKey, Boolean> verifier, TrustLevel trustLevel
1123 ) {
1124 var identity = account.getIdentityKeyStore().getIdentity(recipientId);
1125 if (identity == null) {
1126 return false;
1127 }
1128
1129 if (!verifier.apply(identity.getIdentityKey())) {
1130 return false;
1131 }
1132
1133 account.getIdentityKeyStore().setIdentityTrustLevel(recipientId, identity.getIdentityKey(), trustLevel);
1134 try {
1135 var address = resolveSignalServiceAddress(recipientId);
1136 syncHelper.sendVerifiedMessage(address, identity.getIdentityKey(), trustLevel);
1137 } catch (IOException e) {
1138 logger.warn("Failed to send verification sync message: {}", e.getMessage());
1139 }
1140
1141 return true;
1142 }
1143
1144 private void handleIdentityFailure(
1145 final RecipientId recipientId, final SendMessageResult.IdentityFailure identityFailure
1146 ) {
1147 final var identityKey = identityFailure.getIdentityKey();
1148 if (identityKey != null) {
1149 final var newIdentity = account.getIdentityKeyStore().saveIdentity(recipientId, identityKey, new Date());
1150 if (newIdentity) {
1151 account.getSessionStore().archiveSessions(recipientId);
1152 }
1153 } else {
1154 // Retrieve profile to get the current identity key from the server
1155 profileHelper.refreshRecipientProfile(recipientId);
1156 }
1157 }
1158
1159 public String computeSafetyNumber(SignalServiceAddress theirAddress, IdentityKey theirIdentityKey) {
1160 final Fingerprint fingerprint = computeSafetyNumberFingerprint(theirAddress, theirIdentityKey);
1161 return fingerprint == null ? null : fingerprint.getDisplayableFingerprint().getDisplayText();
1162 }
1163
1164 public byte[] computeSafetyNumberForScanning(SignalServiceAddress theirAddress, IdentityKey theirIdentityKey) {
1165 final Fingerprint fingerprint = computeSafetyNumberFingerprint(theirAddress, theirIdentityKey);
1166 return fingerprint == null ? null : fingerprint.getScannableFingerprint().getSerialized();
1167 }
1168
1169 private Fingerprint computeSafetyNumberFingerprint(
1170 final SignalServiceAddress theirAddress, final IdentityKey theirIdentityKey
1171 ) {
1172 return Utils.computeSafetyNumber(capabilities.isUuid(),
1173 account.getSelfAddress(),
1174 getIdentityKeyPair().getPublicKey(),
1175 theirAddress,
1176 theirIdentityKey);
1177 }
1178
1179 public SignalServiceAddress resolveSignalServiceAddress(SignalServiceAddress address) {
1180 return resolveSignalServiceAddress(resolveRecipient(address));
1181 }
1182
1183 public SignalServiceAddress resolveSignalServiceAddress(UUID uuid) {
1184 return resolveSignalServiceAddress(account.getRecipientStore().resolveRecipient(uuid));
1185 }
1186
1187 public SignalServiceAddress resolveSignalServiceAddress(RecipientId recipientId) {
1188 final var address = account.getRecipientStore().resolveRecipientAddress(recipientId);
1189 if (address.getUuid().isPresent()) {
1190 return address.toSignalServiceAddress();
1191 }
1192
1193 // Address in recipient store doesn't have a uuid, this shouldn't happen
1194 // Try to retrieve the uuid from the server
1195 final var number = address.getNumber().get();
1196 try {
1197 return resolveSignalServiceAddress(getRegisteredUser(number));
1198 } catch (IOException e) {
1199 logger.warn("Failed to get uuid for e164 number: {}", number, e);
1200 // Return SignalServiceAddress with unknown UUID
1201 return address.toSignalServiceAddress();
1202 }
1203 }
1204
1205 private Set<RecipientId> resolveRecipients(Collection<RecipientIdentifier.Single> recipients) throws UnregisteredUserException {
1206 final var recipientIds = new HashSet<RecipientId>(recipients.size());
1207 for (var number : recipients) {
1208 final var recipientId = resolveRecipient(number);
1209 recipientIds.add(recipientId);
1210 }
1211 return recipientIds;
1212 }
1213
1214 private RecipientId resolveRecipient(final RecipientIdentifier.Single recipient) throws UnregisteredUserException {
1215 if (recipient instanceof RecipientIdentifier.Uuid) {
1216 return account.getRecipientStore().resolveRecipient(((RecipientIdentifier.Uuid) recipient).uuid);
1217 } else {
1218 final var number = ((RecipientIdentifier.Number) recipient).number;
1219 return account.getRecipientStore().resolveRecipient(number, () -> {
1220 try {
1221 return getRegisteredUser(number);
1222 } catch (IOException e) {
1223 return null;
1224 }
1225 });
1226 }
1227 }
1228
1229 private RecipientId resolveRecipient(SignalServiceAddress address) {
1230 return account.getRecipientStore().resolveRecipient(address);
1231 }
1232
1233 private RecipientId resolveRecipientTrusted(SignalServiceAddress address) {
1234 return account.getRecipientStore().resolveRecipientTrusted(address);
1235 }
1236
1237 @Override
1238 public void close() throws IOException {
1239 close(true);
1240 }
1241
1242 private void close(boolean closeAccount) throws IOException {
1243 executor.shutdown();
1244
1245 dependencies.getSignalWebSocket().disconnect();
1246
1247 if (closeAccount && account != null) {
1248 account.close();
1249 }
1250 account = null;
1251 }
1252
1253 public interface ReceiveMessageHandler {
1254
1255 void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent decryptedContent, Throwable e);
1256 }
1257 }