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