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