]> nmode's Git Repositories - signal-cli/blob - lib/src/main/java/org/asamk/signal/manager/ManagerImpl.java
Retrieve self profile from storage
[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, profileHelper);
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
334 final var configurationStore = account.getConfigurationStore();
335 if (readReceipts != null) {
336 configurationStore.setReadReceipts(readReceipts);
337 }
338 if (unidentifiedDeliveryIndicators != null) {
339 configurationStore.setUnidentifiedDeliveryIndicators(unidentifiedDeliveryIndicators);
340 }
341 if (typingIndicators != null) {
342 configurationStore.setTypingIndicators(typingIndicators);
343 }
344 if (linkPreviews != null) {
345 configurationStore.setLinkPreviews(linkPreviews);
346 }
347 syncHelper.sendConfigurationMessage();
348 }
349
350 /**
351 * @param givenName if null, the previous givenName will be kept
352 * @param familyName if null, the previous familyName will be kept
353 * @param about if null, the previous about text will be kept
354 * @param aboutEmoji if null, the previous about emoji will be kept
355 * @param avatar if avatar is null the image from the local avatar store is used (if present),
356 */
357 @Override
358 public void setProfile(
359 String givenName, final String familyName, String about, String aboutEmoji, Optional<File> avatar
360 ) throws IOException {
361 profileHelper.setProfile(givenName, familyName, about, aboutEmoji, avatar);
362 syncHelper.sendSyncFetchProfileMessage();
363 }
364
365 @Override
366 public void unregister() throws IOException {
367 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
368 // If this is the master device, other users can't send messages to this number anymore.
369 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
370 dependencies.getAccountManager().setGcmId(Optional.absent());
371
372 account.setRegistered(false);
373 }
374
375 @Override
376 public void deleteAccount() throws IOException {
377 try {
378 pinHelper.removeRegistrationLockPin();
379 } catch (UnauthenticatedResponseException e) {
380 logger.warn("Failed to remove registration lock pin");
381 }
382 account.setRegistrationLockPin(null, null);
383
384 dependencies.getAccountManager().deleteAccount();
385
386 account.setRegistered(false);
387 }
388
389 @Override
390 public void submitRateLimitRecaptchaChallenge(String challenge, String captcha) throws IOException {
391 dependencies.getAccountManager().submitRateLimitRecaptchaChallenge(challenge, captcha);
392 }
393
394 @Override
395 public List<Device> getLinkedDevices() throws IOException {
396 var devices = dependencies.getAccountManager().getDevices();
397 account.setMultiDevice(devices.size() > 1);
398 var identityKey = account.getIdentityKeyPair().getPrivateKey();
399 return devices.stream().map(d -> {
400 String deviceName = d.getName();
401 if (deviceName != null) {
402 try {
403 deviceName = DeviceNameUtil.decryptDeviceName(deviceName, identityKey);
404 } catch (IOException e) {
405 logger.debug("Failed to decrypt device name, maybe plain text?", e);
406 }
407 }
408 return new Device(d.getId(),
409 deviceName,
410 d.getCreated(),
411 d.getLastSeen(),
412 d.getId() == account.getDeviceId());
413 }).collect(Collectors.toList());
414 }
415
416 @Override
417 public void removeLinkedDevices(long deviceId) throws IOException {
418 dependencies.getAccountManager().removeDevice(deviceId);
419 var devices = dependencies.getAccountManager().getDevices();
420 account.setMultiDevice(devices.size() > 1);
421 }
422
423 @Override
424 public void addDeviceLink(URI linkUri) throws IOException, InvalidKeyException {
425 var info = DeviceLinkInfo.parseDeviceLinkUri(linkUri);
426
427 addDevice(info.deviceIdentifier, info.deviceKey);
428 }
429
430 private void addDevice(String deviceIdentifier, ECPublicKey deviceKey) throws IOException, InvalidKeyException {
431 var identityKeyPair = account.getIdentityKeyPair();
432 var verificationCode = dependencies.getAccountManager().getNewDeviceVerificationCode();
433
434 dependencies.getAccountManager()
435 .addDevice(deviceIdentifier,
436 deviceKey,
437 identityKeyPair,
438 Optional.of(account.getProfileKey().serialize()),
439 verificationCode);
440 account.setMultiDevice(true);
441 }
442
443 @Override
444 public void setRegistrationLockPin(Optional<String> pin) throws IOException, UnauthenticatedResponseException {
445 if (!account.isMasterDevice()) {
446 throw new RuntimeException("Only master device can set a PIN");
447 }
448 if (pin.isPresent()) {
449 final var masterKey = account.getPinMasterKey() != null
450 ? account.getPinMasterKey()
451 : KeyUtils.createMasterKey();
452
453 pinHelper.setRegistrationLockPin(pin.get(), masterKey);
454
455 account.setRegistrationLockPin(pin.get(), masterKey);
456 } else {
457 // Remove KBS Pin
458 pinHelper.removeRegistrationLockPin();
459
460 account.setRegistrationLockPin(null, null);
461 }
462 }
463
464 void refreshPreKeys() throws IOException {
465 preKeyHelper.refreshPreKeys();
466 }
467
468 @Override
469 public Profile getRecipientProfile(RecipientIdentifier.Single recipient) throws UnregisteredUserException {
470 return profileHelper.getRecipientProfile(resolveRecipient(recipient));
471 }
472
473 private Profile getRecipientProfile(RecipientId recipientId) {
474 return profileHelper.getRecipientProfile(recipientId);
475 }
476
477 @Override
478 public List<Group> getGroups() {
479 return account.getGroupStore().getGroups().stream().map(this::toGroup).collect(Collectors.toList());
480 }
481
482 private Group toGroup(final GroupInfo groupInfo) {
483 if (groupInfo == null) {
484 return null;
485 }
486
487 return new Group(groupInfo.getGroupId(),
488 groupInfo.getTitle(),
489 groupInfo.getDescription(),
490 groupInfo.getGroupInviteLink(),
491 groupInfo.getMembers()
492 .stream()
493 .map(account.getRecipientStore()::resolveRecipientAddress)
494 .collect(Collectors.toSet()),
495 groupInfo.getPendingMembers()
496 .stream()
497 .map(account.getRecipientStore()::resolveRecipientAddress)
498 .collect(Collectors.toSet()),
499 groupInfo.getRequestingMembers()
500 .stream()
501 .map(account.getRecipientStore()::resolveRecipientAddress)
502 .collect(Collectors.toSet()),
503 groupInfo.getAdminMembers()
504 .stream()
505 .map(account.getRecipientStore()::resolveRecipientAddress)
506 .collect(Collectors.toSet()),
507 groupInfo.isBlocked(),
508 groupInfo.getMessageExpirationTime(),
509 groupInfo.isAnnouncementGroup(),
510 groupInfo.isMember(account.getSelfRecipientId()));
511 }
512
513 @Override
514 public SendGroupMessageResults quitGroup(
515 GroupId groupId, Set<RecipientIdentifier.Single> groupAdmins
516 ) throws GroupNotFoundException, IOException, NotAGroupMemberException, LastGroupAdminException {
517 final var newAdmins = resolveRecipients(groupAdmins);
518 return groupHelper.quitGroup(groupId, newAdmins);
519 }
520
521 @Override
522 public void deleteGroup(GroupId groupId) throws IOException {
523 groupHelper.deleteGroup(groupId);
524 }
525
526 @Override
527 public Pair<GroupId, SendGroupMessageResults> createGroup(
528 String name, Set<RecipientIdentifier.Single> members, File avatarFile
529 ) throws IOException, AttachmentInvalidException {
530 return groupHelper.createGroup(name, members == null ? null : resolveRecipients(members), avatarFile);
531 }
532
533 @Override
534 public SendGroupMessageResults updateGroup(
535 GroupId groupId,
536 String name,
537 String description,
538 Set<RecipientIdentifier.Single> members,
539 Set<RecipientIdentifier.Single> removeMembers,
540 Set<RecipientIdentifier.Single> admins,
541 Set<RecipientIdentifier.Single> removeAdmins,
542 boolean resetGroupLink,
543 GroupLinkState groupLinkState,
544 GroupPermission addMemberPermission,
545 GroupPermission editDetailsPermission,
546 File avatarFile,
547 Integer expirationTimer,
548 Boolean isAnnouncementGroup
549 ) throws IOException, GroupNotFoundException, AttachmentInvalidException, NotAGroupMemberException, GroupSendingNotAllowedException {
550 return groupHelper.updateGroup(groupId,
551 name,
552 description,
553 members == null ? null : resolveRecipients(members),
554 removeMembers == null ? null : resolveRecipients(removeMembers),
555 admins == null ? null : resolveRecipients(admins),
556 removeAdmins == null ? null : resolveRecipients(removeAdmins),
557 resetGroupLink,
558 groupLinkState,
559 addMemberPermission,
560 editDetailsPermission,
561 avatarFile,
562 expirationTimer,
563 isAnnouncementGroup);
564 }
565
566 @Override
567 public Pair<GroupId, SendGroupMessageResults> joinGroup(
568 GroupInviteLinkUrl inviteLinkUrl
569 ) throws IOException, GroupLinkNotActiveException {
570 return groupHelper.joinGroup(inviteLinkUrl);
571 }
572
573 private SendMessageResults sendMessage(
574 SignalServiceDataMessage.Builder messageBuilder, Set<RecipientIdentifier> recipients
575 ) throws IOException, NotAGroupMemberException, GroupNotFoundException, GroupSendingNotAllowedException {
576 var results = new HashMap<RecipientIdentifier, List<SendMessageResult>>();
577 long timestamp = System.currentTimeMillis();
578 messageBuilder.withTimestamp(timestamp);
579 for (final var recipient : recipients) {
580 if (recipient instanceof RecipientIdentifier.Single) {
581 final var recipientId = resolveRecipient((RecipientIdentifier.Single) recipient);
582 final var result = sendHelper.sendMessage(messageBuilder, recipientId);
583 results.put(recipient, List.of(result));
584 } else if (recipient instanceof RecipientIdentifier.NoteToSelf) {
585 final var result = sendHelper.sendSelfMessage(messageBuilder);
586 results.put(recipient, List.of(result));
587 } else if (recipient instanceof RecipientIdentifier.Group) {
588 final var groupId = ((RecipientIdentifier.Group) recipient).groupId;
589 final var result = sendHelper.sendAsGroupMessage(messageBuilder, 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.getMessageText());
655 final var attachments = message.getAttachments();
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, UnregisteredUserException {
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 {
730 groupHelper.setGroupBlocked(groupId, blocked);
731 // TODO cycle our profile key
732 syncHelper.sendBlockedList();
733 }
734
735 /**
736 * Change the expiration timer for a contact
737 */
738 @Override
739 public void setExpirationTimer(
740 RecipientIdentifier.Single recipient, int messageExpirationTimer
741 ) throws IOException {
742 var recipientId = resolveRecipient(recipient);
743 contactHelper.setExpirationTimer(recipientId, messageExpirationTimer);
744 final var messageBuilder = SignalServiceDataMessage.newBuilder().asExpirationUpdate();
745 try {
746 sendMessage(messageBuilder, Set.of(recipient));
747 } catch (NotAGroupMemberException | GroupNotFoundException | GroupSendingNotAllowedException e) {
748 throw new AssertionError(e);
749 }
750 }
751
752 /**
753 * Upload the sticker pack from path.
754 *
755 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
756 * @return if successful, returns the URL to install the sticker pack in the signal app
757 */
758 @Override
759 public URI uploadStickerPack(File path) throws IOException, StickerPackInvalidException {
760 var manifest = StickerUtils.getSignalServiceStickerManifestUpload(path);
761
762 var messageSender = dependencies.getMessageSender();
763
764 var packKey = KeyUtils.createStickerUploadKey();
765 var packIdString = messageSender.uploadStickerManifest(manifest, packKey);
766 var packId = StickerPackId.deserialize(Hex.fromStringCondensed(packIdString));
767
768 var sticker = new Sticker(packId, packKey);
769 account.getStickerStore().updateSticker(sticker);
770
771 try {
772 return new URI("https",
773 "signal.art",
774 "/addstickers/",
775 "pack_id="
776 + URLEncoder.encode(Hex.toStringCondensed(packId.serialize()), StandardCharsets.UTF_8)
777 + "&pack_key="
778 + URLEncoder.encode(Hex.toStringCondensed(packKey), StandardCharsets.UTF_8));
779 } catch (URISyntaxException e) {
780 throw new AssertionError(e);
781 }
782 }
783
784 @Override
785 public void requestAllSyncData() throws IOException {
786 syncHelper.requestAllSyncData();
787 retrieveRemoteStorage();
788 }
789
790 void retrieveRemoteStorage() throws IOException {
791 if (account.getStorageKey() != null) {
792 storageHelper.readDataFromStorage();
793 }
794 }
795
796 private byte[] getSenderCertificate() {
797 byte[] certificate;
798 try {
799 if (account.isPhoneNumberShared()) {
800 certificate = dependencies.getAccountManager().getSenderCertificate();
801 } else {
802 certificate = dependencies.getAccountManager().getSenderCertificateForPhoneNumberPrivacy();
803 }
804 } catch (IOException e) {
805 logger.warn("Failed to get sender certificate, ignoring: {}", e.getMessage());
806 return null;
807 }
808 // TODO cache for a day
809 return certificate;
810 }
811
812 private RecipientId refreshRegisteredUser(RecipientId recipientId) throws IOException {
813 final var address = resolveSignalServiceAddress(recipientId);
814 if (!address.getNumber().isPresent()) {
815 return recipientId;
816 }
817 final var number = address.getNumber().get();
818 final var uuid = getRegisteredUser(number);
819 return resolveRecipientTrusted(new SignalServiceAddress(uuid, number));
820 }
821
822 private UUID getRegisteredUser(final String number) throws IOException {
823 final Map<String, UUID> uuidMap;
824 try {
825 uuidMap = getRegisteredUsers(Set.of(number));
826 } catch (NumberFormatException e) {
827 throw new UnregisteredUserException(number, e);
828 }
829 final var uuid = uuidMap.get(number);
830 if (uuid == null) {
831 throw new UnregisteredUserException(number, null);
832 }
833 return uuid;
834 }
835
836 private Map<String, UUID> getRegisteredUsers(final Set<String> numbers) throws IOException {
837 final Map<String, UUID> registeredUsers;
838 try {
839 registeredUsers = dependencies.getAccountManager()
840 .getRegisteredUsers(ServiceConfig.getIasKeyStore(),
841 numbers,
842 serviceEnvironmentConfig.getCdsMrenclave());
843 } catch (Quote.InvalidQuoteFormatException | UnauthenticatedQuoteException | SignatureException | UnauthenticatedResponseException | InvalidKeyException e) {
844 throw new IOException(e);
845 }
846
847 // Store numbers as recipients so we have the number/uuid association
848 registeredUsers.forEach((number, uuid) -> resolveRecipientTrusted(new SignalServiceAddress(uuid, number)));
849
850 return registeredUsers;
851 }
852
853 private void retryFailedReceivedMessages(ReceiveMessageHandler handler, boolean ignoreAttachments) {
854 Set<HandleAction> queuedActions = new HashSet<>();
855 for (var cachedMessage : account.getMessageCache().getCachedMessages()) {
856 var actions = retryFailedReceivedMessage(handler, ignoreAttachments, cachedMessage);
857 if (actions != null) {
858 queuedActions.addAll(actions);
859 }
860 }
861 handleQueuedActions(queuedActions);
862 }
863
864 private List<HandleAction> retryFailedReceivedMessage(
865 final ReceiveMessageHandler handler, final boolean ignoreAttachments, final CachedMessage cachedMessage
866 ) {
867 var envelope = cachedMessage.loadEnvelope();
868 if (envelope == null) {
869 cachedMessage.delete();
870 return null;
871 }
872
873 final var result = incomingMessageHandler.handleRetryEnvelope(envelope, ignoreAttachments, handler);
874 final var actions = result.first();
875 final var exception = result.second();
876
877 if (exception instanceof UntrustedIdentityException) {
878 if (System.currentTimeMillis() - envelope.getServerDeliveredTimestamp() > 1000L * 60 * 60 * 24 * 30) {
879 // Envelope is more than a month old, cleaning up.
880 cachedMessage.delete();
881 return null;
882 }
883 if (!envelope.hasSourceUuid()) {
884 final var identifier = ((UntrustedIdentityException) exception).getSender();
885 final var recipientId = account.getRecipientStore().resolveRecipient(identifier);
886 try {
887 account.getMessageCache().replaceSender(cachedMessage, recipientId);
888 } catch (IOException ioException) {
889 logger.warn("Failed to move cached message to recipient folder: {}", ioException.getMessage());
890 }
891 }
892 return null;
893 }
894
895 // If successful and for all other errors that are not recoverable, delete the cached message
896 cachedMessage.delete();
897 return actions;
898 }
899
900 @Override
901 public void receiveMessages(
902 long timeout,
903 TimeUnit unit,
904 boolean returnOnTimeout,
905 boolean ignoreAttachments,
906 ReceiveMessageHandler handler
907 ) throws IOException {
908 retryFailedReceivedMessages(handler, ignoreAttachments);
909
910 Set<HandleAction> queuedActions = new HashSet<>();
911
912 final var signalWebSocket = dependencies.getSignalWebSocket();
913 signalWebSocket.connect();
914
915 hasCaughtUpWithOldMessages = false;
916
917 while (!Thread.interrupted()) {
918 SignalServiceEnvelope envelope;
919 final CachedMessage[] cachedMessage = {null};
920 account.setLastReceiveTimestamp(System.currentTimeMillis());
921 logger.debug("Checking for new message from server");
922 try {
923 var result = signalWebSocket.readOrEmpty(unit.toMillis(timeout), envelope1 -> {
924 final var recipientId = envelope1.hasSourceUuid()
925 ? resolveRecipient(envelope1.getSourceAddress())
926 : null;
927 // store message on disk, before acknowledging receipt to the server
928 cachedMessage[0] = account.getMessageCache().cacheMessage(envelope1, recipientId);
929 });
930 if (result.isPresent()) {
931 envelope = result.get();
932 logger.debug("New message received from server");
933 } else {
934 logger.debug("Received indicator that server queue is empty");
935 handleQueuedActions(queuedActions);
936 queuedActions.clear();
937
938 hasCaughtUpWithOldMessages = true;
939 synchronized (this) {
940 this.notifyAll();
941 }
942
943 // Continue to wait another timeout for new messages
944 continue;
945 }
946 } catch (AssertionError e) {
947 if (e.getCause() instanceof InterruptedException) {
948 Thread.currentThread().interrupt();
949 break;
950 } else {
951 throw e;
952 }
953 } catch (WebSocketUnavailableException e) {
954 logger.debug("Pipe unexpectedly unavailable, connecting");
955 signalWebSocket.connect();
956 continue;
957 } catch (TimeoutException e) {
958 if (returnOnTimeout) return;
959 continue;
960 }
961
962 final var result = incomingMessageHandler.handleEnvelope(envelope, ignoreAttachments, handler);
963 queuedActions.addAll(result.first());
964 final var exception = result.second();
965
966 if (hasCaughtUpWithOldMessages) {
967 handleQueuedActions(queuedActions);
968 }
969 if (cachedMessage[0] != null) {
970 if (exception instanceof UntrustedIdentityException) {
971 final var address = ((UntrustedIdentityException) exception).getSender();
972 final var recipientId = resolveRecipient(address);
973 if (!envelope.hasSourceUuid()) {
974 try {
975 cachedMessage[0] = account.getMessageCache().replaceSender(cachedMessage[0], recipientId);
976 } catch (IOException ioException) {
977 logger.warn("Failed to move cached message to recipient folder: {}",
978 ioException.getMessage());
979 }
980 }
981 } else {
982 cachedMessage[0].delete();
983 }
984 }
985 }
986 handleQueuedActions(queuedActions);
987 }
988
989 @Override
990 public boolean hasCaughtUpWithOldMessages() {
991 return hasCaughtUpWithOldMessages;
992 }
993
994 private void handleQueuedActions(final Collection<HandleAction> queuedActions) {
995 var interrupted = false;
996 for (var action : queuedActions) {
997 try {
998 action.execute(context);
999 } catch (Throwable e) {
1000 if ((e instanceof AssertionError || e instanceof RuntimeException)
1001 && e.getCause() instanceof InterruptedException) {
1002 interrupted = true;
1003 continue;
1004 }
1005 logger.warn("Message action failed.", e);
1006 }
1007 }
1008 if (interrupted) {
1009 Thread.currentThread().interrupt();
1010 }
1011 }
1012
1013 @Override
1014 public boolean isContactBlocked(final RecipientIdentifier.Single recipient) {
1015 final RecipientId recipientId;
1016 try {
1017 recipientId = resolveRecipient(recipient);
1018 } catch (UnregisteredUserException e) {
1019 return false;
1020 }
1021 return contactHelper.isContactBlocked(recipientId);
1022 }
1023
1024 @Override
1025 public File getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId) {
1026 return attachmentHelper.getAttachmentFile(attachmentId);
1027 }
1028
1029 @Override
1030 public void sendContacts() throws IOException {
1031 syncHelper.sendContacts();
1032 }
1033
1034 @Override
1035 public List<Pair<RecipientAddress, Contact>> getContacts() {
1036 return account.getContactStore()
1037 .getContacts()
1038 .stream()
1039 .map(p -> new Pair<>(account.getRecipientStore().resolveRecipientAddress(p.first()), p.second()))
1040 .collect(Collectors.toList());
1041 }
1042
1043 @Override
1044 public String getContactOrProfileName(RecipientIdentifier.Single recipient) {
1045 final RecipientId recipientId;
1046 try {
1047 recipientId = resolveRecipient(recipient);
1048 } catch (UnregisteredUserException e) {
1049 return null;
1050 }
1051
1052 final var contact = account.getContactStore().getContact(recipientId);
1053 if (contact != null && !Util.isEmpty(contact.getName())) {
1054 return contact.getName();
1055 }
1056
1057 final var profile = getRecipientProfile(recipientId);
1058 if (profile != null) {
1059 return profile.getDisplayName();
1060 }
1061
1062 return null;
1063 }
1064
1065 @Override
1066 public Group getGroup(GroupId groupId) {
1067 return toGroup(groupHelper.getGroup(groupId));
1068 }
1069
1070 public GroupInfo getGroupInfo(GroupId groupId) {
1071 return groupHelper.getGroup(groupId);
1072 }
1073
1074 @Override
1075 public List<Identity> getIdentities() {
1076 return account.getIdentityKeyStore()
1077 .getIdentities()
1078 .stream()
1079 .map(this::toIdentity)
1080 .collect(Collectors.toList());
1081 }
1082
1083 private Identity toIdentity(final IdentityInfo identityInfo) {
1084 if (identityInfo == null) {
1085 return null;
1086 }
1087
1088 final var address = account.getRecipientStore().resolveRecipientAddress(identityInfo.getRecipientId());
1089 return new Identity(address,
1090 identityInfo.getIdentityKey(),
1091 computeSafetyNumber(address.toSignalServiceAddress(), identityInfo.getIdentityKey()),
1092 computeSafetyNumberForScanning(address.toSignalServiceAddress(), identityInfo.getIdentityKey()),
1093 identityInfo.getTrustLevel(),
1094 identityInfo.getDateAdded());
1095 }
1096
1097 @Override
1098 public List<Identity> getIdentities(RecipientIdentifier.Single recipient) {
1099 IdentityInfo identity;
1100 try {
1101 identity = account.getIdentityKeyStore().getIdentity(resolveRecipient(recipient));
1102 } catch (UnregisteredUserException e) {
1103 identity = null;
1104 }
1105 return identity == null ? List.of() : List.of(toIdentity(identity));
1106 }
1107
1108 /**
1109 * Trust this the identity with this fingerprint
1110 *
1111 * @param recipient username of the identity
1112 * @param fingerprint Fingerprint
1113 */
1114 @Override
1115 public boolean trustIdentityVerified(RecipientIdentifier.Single recipient, byte[] fingerprint) {
1116 RecipientId recipientId;
1117 try {
1118 recipientId = resolveRecipient(recipient);
1119 } catch (UnregisteredUserException e) {
1120 return false;
1121 }
1122 return trustIdentity(recipientId,
1123 identityKey -> Arrays.equals(identityKey.serialize(), fingerprint),
1124 TrustLevel.TRUSTED_VERIFIED);
1125 }
1126
1127 /**
1128 * Trust this the identity with this safety number
1129 *
1130 * @param recipient username of the identity
1131 * @param safetyNumber Safety number
1132 */
1133 @Override
1134 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier.Single recipient, String safetyNumber) {
1135 RecipientId recipientId;
1136 try {
1137 recipientId = resolveRecipient(recipient);
1138 } catch (UnregisteredUserException e) {
1139 return false;
1140 }
1141 var address = resolveSignalServiceAddress(recipientId);
1142 return trustIdentity(recipientId,
1143 identityKey -> safetyNumber.equals(computeSafetyNumber(address, identityKey)),
1144 TrustLevel.TRUSTED_VERIFIED);
1145 }
1146
1147 /**
1148 * Trust this the identity with this scannable safety number
1149 *
1150 * @param recipient username of the identity
1151 * @param safetyNumber Scannable safety number
1152 */
1153 @Override
1154 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier.Single recipient, byte[] safetyNumber) {
1155 RecipientId recipientId;
1156 try {
1157 recipientId = resolveRecipient(recipient);
1158 } catch (UnregisteredUserException e) {
1159 return false;
1160 }
1161 var address = resolveSignalServiceAddress(recipientId);
1162 return trustIdentity(recipientId, identityKey -> {
1163 final var fingerprint = computeSafetyNumberFingerprint(address, identityKey);
1164 try {
1165 return fingerprint != null && fingerprint.getScannableFingerprint().compareTo(safetyNumber);
1166 } catch (FingerprintVersionMismatchException | FingerprintParsingException e) {
1167 return false;
1168 }
1169 }, TrustLevel.TRUSTED_VERIFIED);
1170 }
1171
1172 /**
1173 * Trust all keys of this identity without verification
1174 *
1175 * @param recipient username of the identity
1176 */
1177 @Override
1178 public boolean trustIdentityAllKeys(RecipientIdentifier.Single recipient) {
1179 RecipientId recipientId;
1180 try {
1181 recipientId = resolveRecipient(recipient);
1182 } catch (UnregisteredUserException e) {
1183 return false;
1184 }
1185 return trustIdentity(recipientId, identityKey -> true, TrustLevel.TRUSTED_UNVERIFIED);
1186 }
1187
1188 private boolean trustIdentity(
1189 RecipientId recipientId, Function<IdentityKey, Boolean> verifier, TrustLevel trustLevel
1190 ) {
1191 var identity = account.getIdentityKeyStore().getIdentity(recipientId);
1192 if (identity == null) {
1193 return false;
1194 }
1195
1196 if (!verifier.apply(identity.getIdentityKey())) {
1197 return false;
1198 }
1199
1200 account.getIdentityKeyStore().setIdentityTrustLevel(recipientId, identity.getIdentityKey(), trustLevel);
1201 try {
1202 var address = resolveSignalServiceAddress(recipientId);
1203 syncHelper.sendVerifiedMessage(address, identity.getIdentityKey(), trustLevel);
1204 } catch (IOException e) {
1205 logger.warn("Failed to send verification sync message: {}", e.getMessage());
1206 }
1207
1208 return true;
1209 }
1210
1211 private void handleIdentityFailure(
1212 final RecipientId recipientId, final SendMessageResult.IdentityFailure identityFailure
1213 ) {
1214 final var identityKey = identityFailure.getIdentityKey();
1215 if (identityKey != null) {
1216 final var newIdentity = account.getIdentityKeyStore().saveIdentity(recipientId, identityKey, new Date());
1217 if (newIdentity) {
1218 account.getSessionStore().archiveSessions(recipientId);
1219 }
1220 } else {
1221 // Retrieve profile to get the current identity key from the server
1222 profileHelper.refreshRecipientProfile(recipientId);
1223 }
1224 }
1225
1226 @Override
1227 public String computeSafetyNumber(SignalServiceAddress theirAddress, IdentityKey theirIdentityKey) {
1228 final Fingerprint fingerprint = computeSafetyNumberFingerprint(theirAddress, theirIdentityKey);
1229 return fingerprint == null ? null : fingerprint.getDisplayableFingerprint().getDisplayText();
1230 }
1231
1232 private byte[] computeSafetyNumberForScanning(SignalServiceAddress theirAddress, IdentityKey theirIdentityKey) {
1233 final Fingerprint fingerprint = computeSafetyNumberFingerprint(theirAddress, theirIdentityKey);
1234 return fingerprint == null ? null : fingerprint.getScannableFingerprint().getSerialized();
1235 }
1236
1237 private Fingerprint computeSafetyNumberFingerprint(
1238 final SignalServiceAddress theirAddress, final IdentityKey theirIdentityKey
1239 ) {
1240 return Utils.computeSafetyNumber(capabilities.isUuid(),
1241 account.getSelfAddress(),
1242 account.getIdentityKeyPair().getPublicKey(),
1243 theirAddress,
1244 theirIdentityKey);
1245 }
1246
1247 @Override
1248 public SignalServiceAddress resolveSignalServiceAddress(SignalServiceAddress address) {
1249 return resolveSignalServiceAddress(resolveRecipient(address));
1250 }
1251
1252 private SignalServiceAddress resolveSignalServiceAddress(RecipientId recipientId) {
1253 final var address = account.getRecipientStore().resolveRecipientAddress(recipientId);
1254 if (address.getUuid().isPresent()) {
1255 return address.toSignalServiceAddress();
1256 }
1257
1258 // Address in recipient store doesn't have a uuid, this shouldn't happen
1259 // Try to retrieve the uuid from the server
1260 final var number = address.getNumber().get();
1261 final UUID uuid;
1262 try {
1263 uuid = getRegisteredUser(number);
1264 } catch (IOException e) {
1265 logger.warn("Failed to get uuid for e164 number: {}", number, e);
1266 // Return SignalServiceAddress with unknown UUID
1267 return address.toSignalServiceAddress();
1268 }
1269 return resolveSignalServiceAddress(account.getRecipientStore().resolveRecipient(uuid));
1270 }
1271
1272 private Set<RecipientId> resolveRecipients(Collection<RecipientIdentifier.Single> recipients) throws UnregisteredUserException {
1273 final var recipientIds = new HashSet<RecipientId>(recipients.size());
1274 for (var number : recipients) {
1275 final var recipientId = resolveRecipient(number);
1276 recipientIds.add(recipientId);
1277 }
1278 return recipientIds;
1279 }
1280
1281 private RecipientId resolveRecipient(final RecipientIdentifier.Single recipient) throws UnregisteredUserException {
1282 if (recipient instanceof RecipientIdentifier.Uuid) {
1283 return account.getRecipientStore().resolveRecipient(((RecipientIdentifier.Uuid) recipient).uuid);
1284 } else {
1285 final var number = ((RecipientIdentifier.Number) recipient).number;
1286 return account.getRecipientStore().resolveRecipient(number, () -> {
1287 try {
1288 return getRegisteredUser(number);
1289 } catch (IOException e) {
1290 return null;
1291 }
1292 });
1293 }
1294 }
1295
1296 private RecipientId resolveRecipient(SignalServiceAddress address) {
1297 return account.getRecipientStore().resolveRecipient(address);
1298 }
1299
1300 private RecipientId resolveRecipientTrusted(SignalServiceAddress address) {
1301 return account.getRecipientStore().resolveRecipientTrusted(address);
1302 }
1303
1304 @Override
1305 public void close() throws IOException {
1306 close(true);
1307 }
1308
1309 private void close(boolean closeAccount) throws IOException {
1310 executor.shutdown();
1311
1312 dependencies.getSignalWebSocket().disconnect();
1313
1314 if (closeAccount && account != null) {
1315 account.close();
1316 }
1317 account = null;
1318 }
1319
1320 }