1 package org
.asamk
.signal
.manager
.helper
;
3 import org
.asamk
.signal
.manager
.api
.GroupNotFoundException
;
4 import org
.asamk
.signal
.manager
.api
.NotAGroupMemberException
;
5 import org
.asamk
.signal
.manager
.api
.PhoneNumberSharingMode
;
6 import org
.asamk
.signal
.manager
.api
.Profile
;
7 import org
.asamk
.signal
.manager
.config
.ServiceConfig
;
8 import org
.asamk
.signal
.manager
.internal
.SignalDependencies
;
9 import org
.asamk
.signal
.manager
.jobs
.SyncStorageJob
;
10 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
11 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV2
;
12 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientAddress
;
13 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
14 import org
.asamk
.signal
.manager
.util
.IOUtils
;
15 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
16 import org
.asamk
.signal
.manager
.util
.PaymentUtils
;
17 import org
.asamk
.signal
.manager
.util
.ProfileUtils
;
18 import org
.asamk
.signal
.manager
.util
.Utils
;
19 import org
.signal
.libsignal
.protocol
.IdentityKey
;
20 import org
.signal
.libsignal
.protocol
.InvalidKeyException
;
21 import org
.signal
.libsignal
.zkgroup
.profiles
.ExpiringProfileKeyCredential
;
22 import org
.signal
.libsignal
.zkgroup
.profiles
.ProfileKey
;
23 import org
.slf4j
.Logger
;
24 import org
.slf4j
.LoggerFactory
;
25 import org
.whispersystems
.signalservice
.api
.crypto
.UnidentifiedAccess
;
26 import org
.whispersystems
.signalservice
.api
.profiles
.AvatarUploadParams
;
27 import org
.whispersystems
.signalservice
.api
.profiles
.ProfileAndCredential
;
28 import org
.whispersystems
.signalservice
.api
.profiles
.SignalServiceProfile
;
29 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
30 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.NotFoundException
;
31 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.PushNetworkException
;
32 import org
.whispersystems
.signalservice
.api
.services
.ProfileService
;
33 import org
.whispersystems
.signalservice
.api
.util
.ExpiringProfileCredentialUtil
;
35 import java
.io
.IOException
;
36 import java
.io
.OutputStream
;
37 import java
.nio
.file
.Files
;
38 import java
.util
.Base64
;
39 import java
.util
.Collection
;
40 import java
.util
.List
;
41 import java
.util
.Locale
;
42 import java
.util
.Objects
;
43 import java
.util
.Optional
;
46 import io
.reactivex
.rxjava3
.core
.Flowable
;
47 import io
.reactivex
.rxjava3
.core
.Maybe
;
48 import io
.reactivex
.rxjava3
.core
.Single
;
50 public final class ProfileHelper
{
52 private static final Logger logger
= LoggerFactory
.getLogger(ProfileHelper
.class);
54 private final SignalAccount account
;
55 private final SignalDependencies dependencies
;
56 private final Context context
;
58 public ProfileHelper(final Context context
) {
59 this.account
= context
.getAccount();
60 this.dependencies
= context
.getDependencies();
61 this.context
= context
;
64 public void rotateProfileKey() throws IOException
{
65 // refresh our profile, before creating a new profile key
67 var profileKey
= KeyUtils
.createProfileKey();
68 account
.setProfileKey(profileKey
);
69 context
.getAccountHelper().updateAccountAttributes();
70 setProfile(true, true, null, null, null, null, null, null);
71 account
.getRecipientStore().rotateSelfStorageId();
72 context
.getJobExecutor().enqueueJob(new SyncStorageJob());
74 final var recipientIds
= account
.getRecipientStore().getRecipientIdsWithEnabledProfileSharing();
75 for (final var recipientId
: recipientIds
) {
76 context
.getSendHelper().sendProfileKey(recipientId
);
79 final var selfRecipientId
= account
.getSelfRecipientId();
80 final var activeGroupIds
= account
.getGroupStore()
83 .filter(g
-> g
instanceof GroupInfoV2
&& g
.isMember(selfRecipientId
) && g
.isProfileSharingEnabled())
84 .map(g
-> (GroupInfoV2
) g
)
85 .map(GroupInfoV2
::getGroupId
)
87 for (final var groupId
: activeGroupIds
) {
89 context
.getGroupHelper().updateGroupProfileKey(groupId
);
90 } catch (GroupNotFoundException
| NotAGroupMemberException
| IOException e
) {
91 logger
.warn("Failed to update group profile key: {}", e
.getMessage());
96 public Profile
getRecipientProfile(RecipientId recipientId
) {
97 return getRecipientProfile(recipientId
, false);
100 public List
<Profile
> getRecipientProfiles(Collection
<RecipientId
> recipientIds
) {
101 return getRecipientProfiles(recipientIds
, false);
104 public void refreshRecipientProfile(RecipientId recipientId
) {
105 getRecipientProfile(recipientId
, true);
108 public void refreshRecipientProfiles(Collection
<RecipientId
> recipientIds
) {
109 getRecipientProfiles(recipientIds
, true);
112 public List
<ExpiringProfileKeyCredential
> getExpiringProfileKeyCredential(List
<RecipientId
> recipientIds
) {
113 final var profileFetches
= Flowable
.fromIterable(recipientIds
)
114 .filter(recipientId
-> !ExpiringProfileCredentialUtil
.isValid(account
.getProfileStore()
115 .getExpiringProfileKeyCredential(recipientId
)))
116 .map(recipientId
-> retrieveProfile(recipientId
,
117 SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
).onErrorComplete());
118 Maybe
.merge(profileFetches
, 10).blockingSubscribe();
120 return recipientIds
.stream().map(r
-> account
.getProfileStore().getExpiringProfileKeyCredential(r
)).toList();
123 public ExpiringProfileKeyCredential
getExpiringProfileKeyCredential(RecipientId recipientId
) {
124 var profileKeyCredential
= account
.getProfileStore().getExpiringProfileKeyCredential(recipientId
);
125 if (ExpiringProfileCredentialUtil
.isValid(profileKeyCredential
)) {
126 return profileKeyCredential
;
130 blockingGetProfile(retrieveProfile(recipientId
, SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
));
131 } catch (IOException e
) {
132 logger
.warn("Failed to retrieve profile key credential, ignoring: {}", e
.getMessage());
136 return account
.getProfileStore().getExpiringProfileKeyCredential(recipientId
);
140 * @param givenName if null, the previous givenName will be kept
141 * @param familyName if null, the previous familyName will be kept
142 * @param about if null, the previous about text will be kept
143 * @param aboutEmoji if null, the previous about emoji will be kept
144 * @param avatar if avatar is null the image from the local avatar store is used (if present),
146 public void setProfile(
148 final String familyName
,
151 Optional
<String
> avatar
,
152 byte[] mobileCoinAddress
153 ) throws IOException
{
154 setProfile(true, false, givenName
, familyName
, about
, aboutEmoji
, avatar
, mobileCoinAddress
);
157 public void setProfile(
158 boolean uploadProfile
,
159 boolean forceUploadAvatar
,
161 final String familyName
,
164 Optional
<String
> avatar
,
165 byte[] mobileCoinAddress
166 ) throws IOException
{
167 var profile
= getSelfProfile();
168 var builder
= profile
== null ? Profile
.newBuilder() : Profile
.newBuilder(profile
);
169 if (givenName
!= null) {
170 builder
.withGivenName(givenName
);
172 if (familyName
!= null) {
173 builder
.withFamilyName(familyName
);
176 builder
.withAbout(about
);
178 if (aboutEmoji
!= null) {
179 builder
.withAboutEmoji(aboutEmoji
);
181 if (mobileCoinAddress
!= null) {
182 builder
.withMobileCoinAddress(mobileCoinAddress
);
184 var newProfile
= builder
.build();
187 final var streamDetails
= avatar
!= null && avatar
.isPresent()
188 ? Utils
.createStreamDetails(avatar
.get())
190 : forceUploadAvatar
&& avatar
== null ? context
.getAvatarStore()
191 .retrieveProfileAvatar(account
.getSelfRecipientAddress()) : null;
192 try (streamDetails
) {
193 final var avatarUploadParams
= streamDetails
!= null
194 ? AvatarUploadParams
.forAvatar(streamDetails
)
195 : avatar
== null ? AvatarUploadParams
.unchanged(true) : AvatarUploadParams
.unchanged(false);
196 final var paymentsAddress
= Optional
.ofNullable(newProfile
.getMobileCoinAddress())
197 .map(address
-> PaymentUtils
.signPaymentsAddress(address
,
198 account
.getAciIdentityKeyPair().getPrivateKey()));
199 logger
.debug("Uploading new profile");
200 final var avatarPath
= dependencies
.getAccountManager()
201 .setVersionedProfile(account
.getAci(),
202 account
.getProfileKey(),
203 newProfile
.getInternalServiceName(),
204 newProfile
.getAbout() == null ?
"" : newProfile
.getAbout(),
205 newProfile
.getAboutEmoji() == null ?
"" : newProfile
.getAboutEmoji(),
208 List
.of(/* TODO implement support for badges */),
209 account
.getConfigurationStore().getPhoneNumberSharingMode()
210 == PhoneNumberSharingMode
.EVERYBODY
);
211 if (!avatarUploadParams
.keepTheSame
) {
212 builder
.withAvatarUrlPath(avatarPath
.orElse(null));
214 newProfile
= builder
.build();
218 if (avatar
!= null) {
219 if (avatar
.isPresent()) {
220 try (final var streamDetails
= Utils
.createStreamDetails(avatar
.get()).first()) {
221 context
.getAvatarStore()
222 .storeProfileAvatar(account
.getSelfRecipientAddress(),
223 outputStream
-> IOUtils
.copyStream(streamDetails
.getStream(), outputStream
));
226 context
.getAvatarStore().deleteProfileAvatar(account
.getSelfRecipientAddress());
229 account
.getProfileStore().storeProfile(account
.getSelfRecipientId(), newProfile
);
232 public Profile
getSelfProfile() {
233 return getRecipientProfile(account
.getSelfRecipientId());
236 private List
<Profile
> getRecipientProfiles(Collection
<RecipientId
> recipientIds
, boolean force
) {
237 final var profileStore
= account
.getProfileStore();
238 final var profileFetches
= Flowable
.fromIterable(recipientIds
)
239 .filter(recipientId
-> force
|| isProfileRefreshRequired(profileStore
.getProfile(recipientId
)))
240 .map(recipientId
-> retrieveProfile(recipientId
,
241 SignalServiceProfile
.RequestType
.PROFILE
).onErrorComplete());
242 Maybe
.merge(profileFetches
, 10).blockingSubscribe();
244 return recipientIds
.stream().map(profileStore
::getProfile
).toList();
247 private Profile
getRecipientProfile(RecipientId recipientId
, boolean force
) {
248 var profile
= account
.getProfileStore().getProfile(recipientId
);
250 if (!force
&& !isProfileRefreshRequired(profile
)) {
255 blockingGetProfile(retrieveProfile(recipientId
, SignalServiceProfile
.RequestType
.PROFILE
));
256 } catch (IOException e
) {
257 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
260 return account
.getProfileStore().getProfile(recipientId
);
263 private boolean isProfileRefreshRequired(final Profile profile
) {
264 if (profile
== null) {
267 // Profiles are cached for 6h before retrieving them again, unless forced
268 final var now
= System
.currentTimeMillis();
269 return now
- profile
.getLastUpdateTimestamp() >= 6 * 60 * 60 * 1000;
272 private Profile
decryptProfileAndDownloadAvatar(
273 final RecipientId recipientId
, final ProfileKey profileKey
, final SignalServiceProfile encryptedProfile
275 final var avatarPath
= encryptedProfile
.getAvatar();
276 downloadProfileAvatar(recipientId
, avatarPath
, profileKey
);
278 return ProfileUtils
.decryptProfile(profileKey
, encryptedProfile
);
281 public void downloadProfileAvatar(
282 final RecipientId recipientId
, final String avatarPath
, final ProfileKey profileKey
284 var profile
= account
.getProfileStore().getProfile(recipientId
);
285 if (profile
== null || !Objects
.equals(avatarPath
, profile
.getAvatarUrlPath())) {
286 logger
.trace("Downloading profile avatar for {}", recipientId
);
287 downloadProfileAvatar(account
.getRecipientAddressResolver().resolveRecipientAddress(recipientId
),
290 var builder
= profile
== null ? Profile
.newBuilder() : Profile
.newBuilder(profile
);
291 account
.getProfileStore().storeProfile(recipientId
, builder
.withAvatarUrlPath(avatarPath
).build());
295 private ProfileAndCredential
blockingGetProfile(Single
<ProfileAndCredential
> profile
) throws IOException
{
297 return profile
.blockingGet();
298 } catch (RuntimeException e
) {
299 if (e
.getCause() instanceof PushNetworkException
) {
300 throw (PushNetworkException
) e
.getCause();
301 } else if (e
.getCause() instanceof NotFoundException
) {
302 throw (NotFoundException
) e
.getCause();
304 throw new IOException(e
);
309 private Single
<ProfileAndCredential
> retrieveProfile(
310 RecipientId recipientId
, SignalServiceProfile
.RequestType requestType
312 var unidentifiedAccess
= getUnidentifiedAccess(recipientId
);
313 var profileKey
= Optional
.ofNullable(account
.getProfileStore().getProfileKey(recipientId
));
315 logger
.trace("Retrieving profile for {} {}",
317 profileKey
.isPresent() ?
"with profile key" : "without profile key");
318 final var address
= context
.getRecipientHelper().resolveSignalServiceAddress(recipientId
);
319 return retrieveProfile(address
, profileKey
, unidentifiedAccess
, requestType
).doOnSuccess(p
-> {
320 logger
.trace("Got new profile for {}", recipientId
);
321 final var encryptedProfile
= p
.getProfile();
323 if (requestType
== SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
324 || !ExpiringProfileCredentialUtil
.isValid(account
.getProfileStore()
325 .getExpiringProfileKeyCredential(recipientId
))) {
326 logger
.trace("Storing profile credential");
327 final var profileKeyCredential
= p
.getExpiringProfileKeyCredential().orElse(null);
328 account
.getProfileStore().storeExpiringProfileKeyCredential(recipientId
, profileKeyCredential
);
331 final var profile
= account
.getProfileStore().getProfile(recipientId
);
333 if (recipientId
.equals(account
.getSelfRecipientId())) {
334 final var isUnrestricted
= encryptedProfile
.isUnrestrictedUnidentifiedAccess();
335 if (account
.isUnrestrictedUnidentifiedAccess() != isUnrestricted
) {
336 account
.setUnrestrictedUnidentifiedAccess(isUnrestricted
);
340 Profile newProfile
= null;
341 if (profileKey
.isPresent()) {
342 logger
.trace("Decrypting profile");
343 newProfile
= decryptProfileAndDownloadAvatar(recipientId
, profileKey
.get(), encryptedProfile
);
346 if (newProfile
== null) {
348 profile
== null ? Profile
.newBuilder() : Profile
.newBuilder(profile
)
349 ).withLastUpdateTimestamp(System
.currentTimeMillis())
350 .withUnidentifiedAccessMode(ProfileUtils
.getUnidentifiedAccessMode(encryptedProfile
, null))
351 .withCapabilities(ProfileUtils
.getCapabilities(encryptedProfile
))
356 logger
.trace("Storing identity");
357 final var identityKey
= new IdentityKey(Base64
.getDecoder().decode(encryptedProfile
.getIdentityKey()));
358 account
.getIdentityKeyStore().saveIdentity(p
.getProfile().getServiceId(), identityKey
);
359 } catch (InvalidKeyException ignored
) {
360 logger
.warn("Got invalid identity key in profile for {}",
361 context
.getRecipientHelper().resolveSignalServiceAddress(recipientId
).getIdentifier());
364 logger
.trace("Storing profile");
365 account
.getProfileStore().storeProfile(recipientId
, newProfile
);
367 logger
.trace("Done handling retrieved profile");
369 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
370 final var profile
= account
.getProfileStore().getProfile(recipientId
);
371 final var newProfile
= (
372 profile
== null ? Profile
.newBuilder() : Profile
.newBuilder(profile
)
373 ).withLastUpdateTimestamp(System
.currentTimeMillis())
374 .withUnidentifiedAccessMode(Profile
.UnidentifiedAccessMode
.UNKNOWN
)
375 .withCapabilities(Set
.of())
378 account
.getProfileStore().storeProfile(recipientId
, newProfile
);
382 private Single
<ProfileAndCredential
> retrieveProfile(
383 SignalServiceAddress address
,
384 Optional
<ProfileKey
> profileKey
,
385 Optional
<UnidentifiedAccess
> unidentifiedAccess
,
386 SignalServiceProfile
.RequestType requestType
388 final var profileService
= dependencies
.getProfileService();
389 final var locale
= Utils
.getDefaultLocale(Locale
.US
);
391 return profileService
.getProfile(address
, profileKey
, unidentifiedAccess
, requestType
, locale
).map(pair
-> {
392 var processor
= new ProfileService
.ProfileResponseProcessor(pair
);
393 if (processor
.hasResult()) {
394 return processor
.getResult();
395 } else if (processor
.notFound()) {
396 throw new NotFoundException("Profile not found");
398 throw pair
.getExecutionError()
399 .or(pair
::getApplicationError
)
400 .orElseThrow(() -> new IOException("Unknown error while retrieving profile"));
405 private void downloadProfileAvatar(
406 RecipientAddress address
, String avatarPath
, ProfileKey profileKey
408 if (avatarPath
== null) {
410 context
.getAvatarStore().deleteProfileAvatar(address
);
411 } catch (IOException e
) {
412 logger
.warn("Failed to delete local profile avatar, ignoring: {}", e
.getMessage());
418 context
.getAvatarStore()
419 .storeProfileAvatar(address
,
420 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
421 } catch (Throwable e
) {
422 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
426 private void retrieveProfileAvatar(
427 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
428 ) throws IOException
{
429 var tmpFile
= IOUtils
.createTempFile();
430 try (var input
= dependencies
.getMessageReceiver()
431 .retrieveProfileAvatar(avatarPath
,
434 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
435 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
436 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
439 Files
.delete(tmpFile
.toPath());
440 } catch (IOException e
) {
441 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
448 private Optional
<UnidentifiedAccess
> getUnidentifiedAccess(RecipientId recipientId
) {
449 var unidentifiedAccess
= context
.getUnidentifiedAccessHelper().getAccessFor(recipientId
, true);
451 if (unidentifiedAccess
.isPresent()) {
452 return unidentifiedAccess
.get().getTargetUnidentifiedAccess();
455 return Optional
.empty();