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