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