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