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