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
.storage
.SignalAccount
;
10 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV2
;
11 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientAddress
;
12 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
13 import org
.asamk
.signal
.manager
.util
.IOUtils
;
14 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
15 import org
.asamk
.signal
.manager
.util
.PaymentUtils
;
16 import org
.asamk
.signal
.manager
.util
.ProfileUtils
;
17 import org
.asamk
.signal
.manager
.util
.Utils
;
18 import org
.signal
.libsignal
.protocol
.IdentityKey
;
19 import org
.signal
.libsignal
.protocol
.InvalidKeyException
;
20 import org
.signal
.libsignal
.zkgroup
.profiles
.ExpiringProfileKeyCredential
;
21 import org
.signal
.libsignal
.zkgroup
.profiles
.ProfileKey
;
22 import org
.slf4j
.Logger
;
23 import org
.slf4j
.LoggerFactory
;
24 import org
.whispersystems
.signalservice
.api
.crypto
.UnidentifiedAccess
;
25 import org
.whispersystems
.signalservice
.api
.profiles
.AvatarUploadParams
;
26 import org
.whispersystems
.signalservice
.api
.profiles
.ProfileAndCredential
;
27 import org
.whispersystems
.signalservice
.api
.profiles
.SignalServiceProfile
;
28 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
29 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.NotFoundException
;
30 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.PushNetworkException
;
31 import org
.whispersystems
.signalservice
.api
.services
.ProfileService
;
32 import org
.whispersystems
.signalservice
.api
.util
.ExpiringProfileCredentialUtil
;
34 import java
.io
.IOException
;
35 import java
.io
.OutputStream
;
36 import java
.nio
.file
.Files
;
37 import java
.util
.Base64
;
38 import java
.util
.Collection
;
39 import java
.util
.List
;
40 import java
.util
.Locale
;
41 import java
.util
.Objects
;
42 import java
.util
.Optional
;
45 import io
.reactivex
.rxjava3
.core
.Flowable
;
46 import io
.reactivex
.rxjava3
.core
.Maybe
;
47 import io
.reactivex
.rxjava3
.core
.Single
;
49 public final class ProfileHelper
{
51 private static final Logger logger
= LoggerFactory
.getLogger(ProfileHelper
.class);
53 private final SignalAccount account
;
54 private final SignalDependencies dependencies
;
55 private final Context context
;
57 public ProfileHelper(final Context context
) {
58 this.account
= context
.getAccount();
59 this.dependencies
= context
.getDependencies();
60 this.context
= context
;
63 public void rotateProfileKey() throws IOException
{
64 // refresh our profile, before creating a new profile key
66 var profileKey
= KeyUtils
.createProfileKey();
67 account
.setProfileKey(profileKey
);
68 context
.getAccountHelper().updateAccountAttributes();
69 setProfile(true, true, null, null, null, null, null, null);
70 // TODO update profile key in storage
72 final var recipientIds
= account
.getRecipientStore().getRecipientIdsWithEnabledProfileSharing();
73 for (final var recipientId
: recipientIds
) {
74 context
.getSendHelper().sendProfileKey(recipientId
);
77 final var selfRecipientId
= account
.getSelfRecipientId();
78 final var activeGroupIds
= account
.getGroupStore()
81 .filter(g
-> g
instanceof GroupInfoV2
&& g
.isMember(selfRecipientId
))
82 .map(g
-> (GroupInfoV2
) g
)
83 .map(GroupInfoV2
::getGroupId
)
85 for (final var groupId
: activeGroupIds
) {
87 context
.getGroupHelper().updateGroupProfileKey(groupId
);
88 } catch (GroupNotFoundException
| NotAGroupMemberException
| IOException e
) {
89 logger
.warn("Failed to update group profile key: {}", e
.getMessage());
94 public Profile
getRecipientProfile(RecipientId recipientId
) {
95 return getRecipientProfile(recipientId
, false);
98 public List
<Profile
> getRecipientProfiles(Collection
<RecipientId
> recipientIds
) {
99 return getRecipientProfiles(recipientIds
, false);
102 public void refreshRecipientProfile(RecipientId recipientId
) {
103 getRecipientProfile(recipientId
, true);
106 public void refreshRecipientProfiles(Collection
<RecipientId
> recipientIds
) {
107 getRecipientProfiles(recipientIds
, true);
110 public List
<ExpiringProfileKeyCredential
> getExpiringProfileKeyCredential(List
<RecipientId
> recipientIds
) {
111 final var profileFetches
= Flowable
.fromIterable(recipientIds
)
112 .filter(recipientId
-> !ExpiringProfileCredentialUtil
.isValid(account
.getProfileStore()
113 .getExpiringProfileKeyCredential(recipientId
)))
114 .map(recipientId
-> retrieveProfile(recipientId
,
115 SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
).onErrorComplete());
116 Maybe
.merge(profileFetches
, 10).blockingSubscribe();
118 return recipientIds
.stream().map(r
-> account
.getProfileStore().getExpiringProfileKeyCredential(r
)).toList();
121 public ExpiringProfileKeyCredential
getExpiringProfileKeyCredential(RecipientId recipientId
) {
122 var profileKeyCredential
= account
.getProfileStore().getExpiringProfileKeyCredential(recipientId
);
123 if (ExpiringProfileCredentialUtil
.isValid(profileKeyCredential
)) {
124 return profileKeyCredential
;
128 blockingGetProfile(retrieveProfile(recipientId
, SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
));
129 } catch (IOException e
) {
130 logger
.warn("Failed to retrieve profile key credential, ignoring: {}", e
.getMessage());
134 return account
.getProfileStore().getExpiringProfileKeyCredential(recipientId
);
138 * @param givenName if null, the previous givenName will be kept
139 * @param familyName if null, the previous familyName will be kept
140 * @param about if null, the previous about text will be kept
141 * @param aboutEmoji if null, the previous about emoji will be kept
142 * @param avatar if avatar is null the image from the local avatar store is used (if present),
144 public void setProfile(
146 final String familyName
,
149 Optional
<String
> avatar
,
150 byte[] mobileCoinAddress
151 ) throws IOException
{
152 setProfile(true, false, givenName
, familyName
, about
, aboutEmoji
, avatar
, mobileCoinAddress
);
155 public void setProfile(
156 boolean uploadProfile
,
157 boolean forceUploadAvatar
,
159 final String familyName
,
162 Optional
<String
> avatar
,
163 byte[] mobileCoinAddress
164 ) throws IOException
{
165 var profile
= getSelfProfile();
166 var builder
= profile
== null ? Profile
.newBuilder() : Profile
.newBuilder(profile
);
167 if (givenName
!= null) {
168 builder
.withGivenName(givenName
);
170 if (familyName
!= null) {
171 builder
.withFamilyName(familyName
);
174 builder
.withAbout(about
);
176 if (aboutEmoji
!= null) {
177 builder
.withAboutEmoji(aboutEmoji
);
179 if (mobileCoinAddress
!= null) {
180 builder
.withMobileCoinAddress(mobileCoinAddress
);
182 var newProfile
= builder
.build();
185 final var streamDetails
= avatar
!= null && avatar
.isPresent()
186 ? Utils
.createStreamDetails(avatar
.get())
188 : forceUploadAvatar
&& avatar
== null ? context
.getAvatarStore()
189 .retrieveProfileAvatar(account
.getSelfRecipientAddress()) : null;
190 try (streamDetails
) {
191 final var avatarUploadParams
= streamDetails
!= null
192 ? AvatarUploadParams
.forAvatar(streamDetails
)
193 : avatar
== null ? AvatarUploadParams
.unchanged(true) : AvatarUploadParams
.unchanged(false);
194 final var paymentsAddress
= Optional
.ofNullable(newProfile
.getMobileCoinAddress())
195 .map(address
-> PaymentUtils
.signPaymentsAddress(address
,
196 account
.getAciIdentityKeyPair().getPrivateKey()));
197 logger
.debug("Uploading new profile");
198 final var avatarPath
= dependencies
.getAccountManager()
199 .setVersionedProfile(account
.getAci(),
200 account
.getProfileKey(),
201 newProfile
.getInternalServiceName(),
202 newProfile
.getAbout() == null ?
"" : newProfile
.getAbout(),
203 newProfile
.getAboutEmoji() == null ?
"" : newProfile
.getAboutEmoji(),
206 List
.of(/* TODO implement support for badges */),
207 account
.getConfigurationStore().getPhoneNumberSharingMode()
208 == PhoneNumberSharingMode
.EVERYBODY
);
209 if (!avatarUploadParams
.keepTheSame
) {
210 builder
.withAvatarUrlPath(avatarPath
.orElse(null));
212 newProfile
= builder
.build();
216 if (avatar
!= null) {
217 if (avatar
.isPresent()) {
218 try (final var streamDetails
= Utils
.createStreamDetails(avatar
.get()).first()) {
219 context
.getAvatarStore()
220 .storeProfileAvatar(account
.getSelfRecipientAddress(),
221 outputStream
-> IOUtils
.copyStream(streamDetails
.getStream(), outputStream
));
224 context
.getAvatarStore().deleteProfileAvatar(account
.getSelfRecipientAddress());
227 account
.getProfileStore().storeProfile(account
.getSelfRecipientId(), newProfile
);
230 public Profile
getSelfProfile() {
231 return getRecipientProfile(account
.getSelfRecipientId());
234 private List
<Profile
> getRecipientProfiles(Collection
<RecipientId
> recipientIds
, boolean force
) {
235 final var profileStore
= account
.getProfileStore();
236 final var profileFetches
= Flowable
.fromIterable(recipientIds
)
237 .filter(recipientId
-> force
|| isProfileRefreshRequired(profileStore
.getProfile(recipientId
)))
238 .map(recipientId
-> retrieveProfile(recipientId
,
239 SignalServiceProfile
.RequestType
.PROFILE
).onErrorComplete());
240 Maybe
.merge(profileFetches
, 10).blockingSubscribe();
242 return recipientIds
.stream().map(profileStore
::getProfile
).toList();
245 private Profile
getRecipientProfile(RecipientId recipientId
, boolean force
) {
246 var profile
= account
.getProfileStore().getProfile(recipientId
);
248 if (!force
&& !isProfileRefreshRequired(profile
)) {
253 blockingGetProfile(retrieveProfile(recipientId
, SignalServiceProfile
.RequestType
.PROFILE
));
254 } catch (IOException e
) {
255 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
258 return account
.getProfileStore().getProfile(recipientId
);
261 private boolean isProfileRefreshRequired(final Profile profile
) {
262 if (profile
== null) {
265 // Profiles are cached for 6h before retrieving them again, unless forced
266 final var now
= System
.currentTimeMillis();
267 return now
- profile
.getLastUpdateTimestamp() >= 6 * 60 * 60 * 1000;
270 private Profile
decryptProfileAndDownloadAvatar(
271 final RecipientId recipientId
, final ProfileKey profileKey
, final SignalServiceProfile encryptedProfile
273 final var avatarPath
= encryptedProfile
.getAvatar();
274 downloadProfileAvatar(recipientId
, avatarPath
, profileKey
);
276 return ProfileUtils
.decryptProfile(profileKey
, encryptedProfile
);
279 public void downloadProfileAvatar(
280 final RecipientId recipientId
, final String avatarPath
, final ProfileKey profileKey
282 var profile
= account
.getProfileStore().getProfile(recipientId
);
283 if (profile
== null || !Objects
.equals(avatarPath
, profile
.getAvatarUrlPath())) {
284 logger
.trace("Downloading profile avatar for {}", recipientId
);
285 downloadProfileAvatar(account
.getRecipientAddressResolver().resolveRecipientAddress(recipientId
),
288 var builder
= profile
== null ? Profile
.newBuilder() : Profile
.newBuilder(profile
);
289 account
.getProfileStore().storeProfile(recipientId
, builder
.withAvatarUrlPath(avatarPath
).build());
293 private ProfileAndCredential
blockingGetProfile(Single
<ProfileAndCredential
> profile
) throws IOException
{
295 return profile
.blockingGet();
296 } catch (RuntimeException e
) {
297 if (e
.getCause() instanceof PushNetworkException
) {
298 throw (PushNetworkException
) e
.getCause();
299 } else if (e
.getCause() instanceof NotFoundException
) {
300 throw (NotFoundException
) e
.getCause();
302 throw new IOException(e
);
307 private Single
<ProfileAndCredential
> retrieveProfile(
308 RecipientId recipientId
, SignalServiceProfile
.RequestType requestType
310 var unidentifiedAccess
= getUnidentifiedAccess(recipientId
);
311 var profileKey
= Optional
.ofNullable(account
.getProfileStore().getProfileKey(recipientId
));
313 logger
.trace("Retrieving profile for {} {}",
315 profileKey
.isPresent() ?
"with profile key" : "without profile key");
316 final var address
= context
.getRecipientHelper().resolveSignalServiceAddress(recipientId
);
317 return retrieveProfile(address
, profileKey
, unidentifiedAccess
, requestType
).doOnSuccess(p
-> {
318 logger
.trace("Got new profile for {}", recipientId
);
319 final var encryptedProfile
= p
.getProfile();
321 if (requestType
== SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
322 || !ExpiringProfileCredentialUtil
.isValid(account
.getProfileStore()
323 .getExpiringProfileKeyCredential(recipientId
))) {
324 logger
.trace("Storing profile credential");
325 final var profileKeyCredential
= p
.getExpiringProfileKeyCredential().orElse(null);
326 account
.getProfileStore().storeExpiringProfileKeyCredential(recipientId
, profileKeyCredential
);
329 final var profile
= account
.getProfileStore().getProfile(recipientId
);
331 if (recipientId
.equals(account
.getSelfRecipientId())) {
332 final var isUnrestricted
= encryptedProfile
.isUnrestrictedUnidentifiedAccess();
333 if (account
.isUnrestrictedUnidentifiedAccess() != isUnrestricted
) {
334 account
.setUnrestrictedUnidentifiedAccess(isUnrestricted
);
338 Profile newProfile
= null;
339 if (profileKey
.isPresent()) {
340 logger
.trace("Decrypting profile");
341 newProfile
= decryptProfileAndDownloadAvatar(recipientId
, profileKey
.get(), encryptedProfile
);
344 if (newProfile
== null) {
346 profile
== null ? Profile
.newBuilder() : Profile
.newBuilder(profile
)
347 ).withLastUpdateTimestamp(System
.currentTimeMillis())
348 .withUnidentifiedAccessMode(ProfileUtils
.getUnidentifiedAccessMode(encryptedProfile
, null))
349 .withCapabilities(ProfileUtils
.getCapabilities(encryptedProfile
))
354 logger
.trace("Storing identity");
355 final var identityKey
= new IdentityKey(Base64
.getDecoder().decode(encryptedProfile
.getIdentityKey()));
356 account
.getIdentityKeyStore().saveIdentity(p
.getProfile().getServiceId(), identityKey
);
357 } catch (InvalidKeyException ignored
) {
358 logger
.warn("Got invalid identity key in profile for {}",
359 context
.getRecipientHelper().resolveSignalServiceAddress(recipientId
).getIdentifier());
362 logger
.trace("Storing profile");
363 account
.getProfileStore().storeProfile(recipientId
, newProfile
);
365 logger
.trace("Done handling retrieved profile");
367 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
368 final var profile
= account
.getProfileStore().getProfile(recipientId
);
369 final var newProfile
= (
370 profile
== null ? Profile
.newBuilder() : Profile
.newBuilder(profile
)
371 ).withLastUpdateTimestamp(System
.currentTimeMillis())
372 .withUnidentifiedAccessMode(Profile
.UnidentifiedAccessMode
.UNKNOWN
)
373 .withCapabilities(Set
.of())
376 account
.getProfileStore().storeProfile(recipientId
, newProfile
);
380 private Single
<ProfileAndCredential
> retrieveProfile(
381 SignalServiceAddress address
,
382 Optional
<ProfileKey
> profileKey
,
383 Optional
<UnidentifiedAccess
> unidentifiedAccess
,
384 SignalServiceProfile
.RequestType requestType
386 final var profileService
= dependencies
.getProfileService();
387 final var locale
= Utils
.getDefaultLocale(Locale
.US
);
389 return profileService
.getProfile(address
, profileKey
, unidentifiedAccess
, requestType
, locale
).map(pair
-> {
390 var processor
= new ProfileService
.ProfileResponseProcessor(pair
);
391 if (processor
.hasResult()) {
392 return processor
.getResult();
393 } else if (processor
.notFound()) {
394 throw new NotFoundException("Profile not found");
396 throw pair
.getExecutionError()
397 .or(pair
::getApplicationError
)
398 .orElseThrow(() -> new IOException("Unknown error while retrieving profile"));
403 private void downloadProfileAvatar(
404 RecipientAddress address
, String avatarPath
, ProfileKey profileKey
406 if (avatarPath
== null) {
408 context
.getAvatarStore().deleteProfileAvatar(address
);
409 } catch (IOException e
) {
410 logger
.warn("Failed to delete local profile avatar, ignoring: {}", e
.getMessage());
416 context
.getAvatarStore()
417 .storeProfileAvatar(address
,
418 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
419 } catch (Throwable e
) {
420 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
424 private void retrieveProfileAvatar(
425 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
426 ) throws IOException
{
427 var tmpFile
= IOUtils
.createTempFile();
428 try (var input
= dependencies
.getMessageReceiver()
429 .retrieveProfileAvatar(avatarPath
,
432 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
433 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
434 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
437 Files
.delete(tmpFile
.toPath());
438 } catch (IOException e
) {
439 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
446 private Optional
<UnidentifiedAccess
> getUnidentifiedAccess(RecipientId recipientId
) {
447 var unidentifiedAccess
= context
.getUnidentifiedAccessHelper().getAccessFor(recipientId
, true);
449 if (unidentifiedAccess
.isPresent()) {
450 return unidentifiedAccess
.get().getTargetUnidentifiedAccess();
453 return Optional
.empty();