1 package org
.asamk
.signal
.manager
.helper
;
3 import org
.asamk
.signal
.manager
.SignalDependencies
;
4 import org
.asamk
.signal
.manager
.config
.ServiceConfig
;
5 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
6 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
7 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
8 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV2
;
9 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
10 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientAddress
;
11 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
12 import org
.asamk
.signal
.manager
.util
.IOUtils
;
13 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
14 import org
.asamk
.signal
.manager
.util
.PaymentUtils
;
15 import org
.asamk
.signal
.manager
.util
.ProfileUtils
;
16 import org
.asamk
.signal
.manager
.util
.Utils
;
17 import org
.signal
.libsignal
.protocol
.IdentityKey
;
18 import org
.signal
.libsignal
.protocol
.InvalidKeyException
;
19 import org
.signal
.libsignal
.zkgroup
.profiles
.ProfileKey
;
20 import org
.signal
.libsignal
.zkgroup
.profiles
.ProfileKeyCredential
;
21 import org
.slf4j
.Logger
;
22 import org
.slf4j
.LoggerFactory
;
23 import org
.whispersystems
.signalservice
.api
.crypto
.UnidentifiedAccess
;
24 import org
.whispersystems
.signalservice
.api
.profiles
.AvatarUploadParams
;
25 import org
.whispersystems
.signalservice
.api
.profiles
.ProfileAndCredential
;
26 import org
.whispersystems
.signalservice
.api
.profiles
.SignalServiceProfile
;
27 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
28 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.NotFoundException
;
29 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.PushNetworkException
;
30 import org
.whispersystems
.signalservice
.api
.services
.ProfileService
;
33 import java
.io
.IOException
;
34 import java
.io
.OutputStream
;
35 import java
.nio
.file
.Files
;
36 import java
.util
.Base64
;
37 import java
.util
.Collection
;
38 import java
.util
.Date
;
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 final static 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 var profileKey
= KeyUtils
.createProfileKey();
65 account
.setProfileKey(profileKey
);
66 context
.getAccountHelper().updateAccountAttributes();
67 setProfile(true, true, null, null, null, null, null, null);
68 // TODO update profile key in storage
70 final var recipientIds
= account
.getRecipientStore().getRecipientIdsWithEnabledProfileSharing();
71 for (final var recipientId
: recipientIds
) {
72 context
.getSendHelper().sendProfileKey(recipientId
);
75 final var selfRecipientId
= account
.getSelfRecipientId();
76 final var activeGroupIds
= account
.getGroupStore()
79 .filter(g
-> g
instanceof GroupInfoV2
&& g
.isMember(selfRecipientId
))
80 .map(g
-> (GroupInfoV2
) g
)
81 .map(GroupInfoV2
::getGroupId
)
83 for (final var groupId
: activeGroupIds
) {
85 context
.getGroupHelper().updateGroupProfileKey(groupId
);
86 } catch (GroupNotFoundException
| NotAGroupMemberException
| IOException e
) {
87 logger
.warn("Failed to update group profile key: {}", e
.getMessage());
92 public Profile
getRecipientProfile(RecipientId recipientId
) {
93 return getRecipientProfile(recipientId
, false);
96 public List
<Profile
> getRecipientProfiles(Collection
<RecipientId
> recipientIds
) {
97 return getRecipientProfiles(recipientIds
, false);
100 public void refreshRecipientProfile(RecipientId recipientId
) {
101 getRecipientProfile(recipientId
, true);
104 public void refreshRecipientProfiles(Collection
<RecipientId
> recipientIds
) {
105 getRecipientProfiles(recipientIds
, true);
108 public List
<ProfileKeyCredential
> getRecipientProfileKeyCredential(List
<RecipientId
> recipientIds
) {
110 account
.getRecipientStore().setBulkUpdating(true);
111 final var profileFetches
= Flowable
.fromIterable(recipientIds
)
112 .filter(recipientId
-> account
.getProfileStore().getProfileKeyCredential(recipientId
) == null)
113 .map(recipientId
-> retrieveProfile(recipientId
,
114 SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
).onErrorComplete());
115 Maybe
.merge(profileFetches
, 10).blockingSubscribe();
117 account
.getRecipientStore().setBulkUpdating(false);
120 return recipientIds
.stream().map(r
-> account
.getProfileStore().getProfileKeyCredential(r
)).toList();
123 public ProfileKeyCredential
getRecipientProfileKeyCredential(RecipientId recipientId
) {
124 var profileKeyCredential
= account
.getProfileStore().getProfileKeyCredential(recipientId
);
125 if (profileKeyCredential
!= null) {
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().getProfileKeyCredential(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
<File
> 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
<File
> 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
.createStreamDetailsFromFile(avatar
.get())
189 : forceUploadAvatar
&& avatar
== null ? context
.getAvatarStore()
190 .retrieveProfileAvatar(account
.getSelfRecipientAddress()) : null;
191 try (streamDetails
) {
192 final var avatarUploadParams
= streamDetails
!= null
193 ? AvatarUploadParams
.forAvatar(streamDetails
)
194 : avatar
== null ? AvatarUploadParams
.unchanged(true) : AvatarUploadParams
.unchanged(false);
195 final var paymentsAddress
= Optional
.ofNullable(newProfile
.getMobileCoinAddress())
196 .map(address
-> PaymentUtils
.signPaymentsAddress(address
,
197 account
.getAciIdentityKeyPair().getPrivateKey()));
198 logger
.debug("Uploading new profile");
199 final var avatarPath
= dependencies
.getAccountManager()
200 .setVersionedProfile(account
.getAci(),
201 account
.getProfileKey(),
202 newProfile
.getInternalServiceName(),
203 newProfile
.getAbout() == null ?
"" : newProfile
.getAbout(),
204 newProfile
.getAboutEmoji() == null ?
"" : newProfile
.getAboutEmoji(),
207 List
.of(/* TODO implement support for badges */));
208 if (!avatarUploadParams
.keepTheSame
) {
209 builder
.withAvatarUrlPath(avatarPath
.orElse(null));
211 newProfile
= builder
.build();
215 if (avatar
!= null) {
216 if (avatar
.isPresent()) {
217 context
.getAvatarStore()
218 .storeProfileAvatar(account
.getSelfRecipientAddress(),
219 outputStream
-> IOUtils
.copyFileToStream(avatar
.get(), outputStream
));
221 context
.getAvatarStore().deleteProfileAvatar(account
.getSelfRecipientAddress());
224 account
.getProfileStore().storeProfile(account
.getSelfRecipientId(), newProfile
);
227 public Profile
getSelfProfile() {
228 return getRecipientProfile(account
.getSelfRecipientId());
231 private List
<Profile
> getRecipientProfiles(Collection
<RecipientId
> recipientIds
, boolean force
) {
232 final var profileStore
= account
.getProfileStore();
234 account
.getRecipientStore().setBulkUpdating(true);
235 final var profileFetches
= Flowable
.fromIterable(recipientIds
)
236 .filter(recipientId
-> force
|| isProfileRefreshRequired(profileStore
.getProfile(recipientId
)))
237 .map(recipientId
-> retrieveProfile(recipientId
,
238 SignalServiceProfile
.RequestType
.PROFILE
).onErrorComplete());
239 Maybe
.merge(profileFetches
, 10).blockingSubscribe();
241 account
.getRecipientStore().setBulkUpdating(false);
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 SignalServiceProfile
retrieveProfileSync(String username
) throws IOException
{
273 final var locale
= Utils
.getDefaultLocale(Locale
.US
);
274 return dependencies
.getMessageReceiver().retrieveProfileByUsername(username
, Optional
.empty(), locale
);
277 private Profile
decryptProfileAndDownloadAvatar(
278 final RecipientId recipientId
, final ProfileKey profileKey
, final SignalServiceProfile encryptedProfile
280 final var avatarPath
= encryptedProfile
.getAvatar();
281 downloadProfileAvatar(recipientId
, avatarPath
, profileKey
);
283 return ProfileUtils
.decryptProfile(profileKey
, encryptedProfile
);
286 public void downloadProfileAvatar(
287 final RecipientId recipientId
, final String avatarPath
, final ProfileKey profileKey
289 var profile
= account
.getProfileStore().getProfile(recipientId
);
290 if (profile
== null || !Objects
.equals(avatarPath
, profile
.getAvatarUrlPath())) {
291 logger
.trace("Downloading profile avatar for {}", recipientId
);
292 downloadProfileAvatar(account
.getRecipientStore().resolveRecipientAddress(recipientId
),
295 var builder
= profile
== null ? Profile
.newBuilder() : Profile
.newBuilder(profile
);
296 account
.getProfileStore().storeProfile(recipientId
, builder
.withAvatarUrlPath(avatarPath
).build());
300 private ProfileAndCredential
blockingGetProfile(Single
<ProfileAndCredential
> profile
) throws IOException
{
302 return profile
.blockingGet();
303 } catch (RuntimeException e
) {
304 if (e
.getCause() instanceof PushNetworkException
) {
305 throw (PushNetworkException
) e
.getCause();
306 } else if (e
.getCause() instanceof NotFoundException
) {
307 throw (NotFoundException
) e
.getCause();
309 throw new IOException(e
);
314 private Single
<ProfileAndCredential
> retrieveProfile(
315 RecipientId recipientId
, SignalServiceProfile
.RequestType requestType
317 var unidentifiedAccess
= getUnidentifiedAccess(recipientId
);
318 var profileKey
= Optional
.ofNullable(account
.getProfileStore().getProfileKey(recipientId
));
320 logger
.trace("Retrieving profile for {} {}",
322 profileKey
.isPresent() ?
"with profile key" : "without profile key");
323 final var address
= context
.getRecipientHelper().resolveSignalServiceAddress(recipientId
);
324 return retrieveProfile(address
, profileKey
, unidentifiedAccess
, requestType
).doOnSuccess(p
-> {
325 logger
.trace("Got new profile for {}", recipientId
);
326 final var encryptedProfile
= p
.getProfile();
328 if (requestType
== SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
329 || account
.getProfileStore().getProfileKeyCredential(recipientId
) == null) {
330 logger
.trace("Storing profile credential");
331 final var profileKeyCredential
= p
.getProfileKeyCredential().orElse(null);
332 account
.getProfileStore().storeProfileKeyCredential(recipientId
, profileKeyCredential
);
335 final var profile
= account
.getProfileStore().getProfile(recipientId
);
337 Profile newProfile
= null;
338 if (profileKey
.isPresent()) {
339 logger
.trace("Decrypting profile");
340 newProfile
= decryptProfileAndDownloadAvatar(recipientId
, profileKey
.get(), encryptedProfile
);
343 if (newProfile
== null) {
345 profile
== null ? Profile
.newBuilder() : Profile
.newBuilder(profile
)
346 ).withLastUpdateTimestamp(System
.currentTimeMillis())
347 .withUnidentifiedAccessMode(ProfileUtils
.getUnidentifiedAccessMode(encryptedProfile
, null))
348 .withCapabilities(ProfileUtils
.getCapabilities(encryptedProfile
))
353 logger
.trace("Storing identity");
354 final var identityKey
= new IdentityKey(Base64
.getDecoder().decode(encryptedProfile
.getIdentityKey()));
355 account
.getIdentityKeyStore().saveIdentity(recipientId
, identityKey
, new Date());
356 } catch (InvalidKeyException ignored
) {
357 logger
.warn("Got invalid identity key in profile for {}",
358 context
.getRecipientHelper().resolveSignalServiceAddress(recipientId
).getIdentifier());
361 logger
.trace("Storing profile");
362 account
.getProfileStore().storeProfile(recipientId
, newProfile
);
364 logger
.trace("Done handling retrieved profile");
366 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
367 final var profile
= account
.getProfileStore().getProfile(recipientId
);
368 final var newProfile
= (
369 profile
== null ? Profile
.newBuilder() : Profile
.newBuilder(profile
)
370 ).withLastUpdateTimestamp(System
.currentTimeMillis())
371 .withUnidentifiedAccessMode(Profile
.UnidentifiedAccessMode
.UNKNOWN
)
372 .withCapabilities(Set
.of())
375 account
.getProfileStore().storeProfile(recipientId
, newProfile
);
379 private Single
<ProfileAndCredential
> retrieveProfile(
380 SignalServiceAddress address
,
381 Optional
<ProfileKey
> profileKey
,
382 Optional
<UnidentifiedAccess
> unidentifiedAccess
,
383 SignalServiceProfile
.RequestType requestType
385 final var profileService
= dependencies
.getProfileService();
386 final var locale
= Utils
.getDefaultLocale(Locale
.US
);
388 return profileService
.getProfile(address
, profileKey
, unidentifiedAccess
, requestType
, locale
).map(pair
-> {
389 var processor
= new ProfileService
.ProfileResponseProcessor(pair
);
390 if (processor
.hasResult()) {
391 return processor
.getResult();
392 } else if (processor
.notFound()) {
393 throw new NotFoundException("Profile not found");
395 throw pair
.getExecutionError()
396 .or(pair
::getApplicationError
)
397 .orElseThrow(() -> new IOException("Unknown error while retrieving profile"));
402 private void downloadProfileAvatar(
403 RecipientAddress address
, String avatarPath
, ProfileKey profileKey
405 if (avatarPath
== null) {
407 context
.getAvatarStore().deleteProfileAvatar(address
);
408 } catch (IOException e
) {
409 logger
.warn("Failed to delete local profile avatar, ignoring: {}", e
.getMessage());
415 context
.getAvatarStore()
416 .storeProfileAvatar(address
,
417 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
418 } catch (Throwable e
) {
419 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
423 private void retrieveProfileAvatar(
424 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
425 ) throws IOException
{
426 var tmpFile
= IOUtils
.createTempFile();
427 try (var input
= dependencies
.getMessageReceiver()
428 .retrieveProfileAvatar(avatarPath
,
431 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
432 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
433 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
436 Files
.delete(tmpFile
.toPath());
437 } catch (IOException e
) {
438 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
445 private Optional
<UnidentifiedAccess
> getUnidentifiedAccess(RecipientId recipientId
) {
446 var unidentifiedAccess
= context
.getUnidentifiedAccessHelper().getAccessFor(recipientId
, true);
448 if (unidentifiedAccess
.isPresent()) {
449 return unidentifiedAccess
.get().getTargetUnidentifiedAccess();
452 return Optional
.empty();