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