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