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