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