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