]> nmode's Git Repositories - signal-cli/blob - lib/src/main/java/org/asamk/signal/manager/ManagerImpl.java
Add missing null check
[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 /**
348 * @param givenName if null, the previous givenName will be kept
349 * @param familyName if null, the previous familyName will be kept
350 * @param about if null, the previous about text will be kept
351 * @param aboutEmoji if null, the previous about emoji will be kept
352 * @param avatar if avatar is null the image from the local avatar store is used (if present),
353 */
354 @Override
355 public void setProfile(
356 String givenName, final String familyName, String about, String aboutEmoji, Optional<File> avatar
357 ) throws IOException {
358 profileHelper.setProfile(givenName, familyName, about, aboutEmoji, avatar);
359 syncHelper.sendSyncFetchProfileMessage();
360 }
361
362 @Override
363 public void unregister() throws IOException {
364 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
365 // If this is the master device, other users can't send messages to this number anymore.
366 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
367 dependencies.getAccountManager().setGcmId(Optional.absent());
368
369 account.setRegistered(false);
370 }
371
372 @Override
373 public void deleteAccount() throws IOException {
374 try {
375 pinHelper.removeRegistrationLockPin();
376 } catch (UnauthenticatedResponseException e) {
377 logger.warn("Failed to remove registration lock pin");
378 }
379 account.setRegistrationLockPin(null, null);
380
381 dependencies.getAccountManager().deleteAccount();
382
383 account.setRegistered(false);
384 }
385
386 @Override
387 public void submitRateLimitRecaptchaChallenge(String challenge, String captcha) throws IOException {
388 dependencies.getAccountManager().submitRateLimitRecaptchaChallenge(challenge, captcha);
389 }
390
391 @Override
392 public List<Device> getLinkedDevices() throws IOException {
393 var devices = dependencies.getAccountManager().getDevices();
394 account.setMultiDevice(devices.size() > 1);
395 var identityKey = account.getIdentityKeyPair().getPrivateKey();
396 return devices.stream().map(d -> {
397 String deviceName = d.getName();
398 if (deviceName != null) {
399 try {
400 deviceName = DeviceNameUtil.decryptDeviceName(deviceName, identityKey);
401 } catch (IOException e) {
402 logger.debug("Failed to decrypt device name, maybe plain text?", e);
403 }
404 }
405 return new Device(d.getId(),
406 deviceName,
407 d.getCreated(),
408 d.getLastSeen(),
409 d.getId() == account.getDeviceId());
410 }).collect(Collectors.toList());
411 }
412
413 @Override
414 public void removeLinkedDevices(long deviceId) throws IOException {
415 dependencies.getAccountManager().removeDevice(deviceId);
416 var devices = dependencies.getAccountManager().getDevices();
417 account.setMultiDevice(devices.size() > 1);
418 }
419
420 @Override
421 public void addDeviceLink(URI linkUri) throws IOException, InvalidKeyException {
422 var info = DeviceLinkInfo.parseDeviceLinkUri(linkUri);
423
424 addDevice(info.deviceIdentifier, info.deviceKey);
425 }
426
427 private void addDevice(String deviceIdentifier, ECPublicKey deviceKey) throws IOException, InvalidKeyException {
428 var identityKeyPair = account.getIdentityKeyPair();
429 var verificationCode = dependencies.getAccountManager().getNewDeviceVerificationCode();
430
431 dependencies.getAccountManager()
432 .addDevice(deviceIdentifier,
433 deviceKey,
434 identityKeyPair,
435 Optional.of(account.getProfileKey().serialize()),
436 verificationCode);
437 account.setMultiDevice(true);
438 }
439
440 @Override
441 public void setRegistrationLockPin(Optional<String> pin) throws IOException, UnauthenticatedResponseException {
442 if (!account.isMasterDevice()) {
443 throw new RuntimeException("Only master device can set a PIN");
444 }
445 if (pin.isPresent()) {
446 final var masterKey = account.getPinMasterKey() != null
447 ? account.getPinMasterKey()
448 : KeyUtils.createMasterKey();
449
450 pinHelper.setRegistrationLockPin(pin.get(), masterKey);
451
452 account.setRegistrationLockPin(pin.get(), masterKey);
453 } else {
454 // Remove KBS Pin
455 pinHelper.removeRegistrationLockPin();
456
457 account.setRegistrationLockPin(null, null);
458 }
459 }
460
461 void refreshPreKeys() throws IOException {
462 preKeyHelper.refreshPreKeys();
463 }
464
465 @Override
466 public Profile getRecipientProfile(RecipientIdentifier.Single recipient) throws UnregisteredUserException {
467 return profileHelper.getRecipientProfile(resolveRecipient(recipient));
468 }
469
470 private Profile getRecipientProfile(RecipientId recipientId) {
471 return profileHelper.getRecipientProfile(recipientId);
472 }
473
474 @Override
475 public List<Group> getGroups() {
476 return account.getGroupStore().getGroups().stream().map(this::toGroup).collect(Collectors.toList());
477 }
478
479 private Group toGroup(final GroupInfo groupInfo) {
480 if (groupInfo == null) {
481 return null;
482 }
483
484 return new Group(groupInfo.getGroupId(),
485 groupInfo.getTitle(),
486 groupInfo.getDescription(),
487 groupInfo.getGroupInviteLink(),
488 groupInfo.getMembers()
489 .stream()
490 .map(account.getRecipientStore()::resolveRecipientAddress)
491 .collect(Collectors.toSet()),
492 groupInfo.getPendingMembers()
493 .stream()
494 .map(account.getRecipientStore()::resolveRecipientAddress)
495 .collect(Collectors.toSet()),
496 groupInfo.getRequestingMembers()
497 .stream()
498 .map(account.getRecipientStore()::resolveRecipientAddress)
499 .collect(Collectors.toSet()),
500 groupInfo.getAdminMembers()
501 .stream()
502 .map(account.getRecipientStore()::resolveRecipientAddress)
503 .collect(Collectors.toSet()),
504 groupInfo.isBlocked(),
505 groupInfo.getMessageExpirationTimer(),
506 groupInfo.getPermissionAddMember(),
507 groupInfo.getPermissionEditDetails(),
508 groupInfo.getPermissionSendMessage(),
509 groupInfo.isMember(account.getSelfRecipientId()),
510 groupInfo.isAdmin(account.getSelfRecipientId()));
511 }
512
513 @Override
514 public SendGroupMessageResults quitGroup(
515 GroupId groupId, Set<RecipientIdentifier.Single> groupAdmins
516 ) throws GroupNotFoundException, IOException, NotAGroupMemberException, LastGroupAdminException {
517 final var newAdmins = resolveRecipients(groupAdmins);
518 return groupHelper.quitGroup(groupId, newAdmins);
519 }
520
521 @Override
522 public void deleteGroup(GroupId groupId) throws IOException {
523 groupHelper.deleteGroup(groupId);
524 }
525
526 @Override
527 public Pair<GroupId, SendGroupMessageResults> createGroup(
528 String name, Set<RecipientIdentifier.Single> members, File avatarFile
529 ) throws IOException, AttachmentInvalidException {
530 return groupHelper.createGroup(name, members == null ? null : resolveRecipients(members), avatarFile);
531 }
532
533 @Override
534 public SendGroupMessageResults updateGroup(
535 final GroupId groupId, final UpdateGroup updateGroup
536 ) throws IOException, GroupNotFoundException, AttachmentInvalidException, NotAGroupMemberException, GroupSendingNotAllowedException {
537 return groupHelper.updateGroup(groupId,
538 updateGroup.getName(),
539 updateGroup.getDescription(),
540 updateGroup.getMembers() == null ? null : resolveRecipients(updateGroup.getMembers()),
541 updateGroup.getRemoveMembers() == null ? null : resolveRecipients(updateGroup.getRemoveMembers()),
542 updateGroup.getAdmins() == null ? null : resolveRecipients(updateGroup.getAdmins()),
543 updateGroup.getRemoveAdmins() == null ? null : resolveRecipients(updateGroup.getRemoveAdmins()),
544 updateGroup.isResetGroupLink(),
545 updateGroup.getGroupLinkState(),
546 updateGroup.getAddMemberPermission(),
547 updateGroup.getEditDetailsPermission(),
548 updateGroup.getAvatarFile(),
549 updateGroup.getExpirationTimer(),
550 updateGroup.getIsAnnouncementGroup());
551 }
552
553 @Override
554 public Pair<GroupId, SendGroupMessageResults> joinGroup(
555 GroupInviteLinkUrl inviteLinkUrl
556 ) throws IOException, GroupLinkNotActiveException {
557 return groupHelper.joinGroup(inviteLinkUrl);
558 }
559
560 private SendMessageResults sendMessage(
561 SignalServiceDataMessage.Builder messageBuilder, Set<RecipientIdentifier> recipients
562 ) throws IOException, NotAGroupMemberException, GroupNotFoundException, GroupSendingNotAllowedException {
563 var results = new HashMap<RecipientIdentifier, List<SendMessageResult>>();
564 long timestamp = System.currentTimeMillis();
565 messageBuilder.withTimestamp(timestamp);
566 for (final var recipient : recipients) {
567 if (recipient instanceof RecipientIdentifier.Single) {
568 final var recipientId = resolveRecipient((RecipientIdentifier.Single) recipient);
569 final var result = sendHelper.sendMessage(messageBuilder, recipientId);
570 results.put(recipient, List.of(result));
571 } else if (recipient instanceof RecipientIdentifier.NoteToSelf) {
572 final var result = sendHelper.sendSelfMessage(messageBuilder);
573 results.put(recipient, List.of(result));
574 } else if (recipient instanceof RecipientIdentifier.Group) {
575 final var groupId = ((RecipientIdentifier.Group) recipient).groupId;
576 final var result = sendHelper.sendAsGroupMessage(messageBuilder, groupId);
577 results.put(recipient, result);
578 }
579 }
580 return new SendMessageResults(timestamp, results);
581 }
582
583 private void sendTypingMessage(
584 SignalServiceTypingMessage.Action action, Set<RecipientIdentifier> recipients
585 ) throws IOException, UntrustedIdentityException, NotAGroupMemberException, GroupNotFoundException, GroupSendingNotAllowedException {
586 final var timestamp = System.currentTimeMillis();
587 for (var recipient : recipients) {
588 if (recipient instanceof RecipientIdentifier.Single) {
589 final var message = new SignalServiceTypingMessage(action, timestamp, Optional.absent());
590 final var recipientId = resolveRecipient((RecipientIdentifier.Single) recipient);
591 sendHelper.sendTypingMessage(message, recipientId);
592 } else if (recipient instanceof RecipientIdentifier.Group) {
593 final var groupId = ((RecipientIdentifier.Group) recipient).groupId;
594 final var message = new SignalServiceTypingMessage(action, timestamp, Optional.of(groupId.serialize()));
595 sendHelper.sendGroupTypingMessage(message, groupId);
596 }
597 }
598 }
599
600 @Override
601 public void sendTypingMessage(
602 TypingAction action, Set<RecipientIdentifier> recipients
603 ) throws IOException, UntrustedIdentityException, NotAGroupMemberException, GroupNotFoundException, GroupSendingNotAllowedException {
604 sendTypingMessage(action.toSignalService(), recipients);
605 }
606
607 @Override
608 public void sendReadReceipt(
609 RecipientIdentifier.Single sender, List<Long> messageIds
610 ) throws IOException, UntrustedIdentityException {
611 var receiptMessage = new SignalServiceReceiptMessage(SignalServiceReceiptMessage.Type.READ,
612 messageIds,
613 System.currentTimeMillis());
614
615 sendHelper.sendReceiptMessage(receiptMessage, resolveRecipient(sender));
616 }
617
618 @Override
619 public void sendViewedReceipt(
620 RecipientIdentifier.Single sender, List<Long> messageIds
621 ) throws IOException, UntrustedIdentityException {
622 var receiptMessage = new SignalServiceReceiptMessage(SignalServiceReceiptMessage.Type.VIEWED,
623 messageIds,
624 System.currentTimeMillis());
625
626 sendHelper.sendReceiptMessage(receiptMessage, resolveRecipient(sender));
627 }
628
629 @Override
630 public SendMessageResults sendMessage(
631 Message message, Set<RecipientIdentifier> recipients
632 ) throws IOException, AttachmentInvalidException, NotAGroupMemberException, GroupNotFoundException, GroupSendingNotAllowedException {
633 final var messageBuilder = SignalServiceDataMessage.newBuilder();
634 applyMessage(messageBuilder, message);
635 return sendMessage(messageBuilder, recipients);
636 }
637
638 private void applyMessage(
639 final SignalServiceDataMessage.Builder messageBuilder, final Message message
640 ) throws AttachmentInvalidException, IOException {
641 messageBuilder.withBody(message.getMessageText());
642 final var attachments = message.getAttachments();
643 if (attachments != null) {
644 messageBuilder.withAttachments(attachmentHelper.uploadAttachments(attachments));
645 }
646 }
647
648 @Override
649 public SendMessageResults sendRemoteDeleteMessage(
650 long targetSentTimestamp, Set<RecipientIdentifier> recipients
651 ) throws IOException, NotAGroupMemberException, GroupNotFoundException, GroupSendingNotAllowedException {
652 var delete = new SignalServiceDataMessage.RemoteDelete(targetSentTimestamp);
653 final var messageBuilder = SignalServiceDataMessage.newBuilder().withRemoteDelete(delete);
654 return sendMessage(messageBuilder, recipients);
655 }
656
657 @Override
658 public SendMessageResults sendMessageReaction(
659 String emoji,
660 boolean remove,
661 RecipientIdentifier.Single targetAuthor,
662 long targetSentTimestamp,
663 Set<RecipientIdentifier> recipients
664 ) throws IOException, NotAGroupMemberException, GroupNotFoundException, GroupSendingNotAllowedException {
665 var targetAuthorRecipientId = resolveRecipient(targetAuthor);
666 var reaction = new SignalServiceDataMessage.Reaction(emoji,
667 remove,
668 resolveSignalServiceAddress(targetAuthorRecipientId),
669 targetSentTimestamp);
670 final var messageBuilder = SignalServiceDataMessage.newBuilder().withReaction(reaction);
671 return sendMessage(messageBuilder, recipients);
672 }
673
674 @Override
675 public SendMessageResults sendEndSessionMessage(Set<RecipientIdentifier.Single> recipients) throws IOException {
676 var messageBuilder = SignalServiceDataMessage.newBuilder().asEndSessionMessage();
677
678 try {
679 return sendMessage(messageBuilder,
680 recipients.stream().map(RecipientIdentifier.class::cast).collect(Collectors.toSet()));
681 } catch (GroupNotFoundException | NotAGroupMemberException | GroupSendingNotAllowedException e) {
682 throw new AssertionError(e);
683 } finally {
684 for (var recipient : recipients) {
685 final var recipientId = resolveRecipient(recipient);
686 account.getSessionStore().deleteAllSessions(recipientId);
687 }
688 }
689 }
690
691 @Override
692 public void setContactName(
693 RecipientIdentifier.Single recipient, String name
694 ) throws NotMasterDeviceException, UnregisteredUserException {
695 if (!account.isMasterDevice()) {
696 throw new NotMasterDeviceException();
697 }
698 contactHelper.setContactName(resolveRecipient(recipient), name);
699 }
700
701 @Override
702 public void setContactBlocked(
703 RecipientIdentifier.Single recipient, boolean blocked
704 ) throws NotMasterDeviceException, IOException {
705 if (!account.isMasterDevice()) {
706 throw new NotMasterDeviceException();
707 }
708 contactHelper.setContactBlocked(resolveRecipient(recipient), blocked);
709 // TODO cycle our profile key
710 syncHelper.sendBlockedList();
711 }
712
713 @Override
714 public void setGroupBlocked(
715 final GroupId groupId, final boolean blocked
716 ) throws GroupNotFoundException, IOException, NotMasterDeviceException {
717 if (!account.isMasterDevice()) {
718 throw new NotMasterDeviceException();
719 }
720 groupHelper.setGroupBlocked(groupId, blocked);
721 // TODO cycle our profile key
722 syncHelper.sendBlockedList();
723 }
724
725 /**
726 * Change the expiration timer for a contact
727 */
728 @Override
729 public void setExpirationTimer(
730 RecipientIdentifier.Single recipient, int messageExpirationTimer
731 ) throws IOException {
732 var recipientId = resolveRecipient(recipient);
733 contactHelper.setExpirationTimer(recipientId, messageExpirationTimer);
734 final var messageBuilder = SignalServiceDataMessage.newBuilder().asExpirationUpdate();
735 try {
736 sendMessage(messageBuilder, Set.of(recipient));
737 } catch (NotAGroupMemberException | GroupNotFoundException | GroupSendingNotAllowedException e) {
738 throw new AssertionError(e);
739 }
740 }
741
742 /**
743 * Upload the sticker pack from path.
744 *
745 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
746 * @return if successful, returns the URL to install the sticker pack in the signal app
747 */
748 @Override
749 public URI uploadStickerPack(File path) throws IOException, StickerPackInvalidException {
750 var manifest = StickerUtils.getSignalServiceStickerManifestUpload(path);
751
752 var messageSender = dependencies.getMessageSender();
753
754 var packKey = KeyUtils.createStickerUploadKey();
755 var packIdString = messageSender.uploadStickerManifest(manifest, packKey);
756 var packId = StickerPackId.deserialize(Hex.fromStringCondensed(packIdString));
757
758 var sticker = new Sticker(packId, packKey);
759 account.getStickerStore().updateSticker(sticker);
760
761 try {
762 return new URI("https",
763 "signal.art",
764 "/addstickers/",
765 "pack_id="
766 + URLEncoder.encode(Hex.toStringCondensed(packId.serialize()), StandardCharsets.UTF_8)
767 + "&pack_key="
768 + URLEncoder.encode(Hex.toStringCondensed(packKey), StandardCharsets.UTF_8));
769 } catch (URISyntaxException e) {
770 throw new AssertionError(e);
771 }
772 }
773
774 @Override
775 public void requestAllSyncData() throws IOException {
776 syncHelper.requestAllSyncData();
777 retrieveRemoteStorage();
778 }
779
780 void retrieveRemoteStorage() throws IOException {
781 if (account.getStorageKey() != null) {
782 storageHelper.readDataFromStorage();
783 }
784 }
785
786 private RecipientId refreshRegisteredUser(RecipientId recipientId) throws IOException {
787 final var address = resolveSignalServiceAddress(recipientId);
788 if (!address.getNumber().isPresent()) {
789 return recipientId;
790 }
791 final var number = address.getNumber().get();
792 final var uuid = getRegisteredUser(number);
793 return resolveRecipientTrusted(new SignalServiceAddress(uuid, number));
794 }
795
796 private UUID getRegisteredUser(final String number) throws IOException {
797 final Map<String, UUID> uuidMap;
798 try {
799 uuidMap = getRegisteredUsers(Set.of(number));
800 } catch (NumberFormatException e) {
801 throw new UnregisteredUserException(number, e);
802 }
803 final var uuid = uuidMap.get(number);
804 if (uuid == null) {
805 throw new UnregisteredUserException(number, null);
806 }
807 return uuid;
808 }
809
810 private Map<String, UUID> getRegisteredUsers(final Set<String> numbers) throws IOException {
811 final Map<String, UUID> registeredUsers;
812 try {
813 registeredUsers = dependencies.getAccountManager()
814 .getRegisteredUsers(ServiceConfig.getIasKeyStore(),
815 numbers,
816 serviceEnvironmentConfig.getCdsMrenclave());
817 } catch (Quote.InvalidQuoteFormatException | UnauthenticatedQuoteException | SignatureException | UnauthenticatedResponseException | InvalidKeyException e) {
818 throw new IOException(e);
819 }
820
821 // Store numbers as recipients so we have the number/uuid association
822 registeredUsers.forEach((number, uuid) -> resolveRecipientTrusted(new SignalServiceAddress(uuid, number)));
823
824 return registeredUsers;
825 }
826
827 private void retryFailedReceivedMessages(ReceiveMessageHandler handler, boolean ignoreAttachments) {
828 Set<HandleAction> queuedActions = new HashSet<>();
829 for (var cachedMessage : account.getMessageCache().getCachedMessages()) {
830 var actions = retryFailedReceivedMessage(handler, ignoreAttachments, cachedMessage);
831 if (actions != null) {
832 queuedActions.addAll(actions);
833 }
834 }
835 handleQueuedActions(queuedActions);
836 }
837
838 private List<HandleAction> retryFailedReceivedMessage(
839 final ReceiveMessageHandler handler, final boolean ignoreAttachments, final CachedMessage cachedMessage
840 ) {
841 var envelope = cachedMessage.loadEnvelope();
842 if (envelope == null) {
843 cachedMessage.delete();
844 return null;
845 }
846
847 final var result = incomingMessageHandler.handleRetryEnvelope(envelope, ignoreAttachments, handler);
848 final var actions = result.first();
849 final var exception = result.second();
850
851 if (exception instanceof UntrustedIdentityException) {
852 if (System.currentTimeMillis() - envelope.getServerDeliveredTimestamp() > 1000L * 60 * 60 * 24 * 30) {
853 // Envelope is more than a month old, cleaning up.
854 cachedMessage.delete();
855 return null;
856 }
857 if (!envelope.hasSourceUuid()) {
858 final var identifier = ((UntrustedIdentityException) exception).getSender();
859 final var recipientId = account.getRecipientStore().resolveRecipient(identifier);
860 try {
861 account.getMessageCache().replaceSender(cachedMessage, recipientId);
862 } catch (IOException ioException) {
863 logger.warn("Failed to move cached message to recipient folder: {}", ioException.getMessage());
864 }
865 }
866 return null;
867 }
868
869 // If successful and for all other errors that are not recoverable, delete the cached message
870 cachedMessage.delete();
871 return actions;
872 }
873
874 @Override
875 public void receiveMessages(
876 long timeout,
877 TimeUnit unit,
878 boolean returnOnTimeout,
879 boolean ignoreAttachments,
880 ReceiveMessageHandler handler
881 ) throws IOException {
882 retryFailedReceivedMessages(handler, ignoreAttachments);
883
884 Set<HandleAction> queuedActions = new HashSet<>();
885
886 final var signalWebSocket = dependencies.getSignalWebSocket();
887 signalWebSocket.connect();
888
889 hasCaughtUpWithOldMessages = false;
890 var backOffCounter = 0;
891 final var MAX_BACKOFF_COUNTER = 9;
892
893 while (!Thread.interrupted()) {
894 SignalServiceEnvelope envelope;
895 final CachedMessage[] cachedMessage = {null};
896 account.setLastReceiveTimestamp(System.currentTimeMillis());
897 logger.debug("Checking for new message from server");
898 try {
899 var result = signalWebSocket.readOrEmpty(unit.toMillis(timeout), envelope1 -> {
900 final var recipientId = envelope1.hasSourceUuid()
901 ? resolveRecipient(envelope1.getSourceAddress())
902 : null;
903 // store message on disk, before acknowledging receipt to the server
904 cachedMessage[0] = account.getMessageCache().cacheMessage(envelope1, recipientId);
905 });
906 backOffCounter = 0;
907
908 if (result.isPresent()) {
909 envelope = result.get();
910 logger.debug("New message received from server");
911 } else {
912 logger.debug("Received indicator that server queue is empty");
913 handleQueuedActions(queuedActions);
914 queuedActions.clear();
915
916 hasCaughtUpWithOldMessages = true;
917 synchronized (this) {
918 this.notifyAll();
919 }
920
921 // Continue to wait another timeout for new messages
922 continue;
923 }
924 } catch (AssertionError e) {
925 if (e.getCause() instanceof InterruptedException) {
926 Thread.currentThread().interrupt();
927 break;
928 } else {
929 throw e;
930 }
931 } catch (IOException e) {
932 logger.debug("Pipe unexpectedly unavailable: {}", e.getMessage());
933 if (e instanceof WebSocketUnavailableException || "Connection closed!".equals(e.getMessage())) {
934 final var sleepMilliseconds = 100 * (long) Math.pow(2, backOffCounter);
935 backOffCounter = Math.min(backOffCounter + 1, MAX_BACKOFF_COUNTER);
936 logger.warn("Connection closed unexpectedly, reconnecting in {} ms", sleepMilliseconds);
937 try {
938 Thread.sleep(sleepMilliseconds);
939 } catch (InterruptedException interruptedException) {
940 return;
941 }
942 hasCaughtUpWithOldMessages = false;
943 signalWebSocket.connect();
944 continue;
945 }
946 throw e;
947 } catch (TimeoutException e) {
948 backOffCounter = 0;
949 if (returnOnTimeout) return;
950 continue;
951 }
952
953 final var result = incomingMessageHandler.handleEnvelope(envelope, ignoreAttachments, handler);
954 queuedActions.addAll(result.first());
955 final var exception = result.second();
956
957 if (hasCaughtUpWithOldMessages) {
958 handleQueuedActions(queuedActions);
959 queuedActions.clear();
960 }
961 if (cachedMessage[0] != null) {
962 if (exception instanceof UntrustedIdentityException) {
963 logger.debug("Keeping message with untrusted identity in message cache");
964 final var address = ((UntrustedIdentityException) exception).getSender();
965 final var recipientId = resolveRecipient(address);
966 if (!envelope.hasSourceUuid()) {
967 try {
968 cachedMessage[0] = account.getMessageCache().replaceSender(cachedMessage[0], recipientId);
969 } catch (IOException ioException) {
970 logger.warn("Failed to move cached message to recipient folder: {}",
971 ioException.getMessage());
972 }
973 }
974 } else {
975 cachedMessage[0].delete();
976 }
977 }
978 }
979 handleQueuedActions(queuedActions);
980 queuedActions.clear();
981 }
982
983 @Override
984 public boolean hasCaughtUpWithOldMessages() {
985 return hasCaughtUpWithOldMessages;
986 }
987
988 private void handleQueuedActions(final Collection<HandleAction> queuedActions) {
989 logger.debug("Handling message actions");
990 var interrupted = false;
991 for (var action : queuedActions) {
992 try {
993 action.execute(context);
994 } catch (Throwable e) {
995 if ((e instanceof AssertionError || e instanceof RuntimeException)
996 && e.getCause() instanceof InterruptedException) {
997 interrupted = true;
998 continue;
999 }
1000 logger.warn("Message action failed.", e);
1001 }
1002 }
1003 if (interrupted) {
1004 Thread.currentThread().interrupt();
1005 }
1006 }
1007
1008 @Override
1009 public boolean isContactBlocked(final RecipientIdentifier.Single recipient) {
1010 final RecipientId recipientId;
1011 try {
1012 recipientId = resolveRecipient(recipient);
1013 } catch (UnregisteredUserException e) {
1014 return false;
1015 }
1016 return contactHelper.isContactBlocked(recipientId);
1017 }
1018
1019 @Override
1020 public File getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId) {
1021 return attachmentHelper.getAttachmentFile(attachmentId);
1022 }
1023
1024 @Override
1025 public void sendContacts() throws IOException {
1026 syncHelper.sendContacts();
1027 }
1028
1029 @Override
1030 public List<Pair<RecipientAddress, Contact>> getContacts() {
1031 return account.getContactStore()
1032 .getContacts()
1033 .stream()
1034 .map(p -> new Pair<>(account.getRecipientStore().resolveRecipientAddress(p.first()), p.second()))
1035 .collect(Collectors.toList());
1036 }
1037
1038 @Override
1039 public String getContactOrProfileName(RecipientIdentifier.Single recipient) {
1040 final RecipientId recipientId;
1041 try {
1042 recipientId = resolveRecipient(recipient);
1043 } catch (UnregisteredUserException e) {
1044 return null;
1045 }
1046
1047 final var contact = account.getContactStore().getContact(recipientId);
1048 if (contact != null && !Util.isEmpty(contact.getName())) {
1049 return contact.getName();
1050 }
1051
1052 final var profile = getRecipientProfile(recipientId);
1053 if (profile != null) {
1054 return profile.getDisplayName();
1055 }
1056
1057 return null;
1058 }
1059
1060 @Override
1061 public Group getGroup(GroupId groupId) {
1062 return toGroup(groupHelper.getGroup(groupId));
1063 }
1064
1065 private GroupInfo getGroupInfo(GroupId groupId) {
1066 return groupHelper.getGroup(groupId);
1067 }
1068
1069 @Override
1070 public List<Identity> getIdentities() {
1071 return account.getIdentityKeyStore()
1072 .getIdentities()
1073 .stream()
1074 .map(this::toIdentity)
1075 .collect(Collectors.toList());
1076 }
1077
1078 private Identity toIdentity(final IdentityInfo identityInfo) {
1079 if (identityInfo == null) {
1080 return null;
1081 }
1082
1083 final var address = account.getRecipientStore().resolveRecipientAddress(identityInfo.getRecipientId());
1084 final var scannableFingerprint = identityHelper.computeSafetyNumberForScanning(identityInfo.getRecipientId(),
1085 identityInfo.getIdentityKey());
1086 return new Identity(address,
1087 identityInfo.getIdentityKey(),
1088 identityHelper.computeSafetyNumber(identityInfo.getRecipientId(), identityInfo.getIdentityKey()),
1089 scannableFingerprint == null ? null : scannableFingerprint.getSerialized(),
1090 identityInfo.getTrustLevel(),
1091 identityInfo.getDateAdded());
1092 }
1093
1094 @Override
1095 public List<Identity> getIdentities(RecipientIdentifier.Single recipient) {
1096 IdentityInfo identity;
1097 try {
1098 identity = account.getIdentityKeyStore().getIdentity(resolveRecipient(recipient));
1099 } catch (UnregisteredUserException e) {
1100 identity = null;
1101 }
1102 return identity == null ? List.of() : List.of(toIdentity(identity));
1103 }
1104
1105 /**
1106 * Trust this the identity with this fingerprint
1107 *
1108 * @param recipient username of the identity
1109 * @param fingerprint Fingerprint
1110 */
1111 @Override
1112 public boolean trustIdentityVerified(RecipientIdentifier.Single recipient, byte[] fingerprint) {
1113 RecipientId recipientId;
1114 try {
1115 recipientId = resolveRecipient(recipient);
1116 } catch (UnregisteredUserException e) {
1117 return false;
1118 }
1119 return identityHelper.trustIdentityVerified(recipientId, fingerprint);
1120 }
1121
1122 /**
1123 * Trust this the identity with this safety number
1124 *
1125 * @param recipient username of the identity
1126 * @param safetyNumber Safety number
1127 */
1128 @Override
1129 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier.Single recipient, String safetyNumber) {
1130 RecipientId recipientId;
1131 try {
1132 recipientId = resolveRecipient(recipient);
1133 } catch (UnregisteredUserException e) {
1134 return false;
1135 }
1136 return identityHelper.trustIdentityVerifiedSafetyNumber(recipientId, safetyNumber);
1137 }
1138
1139 /**
1140 * Trust this the identity with this scannable safety number
1141 *
1142 * @param recipient username of the identity
1143 * @param safetyNumber Scannable safety number
1144 */
1145 @Override
1146 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier.Single recipient, byte[] safetyNumber) {
1147 RecipientId recipientId;
1148 try {
1149 recipientId = resolveRecipient(recipient);
1150 } catch (UnregisteredUserException e) {
1151 return false;
1152 }
1153 return identityHelper.trustIdentityVerifiedSafetyNumber(recipientId, safetyNumber);
1154 }
1155
1156 /**
1157 * Trust all keys of this identity without verification
1158 *
1159 * @param recipient username of the identity
1160 */
1161 @Override
1162 public boolean trustIdentityAllKeys(RecipientIdentifier.Single recipient) {
1163 RecipientId recipientId;
1164 try {
1165 recipientId = resolveRecipient(recipient);
1166 } catch (UnregisteredUserException e) {
1167 return false;
1168 }
1169 return identityHelper.trustIdentityAllKeys(recipientId);
1170 }
1171
1172 private void handleIdentityFailure(
1173 final RecipientId recipientId, final SendMessageResult.IdentityFailure identityFailure
1174 ) {
1175 this.identityHelper.handleIdentityFailure(recipientId, identityFailure);
1176 }
1177
1178 @Override
1179 public SignalServiceAddress resolveSignalServiceAddress(SignalServiceAddress address) {
1180 return resolveSignalServiceAddress(resolveRecipient(address));
1181 }
1182
1183 private SignalServiceAddress resolveSignalServiceAddress(RecipientId recipientId) {
1184 final var address = account.getRecipientStore().resolveRecipientAddress(recipientId);
1185 if (address.getUuid().isPresent()) {
1186 return address.toSignalServiceAddress();
1187 }
1188
1189 // Address in recipient store doesn't have a uuid, this shouldn't happen
1190 // Try to retrieve the uuid from the server
1191 final var number = address.getNumber().get();
1192 final UUID uuid;
1193 try {
1194 uuid = getRegisteredUser(number);
1195 } catch (IOException e) {
1196 logger.warn("Failed to get uuid for e164 number: {}", number, e);
1197 // Return SignalServiceAddress with unknown UUID
1198 return address.toSignalServiceAddress();
1199 }
1200 return resolveSignalServiceAddress(account.getRecipientStore().resolveRecipient(uuid));
1201 }
1202
1203 private Set<RecipientId> resolveRecipients(Collection<RecipientIdentifier.Single> recipients) throws UnregisteredUserException {
1204 final var recipientIds = new HashSet<RecipientId>(recipients.size());
1205 for (var number : recipients) {
1206 final var recipientId = resolveRecipient(number);
1207 recipientIds.add(recipientId);
1208 }
1209 return recipientIds;
1210 }
1211
1212 private RecipientId resolveRecipient(final RecipientIdentifier.Single recipient) throws UnregisteredUserException {
1213 if (recipient instanceof RecipientIdentifier.Uuid) {
1214 return account.getRecipientStore().resolveRecipient(((RecipientIdentifier.Uuid) recipient).uuid);
1215 } else {
1216 final var number = ((RecipientIdentifier.Number) recipient).number;
1217 return account.getRecipientStore().resolveRecipient(number, () -> {
1218 try {
1219 return getRegisteredUser(number);
1220 } catch (IOException e) {
1221 return null;
1222 }
1223 });
1224 }
1225 }
1226
1227 private RecipientId resolveRecipient(SignalServiceAddress address) {
1228 return account.getRecipientStore().resolveRecipient(address);
1229 }
1230
1231 private RecipientId resolveRecipientTrusted(SignalServiceAddress address) {
1232 return account.getRecipientStore().resolveRecipientTrusted(address);
1233 }
1234
1235 @Override
1236 public void close() throws IOException {
1237 close(true);
1238 }
1239
1240 private void close(boolean closeAccount) throws IOException {
1241 executor.shutdown();
1242
1243 dependencies.getSignalWebSocket().disconnect();
1244
1245 if (closeAccount && account != null) {
1246 account.close();
1247 }
1248 account = null;
1249 }
1250 }