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