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