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