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