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