]> nmode's Git Repositories - signal-cli/blob - lib/src/main/java/org/asamk/signal/manager/ManagerImpl.java
Add UnregisteredRecipientException
[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.UnregisteredRecipientException;
34 import org.asamk.signal.manager.api.UpdateGroup;
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.RecipientHelper;
52 import org.asamk.signal.manager.helper.SendHelper;
53 import org.asamk.signal.manager.helper.StorageHelper;
54 import org.asamk.signal.manager.helper.SyncHelper;
55 import org.asamk.signal.manager.helper.UnidentifiedAccessHelper;
56 import org.asamk.signal.manager.jobs.Context;
57 import org.asamk.signal.manager.storage.SignalAccount;
58 import org.asamk.signal.manager.storage.groups.GroupInfo;
59 import org.asamk.signal.manager.storage.identities.IdentityInfo;
60 import org.asamk.signal.manager.storage.messageCache.CachedMessage;
61 import org.asamk.signal.manager.storage.recipients.Contact;
62 import org.asamk.signal.manager.storage.recipients.Profile;
63 import org.asamk.signal.manager.storage.recipients.RecipientAddress;
64 import org.asamk.signal.manager.storage.recipients.RecipientId;
65 import org.asamk.signal.manager.storage.stickers.Sticker;
66 import org.asamk.signal.manager.storage.stickers.StickerPackId;
67 import org.asamk.signal.manager.util.KeyUtils;
68 import org.asamk.signal.manager.util.StickerUtils;
69 import org.slf4j.Logger;
70 import org.slf4j.LoggerFactory;
71 import org.whispersystems.libsignal.InvalidKeyException;
72 import org.whispersystems.libsignal.ecc.ECPublicKey;
73 import org.whispersystems.libsignal.util.guava.Optional;
74 import org.whispersystems.signalservice.api.SignalSessionLock;
75 import org.whispersystems.signalservice.api.messages.SignalServiceDataMessage;
76 import org.whispersystems.signalservice.api.messages.SignalServiceEnvelope;
77 import org.whispersystems.signalservice.api.messages.SignalServiceReceiptMessage;
78 import org.whispersystems.signalservice.api.messages.SignalServiceTypingMessage;
79 import org.whispersystems.signalservice.api.push.ACI;
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, UnregisteredRecipientException {
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, UnregisteredRecipientException {
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, UnregisteredRecipientException {
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, UnregisteredRecipientException {
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 try {
618 final var recipientId = recipientHelper.resolveRecipient(single);
619 final var result = sendHelper.sendMessage(messageBuilder, recipientId);
620 results.put(recipient,
621 List.of(SendMessageResult.from(result,
622 account.getRecipientStore(),
623 account.getRecipientStore()::resolveRecipientAddress)));
624 } catch (UnregisteredRecipientException e) {
625 results.put(recipient,
626 List.of(SendMessageResult.unregisteredFailure(single.toPartialRecipientAddress())));
627 }
628 } else if (recipient instanceof RecipientIdentifier.NoteToSelf) {
629 final var result = sendHelper.sendSelfMessage(messageBuilder);
630 results.put(recipient,
631 List.of(SendMessageResult.from(result,
632 account.getRecipientStore(),
633 account.getRecipientStore()::resolveRecipientAddress)));
634 } else if (recipient instanceof RecipientIdentifier.Group group) {
635 final var result = sendHelper.sendAsGroupMessage(messageBuilder, group.groupId());
636 results.put(recipient,
637 result.stream()
638 .map(sendMessageResult -> SendMessageResult.from(sendMessageResult,
639 account.getRecipientStore(),
640 account.getRecipientStore()::resolveRecipientAddress))
641 .toList());
642 }
643 }
644 return new SendMessageResults(timestamp, results);
645 }
646
647 private SendMessageResults sendTypingMessage(
648 SignalServiceTypingMessage.Action action, Set<RecipientIdentifier> recipients
649 ) throws IOException, NotAGroupMemberException, GroupNotFoundException, GroupSendingNotAllowedException {
650 var results = new HashMap<RecipientIdentifier, List<SendMessageResult>>();
651 final var timestamp = System.currentTimeMillis();
652 for (var recipient : recipients) {
653 if (recipient instanceof RecipientIdentifier.Single single) {
654 final var message = new SignalServiceTypingMessage(action, timestamp, Optional.absent());
655 try {
656 final var recipientId = recipientHelper.resolveRecipient(single);
657 final var result = sendHelper.sendTypingMessage(message, recipientId);
658 results.put(recipient,
659 List.of(SendMessageResult.from(result,
660 account.getRecipientStore(),
661 account.getRecipientStore()::resolveRecipientAddress)));
662 } catch (UnregisteredRecipientException e) {
663 results.put(recipient,
664 List.of(SendMessageResult.unregisteredFailure(single.toPartialRecipientAddress())));
665 }
666 } else if (recipient instanceof RecipientIdentifier.Group) {
667 final var groupId = ((RecipientIdentifier.Group) recipient).groupId();
668 final var message = new SignalServiceTypingMessage(action, timestamp, Optional.of(groupId.serialize()));
669 final var result = sendHelper.sendGroupTypingMessage(message, groupId);
670 results.put(recipient,
671 result.stream()
672 .map(r -> SendMessageResult.from(r,
673 account.getRecipientStore(),
674 account.getRecipientStore()::resolveRecipientAddress))
675 .toList());
676 }
677 }
678 return new SendMessageResults(timestamp, results);
679 }
680
681 @Override
682 public SendMessageResults sendTypingMessage(
683 TypingAction action, Set<RecipientIdentifier> recipients
684 ) throws IOException, NotAGroupMemberException, GroupNotFoundException, GroupSendingNotAllowedException {
685 return sendTypingMessage(action.toSignalService(), recipients);
686 }
687
688 @Override
689 public SendMessageResults sendReadReceipt(
690 RecipientIdentifier.Single sender, List<Long> messageIds
691 ) throws IOException {
692 final var timestamp = System.currentTimeMillis();
693 var receiptMessage = new SignalServiceReceiptMessage(SignalServiceReceiptMessage.Type.READ,
694 messageIds,
695 timestamp);
696
697 return sendReceiptMessage(sender, timestamp, receiptMessage);
698 }
699
700 @Override
701 public SendMessageResults sendViewedReceipt(
702 RecipientIdentifier.Single sender, List<Long> messageIds
703 ) throws IOException {
704 final var timestamp = System.currentTimeMillis();
705 var receiptMessage = new SignalServiceReceiptMessage(SignalServiceReceiptMessage.Type.VIEWED,
706 messageIds,
707 timestamp);
708
709 return sendReceiptMessage(sender, timestamp, receiptMessage);
710 }
711
712 private SendMessageResults sendReceiptMessage(
713 final RecipientIdentifier.Single sender,
714 final long timestamp,
715 final SignalServiceReceiptMessage receiptMessage
716 ) throws IOException {
717 try {
718 final var result = sendHelper.sendReceiptMessage(receiptMessage, recipientHelper.resolveRecipient(sender));
719 return new SendMessageResults(timestamp,
720 Map.of(sender,
721 List.of(SendMessageResult.from(result,
722 account.getRecipientStore(),
723 account.getRecipientStore()::resolveRecipientAddress))));
724 } catch (UnregisteredRecipientException e) {
725 return new SendMessageResults(timestamp,
726 Map.of(sender, List.of(SendMessageResult.unregisteredFailure(sender.toPartialRecipientAddress()))));
727 }
728 }
729
730 @Override
731 public SendMessageResults sendMessage(
732 Message message, Set<RecipientIdentifier> recipients
733 ) throws IOException, AttachmentInvalidException, NotAGroupMemberException, GroupNotFoundException, GroupSendingNotAllowedException, UnregisteredRecipientException {
734 final var messageBuilder = SignalServiceDataMessage.newBuilder();
735 applyMessage(messageBuilder, message);
736 return sendMessage(messageBuilder, recipients);
737 }
738
739 private void applyMessage(
740 final SignalServiceDataMessage.Builder messageBuilder, final Message message
741 ) throws AttachmentInvalidException, IOException, UnregisteredRecipientException {
742 messageBuilder.withBody(message.messageText());
743 final var attachments = message.attachments();
744 if (attachments != null) {
745 messageBuilder.withAttachments(attachmentHelper.uploadAttachments(attachments));
746 }
747 if (message.mentions().size() > 0) {
748 messageBuilder.withMentions(resolveMentions(message.mentions()));
749 }
750 if (message.quote().isPresent()) {
751 final var quote = message.quote().get();
752 messageBuilder.withQuote(new SignalServiceDataMessage.Quote(quote.timestamp(),
753 recipientHelper.resolveSignalServiceAddress(recipientHelper.resolveRecipient(quote.author())),
754 quote.message(),
755 List.of(),
756 resolveMentions(quote.mentions())));
757 }
758 }
759
760 private ArrayList<SignalServiceDataMessage.Mention> resolveMentions(final List<Message.Mention> mentionList) throws IOException, UnregisteredRecipientException {
761 final var mentions = new ArrayList<SignalServiceDataMessage.Mention>();
762 for (final var m : mentionList) {
763 final var recipientId = recipientHelper.resolveRecipient(m.recipient());
764 mentions.add(new SignalServiceDataMessage.Mention(recipientHelper.resolveSignalServiceAddress(recipientId)
765 .getAci(), m.start(), m.length()));
766 }
767 return mentions;
768 }
769
770 @Override
771 public SendMessageResults sendRemoteDeleteMessage(
772 long targetSentTimestamp, Set<RecipientIdentifier> recipients
773 ) throws IOException, NotAGroupMemberException, GroupNotFoundException, GroupSendingNotAllowedException {
774 var delete = new SignalServiceDataMessage.RemoteDelete(targetSentTimestamp);
775 final var messageBuilder = SignalServiceDataMessage.newBuilder().withRemoteDelete(delete);
776 return sendMessage(messageBuilder, recipients);
777 }
778
779 @Override
780 public SendMessageResults sendMessageReaction(
781 String emoji,
782 boolean remove,
783 RecipientIdentifier.Single targetAuthor,
784 long targetSentTimestamp,
785 Set<RecipientIdentifier> recipients
786 ) throws IOException, NotAGroupMemberException, GroupNotFoundException, GroupSendingNotAllowedException, UnregisteredRecipientException {
787 var targetAuthorRecipientId = recipientHelper.resolveRecipient(targetAuthor);
788 var reaction = new SignalServiceDataMessage.Reaction(emoji,
789 remove,
790 recipientHelper.resolveSignalServiceAddress(targetAuthorRecipientId),
791 targetSentTimestamp);
792 final var messageBuilder = SignalServiceDataMessage.newBuilder().withReaction(reaction);
793 return sendMessage(messageBuilder, recipients);
794 }
795
796 @Override
797 public SendMessageResults sendEndSessionMessage(Set<RecipientIdentifier.Single> recipients) throws IOException {
798 var messageBuilder = SignalServiceDataMessage.newBuilder().asEndSessionMessage();
799
800 try {
801 return sendMessage(messageBuilder,
802 recipients.stream().map(RecipientIdentifier.class::cast).collect(Collectors.toSet()));
803 } catch (GroupNotFoundException | NotAGroupMemberException | GroupSendingNotAllowedException e) {
804 throw new AssertionError(e);
805 } finally {
806 for (var recipient : recipients) {
807 final RecipientId recipientId;
808 try {
809 recipientId = recipientHelper.resolveRecipient(recipient);
810 } catch (UnregisteredRecipientException e) {
811 continue;
812 }
813 account.getSessionStore().deleteAllSessions(recipientId);
814 }
815 }
816 }
817
818 @Override
819 public void deleteRecipient(final RecipientIdentifier.Single recipient) {
820 account.removeRecipient(account.getRecipientStore().resolveRecipient(recipient.toPartialRecipientAddress()));
821 }
822
823 @Override
824 public void deleteContact(final RecipientIdentifier.Single recipient) {
825 account.getContactStore()
826 .deleteContact(account.getRecipientStore().resolveRecipient(recipient.toPartialRecipientAddress()));
827 }
828
829 @Override
830 public void setContactName(
831 RecipientIdentifier.Single recipient, String name
832 ) throws NotMasterDeviceException, IOException, UnregisteredRecipientException {
833 if (!account.isMasterDevice()) {
834 throw new NotMasterDeviceException();
835 }
836 contactHelper.setContactName(recipientHelper.resolveRecipient(recipient), name);
837 }
838
839 @Override
840 public void setContactBlocked(
841 RecipientIdentifier.Single recipient, boolean blocked
842 ) throws NotMasterDeviceException, IOException, UnregisteredRecipientException {
843 if (!account.isMasterDevice()) {
844 throw new NotMasterDeviceException();
845 }
846 contactHelper.setContactBlocked(recipientHelper.resolveRecipient(recipient), blocked);
847 // TODO cycle our profile key, if we're not together in a group with recipient
848 syncHelper.sendBlockedList();
849 }
850
851 @Override
852 public void setGroupBlocked(
853 final GroupId groupId, final boolean blocked
854 ) throws GroupNotFoundException, IOException, NotMasterDeviceException {
855 if (!account.isMasterDevice()) {
856 throw new NotMasterDeviceException();
857 }
858 groupHelper.setGroupBlocked(groupId, blocked);
859 // TODO cycle our profile key
860 syncHelper.sendBlockedList();
861 }
862
863 /**
864 * Change the expiration timer for a contact
865 */
866 @Override
867 public void setExpirationTimer(
868 RecipientIdentifier.Single recipient, int messageExpirationTimer
869 ) throws IOException, UnregisteredRecipientException {
870 var recipientId = recipientHelper.resolveRecipient(recipient);
871 contactHelper.setExpirationTimer(recipientId, messageExpirationTimer);
872 final var messageBuilder = SignalServiceDataMessage.newBuilder().asExpirationUpdate();
873 try {
874 sendMessage(messageBuilder, Set.of(recipient));
875 } catch (NotAGroupMemberException | GroupNotFoundException | GroupSendingNotAllowedException e) {
876 throw new AssertionError(e);
877 }
878 }
879
880 /**
881 * Upload the sticker pack from path.
882 *
883 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
884 * @return if successful, returns the URL to install the sticker pack in the signal app
885 */
886 @Override
887 public URI uploadStickerPack(File path) throws IOException, StickerPackInvalidException {
888 var manifest = StickerUtils.getSignalServiceStickerManifestUpload(path);
889
890 var messageSender = dependencies.getMessageSender();
891
892 var packKey = KeyUtils.createStickerUploadKey();
893 var packIdString = messageSender.uploadStickerManifest(manifest, packKey);
894 var packId = StickerPackId.deserialize(Hex.fromStringCondensed(packIdString));
895
896 var sticker = new Sticker(packId, packKey);
897 account.getStickerStore().updateSticker(sticker);
898
899 try {
900 return new URI("https",
901 "signal.art",
902 "/addstickers/",
903 "pack_id="
904 + URLEncoder.encode(Hex.toStringCondensed(packId.serialize()), StandardCharsets.UTF_8)
905 + "&pack_key="
906 + URLEncoder.encode(Hex.toStringCondensed(packKey), StandardCharsets.UTF_8));
907 } catch (URISyntaxException e) {
908 throw new AssertionError(e);
909 }
910 }
911
912 @Override
913 public void requestAllSyncData() throws IOException {
914 syncHelper.requestAllSyncData();
915 retrieveRemoteStorage();
916 }
917
918 void retrieveRemoteStorage() throws IOException {
919 if (account.getStorageKey() != null) {
920 storageHelper.readDataFromStorage();
921 }
922 }
923
924 private void retryFailedReceivedMessages(ReceiveMessageHandler handler) {
925 Set<HandleAction> queuedActions = new HashSet<>();
926 for (var cachedMessage : account.getMessageCache().getCachedMessages()) {
927 var actions = retryFailedReceivedMessage(handler, cachedMessage);
928 if (actions != null) {
929 queuedActions.addAll(actions);
930 }
931 }
932 handleQueuedActions(queuedActions);
933 }
934
935 private List<HandleAction> retryFailedReceivedMessage(
936 final ReceiveMessageHandler handler, final CachedMessage cachedMessage
937 ) {
938 var envelope = cachedMessage.loadEnvelope();
939 if (envelope == null) {
940 cachedMessage.delete();
941 return null;
942 }
943
944 final var result = incomingMessageHandler.handleRetryEnvelope(envelope, ignoreAttachments, handler);
945 final var actions = result.first();
946 final var exception = result.second();
947
948 if (exception instanceof UntrustedIdentityException) {
949 if (System.currentTimeMillis() - envelope.getServerDeliveredTimestamp() > 1000L * 60 * 60 * 24 * 30) {
950 // Envelope is more than a month old, cleaning up.
951 cachedMessage.delete();
952 return null;
953 }
954 if (!envelope.hasSourceUuid()) {
955 final var identifier = ((UntrustedIdentityException) exception).getSender();
956 final var recipientId = account.getRecipientStore().resolveRecipient(identifier);
957 try {
958 account.getMessageCache().replaceSender(cachedMessage, recipientId);
959 } catch (IOException ioException) {
960 logger.warn("Failed to move cached message to recipient folder: {}", ioException.getMessage());
961 }
962 }
963 return null;
964 }
965
966 // If successful and for all other errors that are not recoverable, delete the cached message
967 cachedMessage.delete();
968 return actions;
969 }
970
971 @Override
972 public void addReceiveHandler(final ReceiveMessageHandler handler, final boolean isWeakListener) {
973 if (isReceivingSynchronous) {
974 throw new IllegalStateException("Already receiving message synchronously.");
975 }
976 synchronized (messageHandlers) {
977 if (isWeakListener) {
978 weakHandlers.add(handler);
979 } else {
980 messageHandlers.add(handler);
981 startReceiveThreadIfRequired();
982 }
983 }
984 }
985
986 private void startReceiveThreadIfRequired() {
987 if (receiveThread != null) {
988 return;
989 }
990 receiveThread = new Thread(() -> {
991 logger.debug("Starting receiving messages");
992 while (!Thread.interrupted()) {
993 try {
994 receiveMessagesInternal(Duration.ofMinutes(1), false, (envelope, e) -> {
995 synchronized (messageHandlers) {
996 Stream.concat(messageHandlers.stream(), weakHandlers.stream()).forEach(h -> {
997 try {
998 h.handleMessage(envelope, e);
999 } catch (Exception ex) {
1000 logger.warn("Message handler failed, ignoring", ex);
1001 }
1002 });
1003 }
1004 });
1005 break;
1006 } catch (IOException e) {
1007 logger.warn("Receiving messages failed, retrying", e);
1008 }
1009 }
1010 logger.debug("Finished receiving messages");
1011 hasCaughtUpWithOldMessages = false;
1012 synchronized (messageHandlers) {
1013 receiveThread = null;
1014
1015 // Check if in the meantime another handler has been registered
1016 if (!messageHandlers.isEmpty()) {
1017 logger.debug("Another handler has been registered, starting receive thread again");
1018 startReceiveThreadIfRequired();
1019 }
1020 }
1021 });
1022
1023 receiveThread.start();
1024 }
1025
1026 @Override
1027 public void removeReceiveHandler(final ReceiveMessageHandler handler) {
1028 final Thread thread;
1029 synchronized (messageHandlers) {
1030 weakHandlers.remove(handler);
1031 messageHandlers.remove(handler);
1032 if (!messageHandlers.isEmpty() || receiveThread == null || isReceivingSynchronous) {
1033 return;
1034 }
1035 thread = receiveThread;
1036 receiveThread = null;
1037 }
1038
1039 stopReceiveThread(thread);
1040 }
1041
1042 private void stopReceiveThread(final Thread thread) {
1043 thread.interrupt();
1044 try {
1045 thread.join();
1046 } catch (InterruptedException ignored) {
1047 }
1048 }
1049
1050 @Override
1051 public boolean isReceiving() {
1052 if (isReceivingSynchronous) {
1053 return true;
1054 }
1055 synchronized (messageHandlers) {
1056 return messageHandlers.size() > 0;
1057 }
1058 }
1059
1060 @Override
1061 public void receiveMessages(Duration timeout, ReceiveMessageHandler handler) throws IOException {
1062 receiveMessages(timeout, true, handler);
1063 }
1064
1065 @Override
1066 public void receiveMessages(ReceiveMessageHandler handler) throws IOException {
1067 receiveMessages(Duration.ofMinutes(1), false, handler);
1068 }
1069
1070 private void receiveMessages(
1071 Duration timeout, boolean returnOnTimeout, ReceiveMessageHandler handler
1072 ) throws IOException {
1073 if (isReceiving()) {
1074 throw new IllegalStateException("Already receiving message.");
1075 }
1076 isReceivingSynchronous = true;
1077 receiveThread = Thread.currentThread();
1078 try {
1079 receiveMessagesInternal(timeout, returnOnTimeout, handler);
1080 } finally {
1081 receiveThread = null;
1082 hasCaughtUpWithOldMessages = false;
1083 isReceivingSynchronous = false;
1084 }
1085 }
1086
1087 private void receiveMessagesInternal(
1088 Duration timeout, boolean returnOnTimeout, ReceiveMessageHandler handler
1089 ) throws IOException {
1090 needsToRetryFailedMessages = true;
1091
1092 // Use a Map here because java Set doesn't have a get method ...
1093 Map<HandleAction, HandleAction> queuedActions = new HashMap<>();
1094
1095 final var signalWebSocket = dependencies.getSignalWebSocket();
1096 final var webSocketStateDisposable = Observable.merge(signalWebSocket.getUnidentifiedWebSocketState(),
1097 signalWebSocket.getWebSocketState())
1098 .subscribeOn(Schedulers.computation())
1099 .observeOn(Schedulers.computation())
1100 .distinctUntilChanged()
1101 .subscribe(this::onWebSocketStateChange);
1102 signalWebSocket.connect();
1103
1104 hasCaughtUpWithOldMessages = false;
1105 var backOffCounter = 0;
1106 final var MAX_BACKOFF_COUNTER = 9;
1107
1108 while (!Thread.interrupted()) {
1109 if (needsToRetryFailedMessages) {
1110 retryFailedReceivedMessages(handler);
1111 needsToRetryFailedMessages = false;
1112 }
1113 SignalServiceEnvelope envelope;
1114 final CachedMessage[] cachedMessage = {null};
1115 final var nowMillis = System.currentTimeMillis();
1116 if (nowMillis - account.getLastReceiveTimestamp() > 60000) {
1117 account.setLastReceiveTimestamp(nowMillis);
1118 }
1119 logger.debug("Checking for new message from server");
1120 try {
1121 var result = signalWebSocket.readOrEmpty(timeout.toMillis(), envelope1 -> {
1122 final var recipientId = envelope1.hasSourceUuid() ? account.getRecipientStore()
1123 .resolveRecipient(envelope1.getSourceAddress()) : null;
1124 // store message on disk, before acknowledging receipt to the server
1125 cachedMessage[0] = account.getMessageCache().cacheMessage(envelope1, recipientId);
1126 });
1127 backOffCounter = 0;
1128
1129 if (result.isPresent()) {
1130 envelope = result.get();
1131 logger.debug("New message received from server");
1132 } else {
1133 logger.debug("Received indicator that server queue is empty");
1134 handleQueuedActions(queuedActions.keySet());
1135 queuedActions.clear();
1136
1137 hasCaughtUpWithOldMessages = true;
1138 synchronized (this) {
1139 this.notifyAll();
1140 }
1141
1142 // Continue to wait another timeout for new messages
1143 continue;
1144 }
1145 } catch (AssertionError e) {
1146 if (e.getCause() instanceof InterruptedException) {
1147 Thread.currentThread().interrupt();
1148 break;
1149 } else {
1150 throw e;
1151 }
1152 } catch (IOException e) {
1153 logger.debug("Pipe unexpectedly unavailable: {}", e.getMessage());
1154 if (e instanceof WebSocketUnavailableException || "Connection closed!".equals(e.getMessage())) {
1155 final var sleepMilliseconds = 100 * (long) Math.pow(2, backOffCounter);
1156 backOffCounter = Math.min(backOffCounter + 1, MAX_BACKOFF_COUNTER);
1157 logger.warn("Connection closed unexpectedly, reconnecting in {} ms", sleepMilliseconds);
1158 try {
1159 Thread.sleep(sleepMilliseconds);
1160 } catch (InterruptedException interruptedException) {
1161 return;
1162 }
1163 hasCaughtUpWithOldMessages = false;
1164 signalWebSocket.connect();
1165 continue;
1166 }
1167 throw e;
1168 } catch (TimeoutException e) {
1169 backOffCounter = 0;
1170 if (returnOnTimeout) return;
1171 continue;
1172 }
1173
1174 final var result = incomingMessageHandler.handleEnvelope(envelope, ignoreAttachments, handler);
1175 for (final var h : result.first()) {
1176 final var existingAction = queuedActions.get(h);
1177 if (existingAction == null) {
1178 queuedActions.put(h, h);
1179 } else {
1180 existingAction.mergeOther(h);
1181 }
1182 }
1183 final var exception = result.second();
1184
1185 if (hasCaughtUpWithOldMessages) {
1186 handleQueuedActions(queuedActions.keySet());
1187 queuedActions.clear();
1188 }
1189 if (cachedMessage[0] != null) {
1190 if (exception instanceof UntrustedIdentityException) {
1191 logger.debug("Keeping message with untrusted identity in message cache");
1192 final var address = ((UntrustedIdentityException) exception).getSender();
1193 final var recipientId = account.getRecipientStore().resolveRecipient(address);
1194 if (!envelope.hasSourceUuid()) {
1195 try {
1196 cachedMessage[0] = account.getMessageCache().replaceSender(cachedMessage[0], recipientId);
1197 } catch (IOException ioException) {
1198 logger.warn("Failed to move cached message to recipient folder: {}",
1199 ioException.getMessage());
1200 }
1201 }
1202 } else {
1203 cachedMessage[0].delete();
1204 }
1205 }
1206 }
1207 handleQueuedActions(queuedActions.keySet());
1208 queuedActions.clear();
1209 dependencies.getSignalWebSocket().disconnect();
1210 webSocketStateDisposable.dispose();
1211 }
1212
1213 private void onWebSocketStateChange(final WebSocketConnectionState s) {
1214 if (s.equals(WebSocketConnectionState.AUTHENTICATION_FAILED)) {
1215 account.setRegistered(false);
1216 try {
1217 close();
1218 } catch (IOException e) {
1219 e.printStackTrace();
1220 }
1221 }
1222 }
1223
1224 @Override
1225 public void setIgnoreAttachments(final boolean ignoreAttachments) {
1226 this.ignoreAttachments = ignoreAttachments;
1227 }
1228
1229 @Override
1230 public boolean hasCaughtUpWithOldMessages() {
1231 return hasCaughtUpWithOldMessages;
1232 }
1233
1234 private void handleQueuedActions(final Collection<HandleAction> queuedActions) {
1235 logger.debug("Handling message actions");
1236 var interrupted = false;
1237 for (var action : queuedActions) {
1238 logger.debug("Executing action {}", action.getClass().getSimpleName());
1239 try {
1240 action.execute(context);
1241 } catch (Throwable e) {
1242 if ((e instanceof AssertionError || e instanceof RuntimeException)
1243 && e.getCause() instanceof InterruptedException) {
1244 interrupted = true;
1245 continue;
1246 }
1247 logger.warn("Message action failed.", e);
1248 }
1249 }
1250 if (interrupted) {
1251 Thread.currentThread().interrupt();
1252 }
1253 }
1254
1255 @Override
1256 public boolean isContactBlocked(final RecipientIdentifier.Single recipient) {
1257 final RecipientId recipientId;
1258 try {
1259 recipientId = recipientHelper.resolveRecipient(recipient);
1260 } catch (IOException | UnregisteredRecipientException e) {
1261 return false;
1262 }
1263 return contactHelper.isContactBlocked(recipientId);
1264 }
1265
1266 @Override
1267 public void sendContacts() throws IOException {
1268 syncHelper.sendContacts();
1269 }
1270
1271 @Override
1272 public List<Pair<RecipientAddress, Contact>> getContacts() {
1273 return account.getContactStore()
1274 .getContacts()
1275 .stream()
1276 .map(p -> new Pair<>(account.getRecipientStore().resolveRecipientAddress(p.first()), p.second()))
1277 .toList();
1278 }
1279
1280 @Override
1281 public String getContactOrProfileName(RecipientIdentifier.Single recipient) {
1282 final RecipientId recipientId;
1283 try {
1284 recipientId = recipientHelper.resolveRecipient(recipient);
1285 } catch (IOException | UnregisteredRecipientException e) {
1286 return null;
1287 }
1288
1289 final var contact = account.getContactStore().getContact(recipientId);
1290 if (contact != null && !Util.isEmpty(contact.getName())) {
1291 return contact.getName();
1292 }
1293
1294 final var profile = profileHelper.getRecipientProfile(recipientId);
1295 if (profile != null) {
1296 return profile.getDisplayName();
1297 }
1298
1299 return null;
1300 }
1301
1302 @Override
1303 public Group getGroup(GroupId groupId) {
1304 return toGroup(groupHelper.getGroup(groupId));
1305 }
1306
1307 private GroupInfo getGroupInfo(GroupId groupId) {
1308 return groupHelper.getGroup(groupId);
1309 }
1310
1311 @Override
1312 public List<Identity> getIdentities() {
1313 return account.getIdentityKeyStore().getIdentities().stream().map(this::toIdentity).toList();
1314 }
1315
1316 private Identity toIdentity(final IdentityInfo identityInfo) {
1317 if (identityInfo == null) {
1318 return null;
1319 }
1320
1321 final var address = account.getRecipientStore().resolveRecipientAddress(identityInfo.getRecipientId());
1322 final var scannableFingerprint = identityHelper.computeSafetyNumberForScanning(identityInfo.getRecipientId(),
1323 identityInfo.getIdentityKey());
1324 return new Identity(address,
1325 identityInfo.getIdentityKey(),
1326 identityHelper.computeSafetyNumber(identityInfo.getRecipientId(), identityInfo.getIdentityKey()),
1327 scannableFingerprint == null ? null : scannableFingerprint.getSerialized(),
1328 identityInfo.getTrustLevel(),
1329 identityInfo.getDateAdded());
1330 }
1331
1332 @Override
1333 public List<Identity> getIdentities(RecipientIdentifier.Single recipient) {
1334 IdentityInfo identity;
1335 try {
1336 identity = account.getIdentityKeyStore().getIdentity(recipientHelper.resolveRecipient(recipient));
1337 } catch (IOException | UnregisteredRecipientException e) {
1338 identity = null;
1339 }
1340 return identity == null ? List.of() : List.of(toIdentity(identity));
1341 }
1342
1343 /**
1344 * Trust this the identity with this fingerprint
1345 *
1346 * @param recipient account of the identity
1347 * @param fingerprint Fingerprint
1348 */
1349 @Override
1350 public boolean trustIdentityVerified(
1351 RecipientIdentifier.Single recipient, byte[] fingerprint
1352 ) throws UnregisteredRecipientException {
1353 RecipientId recipientId;
1354 try {
1355 recipientId = recipientHelper.resolveRecipient(recipient);
1356 } catch (IOException e) {
1357 return false;
1358 }
1359 final var updated = identityHelper.trustIdentityVerified(recipientId, fingerprint);
1360 if (updated && this.isReceiving()) {
1361 needsToRetryFailedMessages = true;
1362 }
1363 return updated;
1364 }
1365
1366 /**
1367 * Trust this the identity with this safety number
1368 *
1369 * @param recipient account of the identity
1370 * @param safetyNumber Safety number
1371 */
1372 @Override
1373 public boolean trustIdentityVerifiedSafetyNumber(
1374 RecipientIdentifier.Single recipient, String safetyNumber
1375 ) throws UnregisteredRecipientException {
1376 RecipientId recipientId;
1377 try {
1378 recipientId = recipientHelper.resolveRecipient(recipient);
1379 } catch (IOException e) {
1380 return false;
1381 }
1382 final var updated = identityHelper.trustIdentityVerifiedSafetyNumber(recipientId, safetyNumber);
1383 if (updated && this.isReceiving()) {
1384 needsToRetryFailedMessages = true;
1385 }
1386 return updated;
1387 }
1388
1389 /**
1390 * Trust this the identity with this scannable safety number
1391 *
1392 * @param recipient account of the identity
1393 * @param safetyNumber Scannable safety number
1394 */
1395 @Override
1396 public boolean trustIdentityVerifiedSafetyNumber(
1397 RecipientIdentifier.Single recipient, byte[] safetyNumber
1398 ) throws UnregisteredRecipientException {
1399 RecipientId recipientId;
1400 try {
1401 recipientId = recipientHelper.resolveRecipient(recipient);
1402 } catch (IOException e) {
1403 return false;
1404 }
1405 final var updated = identityHelper.trustIdentityVerifiedSafetyNumber(recipientId, safetyNumber);
1406 if (updated && this.isReceiving()) {
1407 needsToRetryFailedMessages = true;
1408 }
1409 return updated;
1410 }
1411
1412 /**
1413 * Trust all keys of this identity without verification
1414 *
1415 * @param recipient account of the identity
1416 */
1417 @Override
1418 public boolean trustIdentityAllKeys(RecipientIdentifier.Single recipient) throws UnregisteredRecipientException {
1419 RecipientId recipientId;
1420 try {
1421 recipientId = recipientHelper.resolveRecipient(recipient);
1422 } catch (IOException e) {
1423 return false;
1424 }
1425 final var updated = identityHelper.trustIdentityAllKeys(recipientId);
1426 if (updated && this.isReceiving()) {
1427 needsToRetryFailedMessages = true;
1428 }
1429 return updated;
1430 }
1431
1432 @Override
1433 public void addClosedListener(final Runnable listener) {
1434 synchronized (closedListeners) {
1435 closedListeners.add(listener);
1436 }
1437 }
1438
1439 private void handleIdentityFailure(
1440 final RecipientId recipientId,
1441 final org.whispersystems.signalservice.api.messages.SendMessageResult.IdentityFailure identityFailure
1442 ) {
1443 this.identityHelper.handleIdentityFailure(recipientId, identityFailure);
1444 }
1445
1446 @Override
1447 public void close() throws IOException {
1448 Thread thread;
1449 synchronized (messageHandlers) {
1450 weakHandlers.clear();
1451 messageHandlers.clear();
1452 thread = receiveThread;
1453 receiveThread = null;
1454 }
1455 if (thread != null) {
1456 stopReceiveThread(thread);
1457 }
1458 executor.shutdown();
1459
1460 dependencies.getSignalWebSocket().disconnect();
1461
1462 synchronized (closedListeners) {
1463 closedListeners.forEach(Runnable::run);
1464 closedListeners.clear();
1465 }
1466
1467 if (account != null) {
1468 account.close();
1469 }
1470 account = null;
1471 }
1472 }