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