2 Copyright (C) 2015-2022 AsamK and contributors
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.
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.
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/>.
17 package org
.asamk
.signal
.manager
.internal
;
19 import org
.asamk
.signal
.manager
.Manager
;
20 import org
.asamk
.signal
.manager
.api
.AlreadyReceivingException
;
21 import org
.asamk
.signal
.manager
.api
.AttachmentInvalidException
;
22 import org
.asamk
.signal
.manager
.api
.CaptchaRejectedException
;
23 import org
.asamk
.signal
.manager
.api
.CaptchaRequiredException
;
24 import org
.asamk
.signal
.manager
.api
.Configuration
;
25 import org
.asamk
.signal
.manager
.api
.Device
;
26 import org
.asamk
.signal
.manager
.api
.DeviceLimitExceededException
;
27 import org
.asamk
.signal
.manager
.api
.DeviceLinkUrl
;
28 import org
.asamk
.signal
.manager
.api
.Group
;
29 import org
.asamk
.signal
.manager
.api
.GroupId
;
30 import org
.asamk
.signal
.manager
.api
.GroupInviteLinkUrl
;
31 import org
.asamk
.signal
.manager
.api
.GroupNotFoundException
;
32 import org
.asamk
.signal
.manager
.api
.GroupSendingNotAllowedException
;
33 import org
.asamk
.signal
.manager
.api
.Identity
;
34 import org
.asamk
.signal
.manager
.api
.IdentityVerificationCode
;
35 import org
.asamk
.signal
.manager
.api
.InactiveGroupLinkException
;
36 import org
.asamk
.signal
.manager
.api
.IncorrectPinException
;
37 import org
.asamk
.signal
.manager
.api
.InvalidDeviceLinkException
;
38 import org
.asamk
.signal
.manager
.api
.InvalidStickerException
;
39 import org
.asamk
.signal
.manager
.api
.InvalidUsernameException
;
40 import org
.asamk
.signal
.manager
.api
.LastGroupAdminException
;
41 import org
.asamk
.signal
.manager
.api
.Message
;
42 import org
.asamk
.signal
.manager
.api
.MessageEnvelope
;
43 import org
.asamk
.signal
.manager
.api
.MessageEnvelope
.Sync
.MessageRequestResponse
;
44 import org
.asamk
.signal
.manager
.api
.NonNormalizedPhoneNumberException
;
45 import org
.asamk
.signal
.manager
.api
.NotAGroupMemberException
;
46 import org
.asamk
.signal
.manager
.api
.NotPrimaryDeviceException
;
47 import org
.asamk
.signal
.manager
.api
.Pair
;
48 import org
.asamk
.signal
.manager
.api
.PendingAdminApprovalException
;
49 import org
.asamk
.signal
.manager
.api
.PhoneNumberSharingMode
;
50 import org
.asamk
.signal
.manager
.api
.PinLockedException
;
51 import org
.asamk
.signal
.manager
.api
.Profile
;
52 import org
.asamk
.signal
.manager
.api
.RateLimitException
;
53 import org
.asamk
.signal
.manager
.api
.ReceiveConfig
;
54 import org
.asamk
.signal
.manager
.api
.Recipient
;
55 import org
.asamk
.signal
.manager
.api
.RecipientIdentifier
;
56 import org
.asamk
.signal
.manager
.api
.SendGroupMessageResults
;
57 import org
.asamk
.signal
.manager
.api
.SendMessageResult
;
58 import org
.asamk
.signal
.manager
.api
.SendMessageResults
;
59 import org
.asamk
.signal
.manager
.api
.StickerPackId
;
60 import org
.asamk
.signal
.manager
.api
.StickerPackInvalidException
;
61 import org
.asamk
.signal
.manager
.api
.StickerPackUrl
;
62 import org
.asamk
.signal
.manager
.api
.TextStyle
;
63 import org
.asamk
.signal
.manager
.api
.TypingAction
;
64 import org
.asamk
.signal
.manager
.api
.UnregisteredRecipientException
;
65 import org
.asamk
.signal
.manager
.api
.UpdateGroup
;
66 import org
.asamk
.signal
.manager
.api
.UpdateProfile
;
67 import org
.asamk
.signal
.manager
.api
.UserStatus
;
68 import org
.asamk
.signal
.manager
.api
.UsernameLinkUrl
;
69 import org
.asamk
.signal
.manager
.api
.UsernameStatus
;
70 import org
.asamk
.signal
.manager
.api
.VerificationMethodNotAvailableException
;
71 import org
.asamk
.signal
.manager
.config
.ServiceConfig
;
72 import org
.asamk
.signal
.manager
.config
.ServiceEnvironmentConfig
;
73 import org
.asamk
.signal
.manager
.helper
.AccountFileUpdater
;
74 import org
.asamk
.signal
.manager
.helper
.Context
;
75 import org
.asamk
.signal
.manager
.helper
.RecipientHelper
.RegisteredUser
;
76 import org
.asamk
.signal
.manager
.jobs
.RefreshRecipientsJob
;
77 import org
.asamk
.signal
.manager
.jobs
.SyncStorageJob
;
78 import org
.asamk
.signal
.manager
.storage
.AttachmentStore
;
79 import org
.asamk
.signal
.manager
.storage
.AvatarStore
;
80 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
81 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfo
;
82 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityInfo
;
83 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientAddress
;
84 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
85 import org
.asamk
.signal
.manager
.storage
.stickerPacks
.JsonStickerPack
;
86 import org
.asamk
.signal
.manager
.storage
.stickerPacks
.StickerPackStore
;
87 import org
.asamk
.signal
.manager
.storage
.stickers
.StickerPack
;
88 import org
.asamk
.signal
.manager
.util
.AttachmentUtils
;
89 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
90 import org
.asamk
.signal
.manager
.util
.MimeUtils
;
91 import org
.asamk
.signal
.manager
.util
.StickerUtils
;
92 import org
.signal
.libsignal
.protocol
.InvalidMessageException
;
93 import org
.signal
.libsignal
.usernames
.BaseUsernameException
;
94 import org
.slf4j
.Logger
;
95 import org
.slf4j
.LoggerFactory
;
96 import org
.whispersystems
.signalservice
.api
.SignalSessionLock
;
97 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachment
;
98 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
99 import org
.whispersystems
.signalservice
.api
.messages
.SignalServicePreview
;
100 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
101 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceTypingMessage
;
102 import org
.whispersystems
.signalservice
.api
.push
.ServiceId
;
103 import org
.whispersystems
.signalservice
.api
.push
.ServiceId
.ACI
;
104 import org
.whispersystems
.signalservice
.api
.push
.ServiceId
.PNI
;
105 import org
.whispersystems
.signalservice
.api
.push
.ServiceIdType
;
106 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.CdsiResourceExhaustedException
;
107 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.UsernameMalformedException
;
108 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.UsernameTakenException
;
109 import org
.whispersystems
.signalservice
.api
.util
.DeviceNameUtil
;
110 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
111 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
112 import org
.whispersystems
.signalservice
.api
.util
.StreamDetails
;
113 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
114 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
116 import java
.io
.ByteArrayInputStream
;
118 import java
.io
.FileNotFoundException
;
119 import java
.io
.IOException
;
120 import java
.io
.InputStream
;
121 import java
.nio
.charset
.StandardCharsets
;
122 import java
.time
.Duration
;
123 import java
.util
.ArrayList
;
124 import java
.util
.Collection
;
125 import java
.util
.HashMap
;
126 import java
.util
.HashSet
;
127 import java
.util
.List
;
128 import java
.util
.Map
;
129 import java
.util
.Objects
;
130 import java
.util
.Optional
;
131 import java
.util
.Set
;
132 import java
.util
.concurrent
.ExecutorService
;
133 import java
.util
.concurrent
.Executors
;
134 import java
.util
.concurrent
.TimeUnit
;
135 import java
.util
.concurrent
.atomic
.AtomicInteger
;
136 import java
.util
.concurrent
.locks
.ReentrantLock
;
137 import java
.util
.function
.Function
;
138 import java
.util
.stream
.Collectors
;
139 import java
.util
.stream
.Stream
;
141 import io
.reactivex
.rxjava3
.disposables
.CompositeDisposable
;
142 import io
.reactivex
.rxjava3
.schedulers
.Schedulers
;
144 public class ManagerImpl
implements Manager
{
146 private static final Logger logger
= LoggerFactory
.getLogger(ManagerImpl
.class);
148 private SignalAccount account
;
149 private final SignalDependencies dependencies
;
150 private final Context context
;
152 private final ExecutorService executor
= Executors
.newCachedThreadPool();
154 private Thread receiveThread
;
155 private boolean isReceivingSynchronous
;
156 private final Set
<ReceiveMessageHandler
> weakHandlers
= new HashSet
<>();
157 private final Set
<ReceiveMessageHandler
> messageHandlers
= new HashSet
<>();
158 private final List
<Runnable
> closedListeners
= new ArrayList
<>();
159 private final List
<Runnable
> addressChangedListeners
= new ArrayList
<>();
160 private final CompositeDisposable disposable
= new CompositeDisposable();
163 SignalAccount account
,
164 PathConfig pathConfig
,
165 AccountFileUpdater accountFileUpdater
,
166 ServiceEnvironmentConfig serviceEnvironmentConfig
,
169 this.account
= account
;
171 final var sessionLock
= new SignalSessionLock() {
172 private final ReentrantLock LEGACY_LOCK
= new ReentrantLock();
175 public Lock
acquire() {
177 return LEGACY_LOCK
::unlock
;
180 this.dependencies
= new SignalDependencies(serviceEnvironmentConfig
,
182 account
.getCredentialsProvider(),
183 account
.getSignalServiceDataStore(),
186 final var avatarStore
= new AvatarStore(pathConfig
.avatarsPath());
187 final var attachmentStore
= new AttachmentStore(pathConfig
.attachmentsPath());
188 final var stickerPackStore
= new StickerPackStore(pathConfig
.stickerPacksPath());
190 this.context
= new Context(account
, new AccountFileUpdater() {
192 public void updateAccountIdentifiers(final String number
, final ACI aci
) {
193 accountFileUpdater
.updateAccountIdentifiers(number
, aci
);
194 synchronized (addressChangedListeners
) {
195 addressChangedListeners
.forEach(Runnable
::run
);
200 public void removeAccount() {
201 accountFileUpdater
.removeAccount();
203 }, dependencies
, avatarStore
, attachmentStore
, stickerPackStore
);
204 this.context
.getAccountHelper().setUnregisteredListener(this::close
);
205 this.context
.getReceiveHelper().setAuthenticationFailureListener(this::close
);
206 this.context
.getReceiveHelper().setCaughtUpWithOldMessagesListener(() -> {
207 synchronized (this) {
211 disposable
.add(account
.getIdentityKeyStore()
212 .getIdentityChanges()
213 .observeOn(Schedulers
.from(executor
))
214 .subscribe(serviceId
-> {
215 logger
.trace("Archiving old sessions for {}", serviceId
);
216 account
.getAccountData(ServiceIdType
.ACI
).getSessionStore().archiveSessions(serviceId
);
217 account
.getAccountData(ServiceIdType
.PNI
).getSessionStore().archiveSessions(serviceId
);
218 account
.getSenderKeyStore().deleteSharedWith(serviceId
);
219 final var recipientId
= account
.getRecipientResolver().resolveRecipient(serviceId
);
220 final var profile
= account
.getProfileStore().getProfile(recipientId
);
221 if (profile
!= null) {
222 account
.getProfileStore()
223 .storeProfile(recipientId
,
224 Profile
.newBuilder(profile
)
225 .withUnidentifiedAccessMode(Profile
.UnidentifiedAccessMode
.UNKNOWN
)
226 .withLastUpdateTimestamp(0)
233 public String
getSelfNumber() {
234 return account
.getNumber();
237 public void checkAccountState() throws IOException
{
238 context
.getAccountHelper().checkAccountState();
239 final var lastRecipientsRefresh
= account
.getLastRecipientsRefresh();
240 if (lastRecipientsRefresh
== null
241 || lastRecipientsRefresh
< System
.currentTimeMillis() - TimeUnit
.DAYS
.toMillis(1)) {
242 context
.getJobExecutor().enqueueJob(new RefreshRecipientsJob());
243 context
.getAccountHelper().checkWhoAmiI();
248 public Map
<String
, UserStatus
> getUserStatus(Set
<String
> numbers
) throws IOException
, RateLimitException
{
249 final var canonicalizedNumbers
= numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
251 final var canonicalizedNumber
= PhoneNumberFormatter
.formatNumber(n
, account
.getNumber());
252 if (!canonicalizedNumber
.equals(n
)) {
253 logger
.debug("Normalized number {} to {}.", n
, canonicalizedNumber
);
255 return canonicalizedNumber
;
256 } catch (InvalidNumberException e
) {
261 // Note "registeredUsers" has no optionals. It only gives us info on users who are registered
262 final var canonicalizedNumbersSet
= canonicalizedNumbers
.values()
264 .filter(s
-> !s
.isEmpty())
265 .collect(Collectors
.toSet());
267 final Map
<String
, RegisteredUser
> registeredUsers
;
269 registeredUsers
= context
.getRecipientHelper().getRegisteredUsers(canonicalizedNumbersSet
);
270 } catch (CdsiResourceExhaustedException e
) {
271 logger
.debug("CDSI resource exhausted: {}", e
.getMessage());
272 throw new RateLimitException(System
.currentTimeMillis() + e
.getRetryAfterSeconds() * 1000L);
275 return numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
276 final var number
= canonicalizedNumbers
.get(n
);
277 final var user
= registeredUsers
.get(number
);
278 final var serviceId
= user
== null ?
null : user
.getServiceId();
279 final var profile
= serviceId
== null
281 : context
.getProfileHelper()
282 .getRecipientProfile(account
.getRecipientResolver().resolveRecipient(serviceId
));
283 return new UserStatus(number
.isEmpty() ?
null : number
,
284 serviceId
== null ?
null : serviceId
.getRawUuid(),
286 && profile
.getUnidentifiedAccessMode() == Profile
.UnidentifiedAccessMode
.UNRESTRICTED
);
291 public Map
<String
, UsernameStatus
> getUsernameStatus(Set
<String
> usernames
) {
292 final var registeredUsers
= new HashMap
<String
, RecipientAddress
>();
293 for (final var username
: usernames
) {
295 final var recipientId
= context
.getRecipientHelper().resolveRecipientByUsernameOrLink(username
, true);
296 final var address
= account
.getRecipientAddressResolver().resolveRecipientAddress(recipientId
);
297 registeredUsers
.put(username
, address
);
298 } catch (UnregisteredRecipientException e
) {
303 return usernames
.stream().collect(Collectors
.toMap(n
-> n
, username
-> {
304 final var user
= registeredUsers
.get(username
);
305 final var serviceId
= user
== null ?
null : user
.serviceId().orElse(null);
306 final var profile
= serviceId
== null
308 : context
.getProfileHelper()
309 .getRecipientProfile(account
.getRecipientResolver().resolveRecipient(serviceId
));
310 return new UsernameStatus(username
,
311 serviceId
== null ?
null : serviceId
.getRawUuid(),
313 && profile
.getUnidentifiedAccessMode() == Profile
.UnidentifiedAccessMode
.UNRESTRICTED
);
318 public void updateAccountAttributes(
320 Boolean unrestrictedUnidentifiedSender
,
321 final Boolean discoverableByNumber
,
322 final Boolean numberSharing
323 ) throws IOException
{
324 if (deviceName
!= null) {
325 context
.getAccountHelper().setDeviceName(deviceName
);
327 if (unrestrictedUnidentifiedSender
!= null) {
328 account
.setUnrestrictedUnidentifiedAccess(unrestrictedUnidentifiedSender
);
330 if (discoverableByNumber
!= null) {
331 account
.getConfigurationStore().setPhoneNumberUnlisted(!discoverableByNumber
);
333 if (numberSharing
!= null) {
334 account
.getConfigurationStore()
335 .setPhoneNumberSharingMode(numberSharing
336 ? PhoneNumberSharingMode
.EVERYBODY
337 : PhoneNumberSharingMode
.NOBODY
);
339 context
.getAccountHelper().updateAccountAttributes();
340 context
.getAccountHelper().checkWhoAmiI();
344 public Configuration
getConfiguration() {
345 final var configurationStore
= account
.getConfigurationStore();
346 return Configuration
.from(configurationStore
);
350 public void updateConfiguration(Configuration configuration
) {
351 final var configurationStore
= account
.getConfigurationStore();
352 if (configuration
.readReceipts().isPresent()) {
353 configurationStore
.setReadReceipts(configuration
.readReceipts().get());
355 if (configuration
.unidentifiedDeliveryIndicators().isPresent()) {
356 configurationStore
.setUnidentifiedDeliveryIndicators(configuration
.unidentifiedDeliveryIndicators().get());
358 if (configuration
.typingIndicators().isPresent()) {
359 configurationStore
.setTypingIndicators(configuration
.typingIndicators().get());
361 if (configuration
.linkPreviews().isPresent()) {
362 configurationStore
.setLinkPreviews(configuration
.linkPreviews().get());
364 context
.getSyncHelper().sendConfigurationMessage();
369 public void updateProfile(UpdateProfile updateProfile
) throws IOException
{
370 context
.getProfileHelper()
371 .setProfile(updateProfile
.getGivenName(),
372 updateProfile
.getFamilyName(),
373 updateProfile
.getAbout(),
374 updateProfile
.getAboutEmoji(),
375 updateProfile
.isDeleteAvatar()
377 : updateProfile
.getAvatar() == null ?
null : Optional
.of(updateProfile
.getAvatar()),
378 updateProfile
.getMobileCoinAddress());
379 context
.getSyncHelper().sendSyncFetchProfileMessage();
382 void refreshCurrentUsername() throws IOException
, BaseUsernameException
{
383 context
.getAccountHelper().refreshCurrentUsername();
387 public String
getUsername() {
388 return account
.getUsername();
392 public UsernameLinkUrl
getUsernameLink() {
393 return new UsernameLinkUrl(account
.getUsernameLink());
397 public void setUsername(final String username
) throws IOException
, InvalidUsernameException
{
399 if (username
.contains(".")) {
400 context
.getAccountHelper().reserveExactUsername(username
);
402 context
.getAccountHelper().reserveUsernameFromNickname(username
);
404 } catch (UsernameMalformedException e
) {
405 throw new InvalidUsernameException("Username is malformed", e
);
406 } catch (UsernameTakenException e
) {
407 throw new InvalidUsernameException("Username is already registered", e
);
408 } catch (BaseUsernameException e
) {
409 throw new InvalidUsernameException(e
.getMessage() + " (" + e
.getClass().getSimpleName() + ")", e
);
414 public void deleteUsername() throws IOException
{
415 context
.getAccountHelper().deleteUsername();
419 public void startChangeNumber(
421 boolean voiceVerification
,
423 ) throws RateLimitException
, IOException
, CaptchaRequiredException
, NonNormalizedPhoneNumberException
, NotPrimaryDeviceException
, VerificationMethodNotAvailableException
{
424 if (!account
.isPrimaryDevice()) {
425 throw new NotPrimaryDeviceException();
427 context
.getAccountHelper().startChangeNumber(newNumber
, voiceVerification
, captcha
);
431 public void finishChangeNumber(
433 String verificationCode
,
435 ) throws IncorrectPinException
, PinLockedException
, IOException
, NotPrimaryDeviceException
{
436 if (!account
.isPrimaryDevice()) {
437 throw new NotPrimaryDeviceException();
439 context
.getAccountHelper().finishChangeNumber(newNumber
, verificationCode
, pin
);
443 public void unregister() throws IOException
{
444 context
.getAccountHelper().unregister();
448 public void deleteAccount() throws IOException
{
449 context
.getAccountHelper().deleteAccount();
453 public void submitRateLimitRecaptchaChallenge(
456 ) throws IOException
, CaptchaRejectedException
{
457 captcha
= captcha
== null ?
null : captcha
.replace("signalcaptcha://", "");
460 dependencies
.getAccountManager().submitRateLimitRecaptchaChallenge(challenge
, captcha
);
461 } catch (org
.whispersystems
.signalservice
.internal
.push
.exceptions
.CaptchaRejectedException ignored
) {
462 throw new CaptchaRejectedException();
467 public List
<Device
> getLinkedDevices() throws IOException
{
468 var devices
= dependencies
.getAccountManager().getDevices();
469 account
.setMultiDevice(devices
.size() > 1);
470 var identityKey
= account
.getAciIdentityKeyPair().getPrivateKey();
471 return devices
.stream().map(d
-> {
472 String deviceName
= d
.getName();
473 if (deviceName
!= null) {
475 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
476 } catch (IOException e
) {
477 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
480 return new Device(d
.getId(),
484 d
.getId() == account
.getDeviceId());
489 public void removeLinkedDevices(int deviceId
) throws IOException
, NotPrimaryDeviceException
{
490 if (!account
.isPrimaryDevice()) {
491 throw new NotPrimaryDeviceException();
493 context
.getAccountHelper().removeLinkedDevices(deviceId
);
497 public void addDeviceLink(DeviceLinkUrl linkUrl
) throws IOException
, InvalidDeviceLinkException
, NotPrimaryDeviceException
, DeviceLimitExceededException
{
498 if (!account
.isPrimaryDevice()) {
499 throw new NotPrimaryDeviceException();
501 context
.getAccountHelper().addDevice(linkUrl
);
505 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, NotPrimaryDeviceException
{
506 if (!account
.isPrimaryDevice()) {
507 throw new NotPrimaryDeviceException();
509 if (pin
.isPresent()) {
510 context
.getAccountHelper().setRegistrationPin(pin
.get());
512 context
.getAccountHelper().removeRegistrationPin();
516 void refreshPreKeys() throws IOException
{
517 context
.getPreKeyHelper().refreshPreKeysIfNecessary();
521 public List
<Group
> getGroups() {
522 return context
.getGroupHelper().getGroups().stream().map(this::toGroup
).toList();
525 private Group
toGroup(final GroupInfo groupInfo
) {
526 if (groupInfo
== null) {
530 return Group
.from(groupInfo
, account
.getRecipientAddressResolver(), account
.getSelfRecipientId());
534 public SendGroupMessageResults
quitGroup(
536 Set
<RecipientIdentifier
.Single
> groupAdmins
537 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, LastGroupAdminException
, UnregisteredRecipientException
{
538 final var newAdmins
= context
.getRecipientHelper().resolveRecipients(groupAdmins
);
539 return context
.getGroupHelper().quitGroup(groupId
, newAdmins
);
543 public void deleteGroup(GroupId groupId
) throws IOException
{
544 final var group
= context
.getGroupHelper().getGroup(groupId
);
545 if (group
.isMember(account
.getSelfRecipientId())) {
546 throw new IOException(
547 "The local group information cannot be removed, as the user is still a member of the group");
549 context
.getGroupHelper().deleteGroup(groupId
);
553 public Pair
<GroupId
, SendGroupMessageResults
> createGroup(
555 Set
<RecipientIdentifier
.Single
> members
,
557 ) throws IOException
, AttachmentInvalidException
, UnregisteredRecipientException
{
558 return context
.getGroupHelper()
560 members
== null ?
null : context
.getRecipientHelper().resolveRecipients(members
),
565 public SendGroupMessageResults
updateGroup(
566 final GroupId groupId
,
567 final UpdateGroup updateGroup
568 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
{
569 return context
.getGroupHelper()
570 .updateGroup(groupId
,
571 updateGroup
.getName(),
572 updateGroup
.getDescription(),
573 updateGroup
.getMembers() == null
575 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getMembers()),
576 updateGroup
.getRemoveMembers() == null
578 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getRemoveMembers()),
579 updateGroup
.getAdmins() == null
581 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getAdmins()),
582 updateGroup
.getRemoveAdmins() == null
584 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getRemoveAdmins()),
585 updateGroup
.getBanMembers() == null
587 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getBanMembers()),
588 updateGroup
.getUnbanMembers() == null
590 : context
.getRecipientHelper().resolveRecipients(updateGroup
.getUnbanMembers()),
591 updateGroup
.isResetGroupLink(),
592 updateGroup
.getGroupLinkState(),
593 updateGroup
.getAddMemberPermission(),
594 updateGroup
.getEditDetailsPermission(),
595 updateGroup
.getAvatarFile(),
596 updateGroup
.getExpirationTimer(),
597 updateGroup
.getIsAnnouncementGroup());
601 public Pair
<GroupId
, SendGroupMessageResults
> joinGroup(
602 GroupInviteLinkUrl inviteLinkUrl
603 ) throws IOException
, InactiveGroupLinkException
, PendingAdminApprovalException
{
604 return context
.getGroupHelper().joinGroup(inviteLinkUrl
);
607 private SendMessageResults
sendMessage(
608 SignalServiceDataMessage
.Builder messageBuilder
,
609 Set
<RecipientIdentifier
> recipients
,
611 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
612 return sendMessage(messageBuilder
, recipients
, notifySelf
, Optional
.empty());
615 private SendMessageResults
sendMessage(
616 SignalServiceDataMessage
.Builder messageBuilder
,
617 Set
<RecipientIdentifier
> recipients
,
619 Optional
<Long
> editTargetTimestamp
620 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
621 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
622 long timestamp
= System
.currentTimeMillis();
623 messageBuilder
.withTimestamp(timestamp
);
624 for (final var recipient
: recipients
) {
625 if (recipient
instanceof RecipientIdentifier
.NoteToSelf
|| (
626 recipient
instanceof RecipientIdentifier
.Single single
627 && new RecipientAddress(single
.toPartialRecipientAddress()).matches(account
.getSelfRecipientAddress())
629 final var result
= notifySelf
630 ? context
.getSendHelper()
631 .sendMessage(messageBuilder
, account
.getSelfRecipientId(), editTargetTimestamp
)
632 : context
.getSendHelper().sendSelfMessage(messageBuilder
, editTargetTimestamp
);
633 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
634 } else if (recipient
instanceof RecipientIdentifier
.Single single
) {
636 final var recipientId
= context
.getRecipientHelper().resolveRecipient(single
);
637 final var result
= context
.getSendHelper()
638 .sendMessage(messageBuilder
, recipientId
, editTargetTimestamp
);
639 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
640 } catch (UnregisteredRecipientException e
) {
641 results
.put(recipient
,
642 List
.of(SendMessageResult
.unregisteredFailure(single
.toPartialRecipientAddress())));
644 } else if (recipient
instanceof RecipientIdentifier
.Group group
) {
645 final var result
= context
.getSendHelper()
646 .sendAsGroupMessage(messageBuilder
, group
.groupId(), notifySelf
, editTargetTimestamp
);
647 results
.put(recipient
, result
.stream().map(this::toSendMessageResult
).toList());
650 return new SendMessageResults(timestamp
, results
);
653 private SendMessageResult
toSendMessageResult(final org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult result
) {
654 return SendMessageResult
.from(result
, account
.getRecipientResolver(), account
.getRecipientAddressResolver());
657 private SendMessageResults
sendTypingMessage(
658 SignalServiceTypingMessage
.Action action
,
659 Set
<RecipientIdentifier
> recipients
660 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
661 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
662 final var timestamp
= System
.currentTimeMillis();
663 for (var recipient
: recipients
) {
664 if (recipient
instanceof RecipientIdentifier
.Single single
) {
665 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.empty());
667 final var recipientId
= context
.getRecipientHelper().resolveRecipient(single
);
668 final var result
= context
.getSendHelper().sendTypingMessage(message
, recipientId
);
669 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
670 } catch (UnregisteredRecipientException e
) {
671 results
.put(recipient
,
672 List
.of(SendMessageResult
.unregisteredFailure(single
.toPartialRecipientAddress())));
674 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
675 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId();
676 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.of(groupId
.serialize()));
677 final var result
= context
.getSendHelper().sendGroupTypingMessage(message
, groupId
);
678 results
.put(recipient
, result
.stream().map(this::toSendMessageResult
).toList());
681 return new SendMessageResults(timestamp
, results
);
685 public SendMessageResults
sendTypingMessage(
687 Set
<RecipientIdentifier
> recipients
688 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
689 return sendTypingMessage(action
.toSignalService(), recipients
);
693 public SendMessageResults
sendReadReceipt(RecipientIdentifier
.Single sender
, List
<Long
> messageIds
) {
694 final var timestamp
= System
.currentTimeMillis();
695 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.READ
,
699 return sendReceiptMessage(sender
, timestamp
, receiptMessage
);
703 public SendMessageResults
sendViewedReceipt(RecipientIdentifier
.Single sender
, List
<Long
> messageIds
) {
704 final var timestamp
= System
.currentTimeMillis();
705 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.VIEWED
,
709 return sendReceiptMessage(sender
, timestamp
, receiptMessage
);
712 private SendMessageResults
sendReceiptMessage(
713 final RecipientIdentifier
.Single sender
,
714 final long timestamp
,
715 final SignalServiceReceiptMessage receiptMessage
718 final var recipientId
= context
.getRecipientHelper().resolveRecipient(sender
);
719 final var result
= context
.getSendHelper().sendReceiptMessage(receiptMessage
, recipientId
);
721 final var serviceId
= account
.getRecipientAddressResolver()
722 .resolveRecipientAddress(recipientId
)
724 if (serviceId
.isPresent()) {
725 context
.getSyncHelper().sendSyncReceiptMessage(serviceId
.get(), receiptMessage
);
727 return new SendMessageResults(timestamp
, Map
.of(sender
, List
.of(toSendMessageResult(result
))));
728 } catch (UnregisteredRecipientException e
) {
729 return new SendMessageResults(timestamp
,
730 Map
.of(sender
, List
.of(SendMessageResult
.unregisteredFailure(sender
.toPartialRecipientAddress()))));
735 public SendMessageResults
sendMessage(
737 Set
<RecipientIdentifier
> recipients
,
739 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
, InvalidStickerException
{
740 final var selfProfile
= context
.getProfileHelper().getSelfProfile();
741 if (selfProfile
== null || selfProfile
.getDisplayName().isEmpty()) {
743 "No profile name set. When sending a message it's recommended to set a profile name with the updateProfile command. This may become mandatory in the future.");
745 final var messageBuilder
= SignalServiceDataMessage
.newBuilder();
746 applyMessage(messageBuilder
, message
);
747 return sendMessage(messageBuilder
, recipients
, notifySelf
);
751 public SendMessageResults
sendEditMessage(
753 Set
<RecipientIdentifier
> recipients
,
754 long editTargetTimestamp
755 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
, InvalidStickerException
{
756 final var messageBuilder
= SignalServiceDataMessage
.newBuilder();
757 applyMessage(messageBuilder
, message
);
758 return sendMessage(messageBuilder
, recipients
, false, Optional
.of(editTargetTimestamp
));
761 private void applyMessage(
762 final SignalServiceDataMessage
.Builder messageBuilder
,
763 final Message message
764 ) throws AttachmentInvalidException
, IOException
, UnregisteredRecipientException
, InvalidStickerException
{
765 final var additionalAttachments
= new ArrayList
<SignalServiceAttachment
>();
766 if (message
.messageText().length() > ServiceConfig
.MAX_MESSAGE_BODY_SIZE
) {
767 final var messageBytes
= message
.messageText().getBytes(StandardCharsets
.UTF_8
);
768 final var uploadSpec
= dependencies
.getMessageSender().getResumableUploadSpec();
769 final var streamDetails
= new StreamDetails(new ByteArrayInputStream(messageBytes
),
771 messageBytes
.length
);
772 final var textAttachment
= AttachmentUtils
.createAttachmentStream(streamDetails
,
775 messageBuilder
.withBody(message
.messageText().substring(0, ServiceConfig
.MAX_MESSAGE_BODY_SIZE
));
776 additionalAttachments
.add(context
.getAttachmentHelper().uploadAttachment(textAttachment
));
778 messageBuilder
.withBody(message
.messageText());
780 if (!message
.attachments().isEmpty()) {
781 final var uploadedAttachments
= context
.getAttachmentHelper().uploadAttachments(message
.attachments());
782 if (!additionalAttachments
.isEmpty()) {
783 additionalAttachments
.addAll(uploadedAttachments
);
784 messageBuilder
.withAttachments(additionalAttachments
);
786 messageBuilder
.withAttachments(uploadedAttachments
);
788 } else if (!additionalAttachments
.isEmpty()) {
789 messageBuilder
.withAttachments(additionalAttachments
);
791 if (!message
.mentions().isEmpty()) {
792 messageBuilder
.withMentions(resolveMentions(message
.mentions()));
794 if (!message
.textStyles().isEmpty()) {
795 messageBuilder
.withBodyRanges(message
.textStyles().stream().map(TextStyle
::toBodyRange
).toList());
797 if (message
.quote().isPresent()) {
798 final var quote
= message
.quote().get();
799 final var quotedAttachments
= new ArrayList
<SignalServiceDataMessage
.Quote
.QuotedAttachment
>();
800 for (final var a
: quote
.attachments()) {
801 final var quotedAttachment
= new SignalServiceDataMessage
.Quote
.QuotedAttachment(a
.contentType(),
803 a
.preview() == null ?
null : context
.getAttachmentHelper().uploadAttachment(a
.preview()));
804 quotedAttachments
.add(quotedAttachment
);
806 messageBuilder
.withQuote(new SignalServiceDataMessage
.Quote(quote
.timestamp(),
807 context
.getRecipientHelper()
808 .resolveSignalServiceAddress(context
.getRecipientHelper().resolveRecipient(quote
.author()))
812 resolveMentions(quote
.mentions()),
813 SignalServiceDataMessage
.Quote
.Type
.NORMAL
,
814 quote
.textStyles().stream().map(TextStyle
::toBodyRange
).toList()));
816 if (message
.sticker().isPresent()) {
817 final var sticker
= message
.sticker().get();
818 final var packId
= StickerPackId
.deserialize(sticker
.packId());
819 final var stickerId
= sticker
.stickerId();
821 final var stickerPack
= context
.getAccount().getStickerStore().getStickerPack(packId
);
822 if (stickerPack
== null) {
823 throw new InvalidStickerException("Sticker pack not found");
825 final var manifest
= context
.getStickerHelper().getOrRetrieveStickerPack(packId
, stickerPack
.packKey());
826 if (manifest
.stickers().size() <= stickerId
) {
827 throw new InvalidStickerException("Sticker id not part of this pack");
829 final var manifestSticker
= manifest
.stickers().get(stickerId
);
830 final var streamDetails
= context
.getStickerPackStore().retrieveSticker(packId
, stickerId
);
831 if (streamDetails
== null) {
832 throw new InvalidStickerException("Missing local sticker file");
834 final var uploadSpec
= dependencies
.getMessageSender().getResumableUploadSpec();
835 final var stickerAttachment
= AttachmentUtils
.createAttachmentStream(streamDetails
,
838 messageBuilder
.withSticker(new SignalServiceDataMessage
.Sticker(packId
.serialize(),
839 stickerPack
.packKey(),
841 manifestSticker
.emoji(),
844 if (!message
.previews().isEmpty()) {
845 final var previews
= new ArrayList
<SignalServicePreview
>(message
.previews().size());
846 for (final var p
: message
.previews()) {
847 final var image
= p
.image().isPresent() ? context
.getAttachmentHelper()
848 .uploadAttachment(p
.image().get()) : null;
849 previews
.add(new SignalServicePreview(p
.url(),
853 Optional
.ofNullable(image
)));
855 messageBuilder
.withPreviews(previews
);
857 if (message
.storyReply().isPresent()) {
858 final var storyReply
= message
.storyReply().get();
859 final var authorServiceId
= context
.getRecipientHelper()
860 .resolveSignalServiceAddress(context
.getRecipientHelper().resolveRecipient(storyReply
.author()))
862 messageBuilder
.withStoryContext(new SignalServiceDataMessage
.StoryContext(authorServiceId
,
863 storyReply
.timestamp()));
867 private ArrayList
<SignalServiceDataMessage
.Mention
> resolveMentions(final List
<Message
.Mention
> mentionList
) throws UnregisteredRecipientException
{
868 final var mentions
= new ArrayList
<SignalServiceDataMessage
.Mention
>();
869 for (final var m
: mentionList
) {
870 final var recipientId
= context
.getRecipientHelper().resolveRecipient(m
.recipient());
871 mentions
.add(new SignalServiceDataMessage
.Mention(context
.getRecipientHelper()
872 .resolveSignalServiceAddress(recipientId
)
873 .getServiceId(), m
.start(), m
.length()));
879 public SendMessageResults
sendRemoteDeleteMessage(
880 long targetSentTimestamp
,
881 Set
<RecipientIdentifier
> recipients
882 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
883 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
884 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
885 for (final var recipient
: recipients
) {
886 if (recipient
instanceof RecipientIdentifier
.Uuid u
) {
887 account
.getMessageSendLogStore()
888 .deleteEntryForRecipientNonGroup(targetSentTimestamp
, ACI
.from(u
.uuid()));
889 } else if (recipient
instanceof RecipientIdentifier
.Pni pni
) {
890 account
.getMessageSendLogStore()
891 .deleteEntryForRecipientNonGroup(targetSentTimestamp
, PNI
.from(pni
.pni()));
892 } else if (recipient
instanceof RecipientIdentifier
.Single r
) {
894 final var recipientId
= context
.getRecipientHelper().resolveRecipient(r
);
895 final var address
= account
.getRecipientAddressResolver().resolveRecipientAddress(recipientId
);
896 if (address
.serviceId().isPresent()) {
897 account
.getMessageSendLogStore()
898 .deleteEntryForRecipientNonGroup(targetSentTimestamp
, address
.serviceId().get());
900 } catch (UnregisteredRecipientException ignored
) {
902 } else if (recipient
instanceof RecipientIdentifier
.Group r
) {
903 account
.getMessageSendLogStore().deleteEntryForGroup(targetSentTimestamp
, r
.groupId());
906 return sendMessage(messageBuilder
, recipients
, false);
910 public SendMessageResults
sendMessageReaction(
913 RecipientIdentifier
.Single targetAuthor
,
914 long targetSentTimestamp
,
915 Set
<RecipientIdentifier
> recipients
,
916 final boolean isStory
917 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
, UnregisteredRecipientException
{
918 var targetAuthorRecipientId
= context
.getRecipientHelper().resolveRecipient(targetAuthor
);
919 final var authorServiceId
= context
.getRecipientHelper()
920 .resolveSignalServiceAddress(targetAuthorRecipientId
)
922 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
, remove
, authorServiceId
, targetSentTimestamp
);
923 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
925 messageBuilder
.withStoryContext(new SignalServiceDataMessage
.StoryContext(authorServiceId
,
926 targetSentTimestamp
));
928 return sendMessage(messageBuilder
, recipients
, false);
932 public SendMessageResults
sendPaymentNotificationMessage(
935 RecipientIdentifier
.Single recipient
936 ) throws IOException
{
937 final var paymentNotification
= new SignalServiceDataMessage
.PaymentNotification(receipt
, note
);
938 final var payment
= new SignalServiceDataMessage
.Payment(paymentNotification
, null);
939 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withPayment(payment
);
941 return sendMessage(messageBuilder
, Set
.of(recipient
), false);
942 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
943 throw new AssertionError(e
);
948 public SendMessageResults
sendEndSessionMessage(Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
949 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
952 return sendMessage(messageBuilder
,
953 recipients
.stream().map(RecipientIdentifier
.class::cast
).collect(Collectors
.toSet()),
955 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
956 throw new AssertionError(e
);
958 for (var recipient
: recipients
) {
959 final RecipientId recipientId
;
961 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
962 } catch (UnregisteredRecipientException e
) {
965 final var serviceId
= context
.getAccount()
966 .getRecipientAddressResolver()
967 .resolveRecipientAddress(recipientId
)
969 if (serviceId
.isPresent()) {
970 account
.getAccountData(ServiceIdType
.ACI
).getSessionStore().deleteAllSessions(serviceId
.get());
977 public SendMessageResults
sendMessageRequestResponse(
978 final MessageRequestResponse
.Type type
,
979 final Set
<RecipientIdentifier
> recipients
981 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
982 for (final var recipient
: recipients
) {
983 if (recipient
instanceof RecipientIdentifier
.NoteToSelf
|| (
984 recipient
instanceof RecipientIdentifier
.Single single
985 && new RecipientAddress(single
.toPartialRecipientAddress()).matches(account
.getSelfRecipientAddress())
987 final var result
= context
.getSyncHelper()
988 .sendMessageRequestResponse(type
, account
.getSelfRecipientId());
989 if (result
!= null) {
990 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
992 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
993 } else if (recipient
instanceof RecipientIdentifier
.Single single
) {
995 final var recipientId
= context
.getRecipientHelper().resolveRecipient(single
);
996 final var result
= context
.getSyncHelper().sendMessageRequestResponse(type
, recipientId
);
997 if (result
!= null) {
998 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
1000 } catch (UnregisteredRecipientException e
) {
1001 results
.put(recipient
,
1002 List
.of(SendMessageResult
.unregisteredFailure(single
.toPartialRecipientAddress())));
1004 } else if (recipient
instanceof RecipientIdentifier
.Group group
) {
1005 final var result
= context
.getSyncHelper().sendMessageRequestResponse(type
, group
.groupId());
1006 results
.put(recipient
, List
.of(toSendMessageResult(result
)));
1009 return new SendMessageResults(0, results
);
1013 public void hideRecipient(final RecipientIdentifier
.Single recipient
) {
1014 final var recipientIdOptional
= context
.getRecipientHelper().resolveRecipientOptional(recipient
);
1015 if (recipientIdOptional
.isPresent()) {
1016 context
.getContactHelper().setContactHidden(recipientIdOptional
.get(), true);
1017 account
.removeRecipient(recipientIdOptional
.get());
1018 syncRemoteStorage();
1023 public void deleteRecipient(final RecipientIdentifier
.Single recipient
) {
1024 final var recipientIdOptional
= context
.getRecipientHelper().resolveRecipientOptional(recipient
);
1025 if (recipientIdOptional
.isPresent()) {
1026 account
.removeRecipient(recipientIdOptional
.get());
1027 syncRemoteStorage();
1032 public void deleteContact(final RecipientIdentifier
.Single recipient
) {
1033 final var recipientIdOptional
= context
.getRecipientHelper().resolveRecipientOptional(recipient
);
1034 if (recipientIdOptional
.isPresent()) {
1035 account
.getContactStore().deleteContact(recipientIdOptional
.get());
1036 syncRemoteStorage();
1041 public void setContactName(
1042 RecipientIdentifier
.Single recipient
,
1044 final String familyName
1045 ) throws NotPrimaryDeviceException
, UnregisteredRecipientException
{
1046 if (!account
.isPrimaryDevice()) {
1047 throw new NotPrimaryDeviceException();
1049 context
.getContactHelper()
1050 .setContactName(context
.getRecipientHelper().resolveRecipient(recipient
), givenName
, familyName
);
1051 syncRemoteStorage();
1055 public void setContactsBlocked(
1056 Collection
<RecipientIdentifier
.Single
> recipients
,
1058 ) throws IOException
, UnregisteredRecipientException
{
1059 if (recipients
.isEmpty()) {
1062 final var recipientIds
= context
.getRecipientHelper().resolveRecipients(recipients
);
1063 final var selfRecipientId
= account
.getSelfRecipientId();
1064 boolean shouldRotateProfileKey
= false;
1065 for (final var recipientId
: recipientIds
) {
1066 if (context
.getContactHelper().isContactBlocked(recipientId
) == blocked
) {
1069 context
.getContactHelper().setContactBlocked(recipientId
, blocked
);
1070 context
.getSyncHelper()
1071 .sendMessageRequestResponse(blocked
1072 ? MessageRequestResponse
.Type
.BLOCK
1073 : MessageRequestResponse
.Type
.UNBLOCK_AND_ACCEPT
, recipientId
);
1074 // if we don't have a common group with the blocked contact we need to rotate the profile key
1075 shouldRotateProfileKey
= blocked
&& (
1076 shouldRotateProfileKey
|| account
.getGroupStore()
1079 .noneMatch(g
-> g
.isMember(selfRecipientId
) && g
.isMember(recipientId
))
1082 if (shouldRotateProfileKey
) {
1083 context
.getProfileHelper().rotateProfileKey();
1085 context
.getSyncHelper().sendBlockedList();
1086 syncRemoteStorage();
1090 public void setGroupsBlocked(
1091 final Collection
<GroupId
> groupIds
,
1092 final boolean blocked
1093 ) throws GroupNotFoundException
, IOException
{
1094 if (groupIds
.isEmpty()) {
1097 boolean shouldRotateProfileKey
= false;
1098 for (final var groupId
: groupIds
) {
1099 if (context
.getGroupHelper().isGroupBlocked(groupId
) == blocked
) {
1102 context
.getGroupHelper().setGroupBlocked(groupId
, blocked
);
1103 context
.getSyncHelper()
1104 .sendMessageRequestResponse(blocked
1105 ? MessageRequestResponse
.Type
.BLOCK
1106 : MessageRequestResponse
.Type
.UNBLOCK_AND_ACCEPT
, groupId
);
1107 shouldRotateProfileKey
= blocked
;
1109 if (shouldRotateProfileKey
) {
1110 context
.getProfileHelper().rotateProfileKey();
1112 context
.getSyncHelper().sendBlockedList();
1113 syncRemoteStorage();
1117 public void setExpirationTimer(
1118 RecipientIdentifier
.Single recipient
,
1119 int messageExpirationTimer
1120 ) throws IOException
, UnregisteredRecipientException
{
1121 var recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
1122 context
.getContactHelper().setExpirationTimer(recipientId
, messageExpirationTimer
);
1123 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
1125 sendMessage(messageBuilder
, Set
.of(recipient
), false);
1126 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
1127 throw new AssertionError(e
);
1129 syncRemoteStorage();
1133 public StickerPackUrl
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
1134 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
1136 var messageSender
= dependencies
.getMessageSender();
1138 var packKey
= KeyUtils
.createStickerUploadKey();
1139 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
1140 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
1142 var sticker
= new StickerPack(packId
, packKey
);
1143 account
.getStickerStore().addStickerPack(sticker
);
1144 context
.getSyncHelper().sendStickerOperationsMessage(List
.of(sticker
), List
.of());
1146 return new StickerPackUrl(packId
, packKey
);
1150 public void installStickerPack(StickerPackUrl url
) throws IOException
{
1151 final var packId
= url
.packId();
1152 final var packKey
= url
.packKey();
1154 context
.getStickerHelper().retrieveStickerPack(packId
, packKey
);
1155 } catch (InvalidMessageException e
) {
1156 throw new IOException(e
);
1159 final var sticker
= context
.getStickerHelper().addOrUpdateStickerPack(packId
, packKey
, true);
1160 context
.getSyncHelper().sendStickerOperationsMessage(List
.of(sticker
), List
.of());
1164 public List
<org
.asamk
.signal
.manager
.api
.StickerPack
> getStickerPacks() {
1165 final var stickerPackStore
= context
.getStickerPackStore();
1166 return account
.getStickerStore().getStickerPacks().stream().map(pack
-> {
1167 if (stickerPackStore
.existsStickerPack(pack
.packId())) {
1169 final var manifest
= stickerPackStore
.retrieveManifest(pack
.packId());
1170 return new org
.asamk
.signal
.manager
.api
.StickerPack(pack
.packId(),
1171 new StickerPackUrl(pack
.packId(), pack
.packKey()),
1175 Optional
.ofNullable(manifest
.cover() == null ?
null : manifest
.cover().toApi()),
1176 manifest
.stickers().stream().map(JsonStickerPack
.JsonSticker
::toApi
).toList());
1177 } catch (Exception e
) {
1178 logger
.warn("Failed to read local sticker pack manifest: {}", e
.getMessage(), e
);
1182 return new org
.asamk
.signal
.manager
.api
.StickerPack(pack
.packId(), pack
.packKey(), pack
.isInstalled());
1187 public void requestAllSyncData() {
1188 context
.getSyncHelper().requestAllSyncData();
1189 syncRemoteStorage();
1192 void syncRemoteStorage() {
1193 context
.getJobExecutor().enqueueJob(new SyncStorageJob());
1197 public void addReceiveHandler(final ReceiveMessageHandler handler
, final boolean isWeakListener
) {
1198 synchronized (messageHandlers
) {
1199 if (isWeakListener
) {
1200 weakHandlers
.add(handler
);
1202 messageHandlers
.add(handler
);
1203 startReceiveThreadIfRequired();
1208 private static final AtomicInteger threadNumber
= new AtomicInteger(0);
1210 private void startReceiveThreadIfRequired() {
1211 if (receiveThread
!= null || isReceivingSynchronous
) {
1214 receiveThread
= Thread
.ofPlatform().name("receive-" + threadNumber
.getAndIncrement()).start(() -> {
1215 logger
.debug("Starting receiving messages");
1216 context
.getReceiveHelper().receiveMessagesContinuously(this::passReceivedMessageToHandlers
);
1217 logger
.debug("Finished receiving messages");
1218 synchronized (messageHandlers
) {
1219 receiveThread
= null;
1221 // Check if in the meantime another handler has been registered
1222 if (!messageHandlers
.isEmpty()) {
1223 logger
.debug("Another handler has been registered, starting receive thread again");
1224 startReceiveThreadIfRequired();
1230 private void passReceivedMessageToHandlers(MessageEnvelope envelope
, Throwable e
) {
1231 synchronized (messageHandlers
) {
1232 Stream
.concat(messageHandlers
.stream(), weakHandlers
.stream()).forEach(h
-> {
1234 h
.handleMessage(envelope
, e
);
1235 } catch (Throwable ex
) {
1236 logger
.warn("Message handler failed, ignoring", ex
);
1243 public void removeReceiveHandler(final ReceiveMessageHandler handler
) {
1244 final Thread thread
;
1245 synchronized (messageHandlers
) {
1246 weakHandlers
.remove(handler
);
1247 messageHandlers
.remove(handler
);
1248 if (!messageHandlers
.isEmpty() || receiveThread
== null || isReceivingSynchronous
) {
1251 thread
= receiveThread
;
1252 receiveThread
= null;
1255 stopReceiveThread(thread
);
1258 private void stopReceiveThread(final Thread thread
) {
1259 if (context
.getReceiveHelper().requestStopReceiveMessages()) {
1260 logger
.debug("Receive stop requested, interrupting read from server.");
1265 } catch (InterruptedException ignored
) {
1270 public boolean isReceiving() {
1271 if (isReceivingSynchronous
) {
1274 synchronized (messageHandlers
) {
1275 return !messageHandlers
.isEmpty();
1280 public void receiveMessages(
1281 Optional
<Duration
> timeout
,
1282 Optional
<Integer
> maxMessages
,
1283 ReceiveMessageHandler handler
1284 ) throws IOException
, AlreadyReceivingException
{
1285 receiveMessages(timeout
.orElse(Duration
.ofMinutes(1)), timeout
.isPresent(), maxMessages
.orElse(null), handler
);
1289 public void stopReceiveMessages() {
1290 Thread thread
= null;
1291 synchronized (messageHandlers
) {
1292 if (isReceivingSynchronous
) {
1293 thread
= receiveThread
;
1294 receiveThread
= null;
1297 if (thread
!= null) {
1298 stopReceiveThread(thread
);
1302 private void receiveMessages(
1304 boolean returnOnTimeout
,
1305 Integer maxMessages
,
1306 ReceiveMessageHandler handler
1307 ) throws IOException
, AlreadyReceivingException
{
1308 synchronized (messageHandlers
) {
1309 if (isReceiving()) {
1310 throw new AlreadyReceivingException("Already receiving message.");
1312 isReceivingSynchronous
= true;
1313 receiveThread
= Thread
.currentThread();
1316 context
.getReceiveHelper().receiveMessages(timeout
, returnOnTimeout
, maxMessages
, (envelope
, e
) -> {
1317 passReceivedMessageToHandlers(envelope
, e
);
1318 handler
.handleMessage(envelope
, e
);
1321 synchronized (messageHandlers
) {
1322 receiveThread
= null;
1323 isReceivingSynchronous
= false;
1324 if (!messageHandlers
.isEmpty()) {
1325 startReceiveThreadIfRequired();
1332 public void setReceiveConfig(final ReceiveConfig receiveConfig
) {
1333 context
.getReceiveHelper().setReceiveConfig(receiveConfig
);
1337 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
1338 final RecipientId recipientId
;
1340 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
1341 } catch (UnregisteredRecipientException e
) {
1344 return context
.getContactHelper().isContactBlocked(recipientId
);
1348 public void sendContacts() throws IOException
{
1349 context
.getSyncHelper().sendContacts();
1353 public List
<Recipient
> getRecipients(
1354 boolean onlyContacts
,
1355 Optional
<Boolean
> blocked
,
1356 Collection
<RecipientIdentifier
.Single
> recipients
,
1357 Optional
<String
> name
1359 final var recipientIds
= recipients
.stream().map(a
-> {
1361 return context
.getRecipientHelper().resolveRecipient(a
);
1362 } catch (UnregisteredRecipientException e
) {
1365 }).filter(Objects
::nonNull
).collect(Collectors
.toSet());
1366 if (!recipients
.isEmpty() && recipientIds
.isEmpty()) {
1369 // refresh profiles of explicitly given recipients
1370 context
.getProfileHelper().refreshRecipientProfiles(recipientIds
);
1371 return account
.getRecipientStore()
1372 .getRecipients(onlyContacts
, blocked
, recipientIds
, name
)
1374 .map(s
-> new Recipient(s
.getRecipientId(),
1375 s
.getAddress().toApiRecipientAddress(),
1378 s
.getExpiringProfileKeyCredential(),
1380 s
.getDiscoverable()))
1385 public String
getContactOrProfileName(RecipientIdentifier
.Single recipient
) {
1386 final RecipientId recipientId
;
1388 recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
1389 } catch (UnregisteredRecipientException e
) {
1393 final var contact
= account
.getContactStore().getContact(recipientId
);
1394 if (contact
!= null && !Util
.isEmpty(contact
.getName())) {
1395 return contact
.getName();
1398 final var profile
= context
.getProfileHelper().getRecipientProfile(recipientId
);
1399 if (profile
!= null) {
1400 return profile
.getDisplayName();
1407 public Group
getGroup(GroupId groupId
) {
1408 return toGroup(context
.getGroupHelper().getGroup(groupId
));
1412 public List
<Identity
> getIdentities() {
1413 return account
.getIdentityKeyStore()
1416 .map(this::toIdentity
)
1417 .filter(Objects
::nonNull
)
1421 private Identity
toIdentity(final IdentityInfo identityInfo
) {
1422 if (identityInfo
== null) {
1426 final var address
= account
.getRecipientAddressResolver()
1427 .resolveRecipientAddress(account
.getRecipientResolver().resolveRecipient(identityInfo
.getServiceId()));
1428 if (address
.serviceId().isPresent() && !Objects
.equals(address
.serviceId().get(),
1429 identityInfo
.getServiceId())) {
1432 final var scannableFingerprint
= context
.getIdentityHelper()
1433 .computeSafetyNumberForScanning(identityInfo
.getServiceId(), identityInfo
.getIdentityKey());
1434 return new Identity(address
.toApiRecipientAddress(),
1435 identityInfo
.getIdentityKey().getPublicKey().serialize(),
1436 context
.getIdentityHelper()
1437 .computeSafetyNumber(identityInfo
.getServiceId(), identityInfo
.getIdentityKey()),
1438 scannableFingerprint
== null ?
null : scannableFingerprint
.getSerialized(),
1439 identityInfo
.getTrustLevel(),
1440 identityInfo
.getDateAddedTimestamp());
1444 public List
<Identity
> getIdentities(RecipientIdentifier
.Single recipient
) {
1445 ServiceId serviceId
;
1447 final var address
= account
.getRecipientAddressResolver()
1448 .resolveRecipientAddress(context
.getRecipientHelper().resolveRecipient(recipient
));
1449 if (address
.serviceId().isEmpty()) {
1452 serviceId
= address
.serviceId().get();
1453 } catch (UnregisteredRecipientException e
) {
1456 final var identity
= account
.getIdentityKeyStore().getIdentityInfo(serviceId
);
1457 return identity
== null ? List
.of() : List
.of(toIdentity(identity
));
1461 public boolean trustIdentityVerified(
1462 RecipientIdentifier
.Single recipient
,
1463 IdentityVerificationCode verificationCode
1464 ) throws UnregisteredRecipientException
{
1465 return switch (verificationCode
) {
1466 case IdentityVerificationCode
.Fingerprint fingerprint
-> trustIdentity(recipient
,
1467 r
-> context
.getIdentityHelper().trustIdentityVerified(r
, fingerprint
.fingerprint()));
1468 case IdentityVerificationCode
.SafetyNumber safetyNumber
-> trustIdentity(recipient
,
1469 r
-> context
.getIdentityHelper().trustIdentityVerifiedSafetyNumber(r
, safetyNumber
.safetyNumber()));
1470 case IdentityVerificationCode
.ScannableSafetyNumber safetyNumber
-> trustIdentity(recipient
,
1471 r
-> context
.getIdentityHelper().trustIdentityVerifiedSafetyNumber(r
, safetyNumber
.safetyNumber()));
1472 case null -> throw new AssertionError("Invalid verification code type");
1477 public boolean trustIdentityAllKeys(RecipientIdentifier
.Single recipient
) throws UnregisteredRecipientException
{
1478 return trustIdentity(recipient
, r
-> context
.getIdentityHelper().trustIdentityAllKeys(r
));
1481 private boolean trustIdentity(
1482 RecipientIdentifier
.Single recipient
,
1483 Function
<RecipientId
, Boolean
> trustMethod
1484 ) throws UnregisteredRecipientException
{
1485 final var recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
1486 final var updated
= trustMethod
.apply(recipientId
);
1487 if (updated
&& this.isReceiving()) {
1488 account
.setNeedsToRetryFailedMessages(true);
1494 public void addAddressChangedListener(final Runnable listener
) {
1495 synchronized (addressChangedListeners
) {
1496 addressChangedListeners
.add(listener
);
1501 public void addClosedListener(final Runnable listener
) {
1502 synchronized (closedListeners
) {
1503 closedListeners
.add(listener
);
1508 public InputStream
retrieveAttachment(final String id
) throws IOException
{
1509 return context
.getAttachmentHelper().retrieveAttachment(id
).getStream();
1513 public InputStream
retrieveContactAvatar(final RecipientIdentifier
.Single recipient
) throws IOException
, UnregisteredRecipientException
{
1514 final var recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
1515 final var address
= account
.getRecipientStore().resolveRecipientAddress(recipientId
);
1516 final var streamDetails
= context
.getAvatarStore().retrieveContactAvatar(address
);
1517 if (streamDetails
== null) {
1518 throw new FileNotFoundException();
1520 return streamDetails
.getStream();
1524 public InputStream
retrieveProfileAvatar(final RecipientIdentifier
.Single recipient
) throws IOException
, UnregisteredRecipientException
{
1525 final var recipientId
= context
.getRecipientHelper().resolveRecipient(recipient
);
1526 context
.getProfileHelper().getRecipientProfile(recipientId
);
1527 final var address
= account
.getRecipientStore().resolveRecipientAddress(recipientId
);
1528 final var streamDetails
= context
.getAvatarStore().retrieveProfileAvatar(address
);
1529 if (streamDetails
== null) {
1530 throw new FileNotFoundException();
1532 return streamDetails
.getStream();
1536 public InputStream
retrieveGroupAvatar(final GroupId groupId
) throws IOException
{
1537 final var streamDetails
= context
.getAvatarStore().retrieveGroupAvatar(groupId
);
1538 context
.getGroupHelper().getGroup(groupId
);
1539 if (streamDetails
== null) {
1540 throw new FileNotFoundException();
1542 return streamDetails
.getStream();
1546 public InputStream
retrieveSticker(final StickerPackId stickerPackId
, final int stickerId
) throws IOException
{
1547 var streamDetails
= context
.getStickerPackStore().retrieveSticker(stickerPackId
, stickerId
);
1548 if (streamDetails
== null) {
1549 final var pack
= account
.getStickerStore().getStickerPack(stickerPackId
);
1552 context
.getStickerHelper().retrieveStickerPack(stickerPackId
, pack
.packKey());
1553 } catch (InvalidMessageException e
) {
1554 logger
.warn("Failed to download sticker pack");
1558 if (streamDetails
== null) {
1559 throw new FileNotFoundException();
1561 return streamDetails
.getStream();
1565 public void close() {
1567 synchronized (messageHandlers
) {
1568 weakHandlers
.clear();
1569 messageHandlers
.clear();
1570 thread
= receiveThread
;
1571 receiveThread
= null;
1573 if (thread
!= null) {
1574 stopReceiveThread(thread
);
1579 dependencies
.getSignalWebSocket().disconnect();
1580 dependencies
.getPushServiceSocket().close();
1581 disposable
.dispose();
1583 if (account
!= null) {
1587 synchronized (closedListeners
) {
1588 closedListeners
.forEach(Runnable
::run
);
1589 closedListeners
.clear();