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