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