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 // 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
<ProfileKeyCredential
> getRecipientProfileKeyCredential(List
<RecipientId
> recipientIds
) {
112 account
.getRecipientStore().setBulkUpdating(true);
113 final var profileFetches
= Flowable
.fromIterable(recipientIds
)
114 .filter(recipientId
-> account
.getProfileStore().getProfileKeyCredential(recipientId
) == null)
115 .map(recipientId
-> retrieveProfile(recipientId
,
116 SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
).onErrorComplete());
117 Maybe
.merge(profileFetches
, 10).blockingSubscribe();
119 account
.getRecipientStore().setBulkUpdating(false);
122 return recipientIds
.stream().map(r
-> account
.getProfileStore().getProfileKeyCredential(r
)).toList();
125 public ProfileKeyCredential
getRecipientProfileKeyCredential(RecipientId recipientId
) {
126 var profileKeyCredential
= account
.getProfileStore().getProfileKeyCredential(recipientId
);
127 if (profileKeyCredential
!= null) {
128 return profileKeyCredential
;
132 blockingGetProfile(retrieveProfile(recipientId
, SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
));
133 } catch (IOException e
) {
134 logger
.warn("Failed to retrieve profile key credential, ignoring: {}", e
.getMessage());
138 return account
.getProfileStore().getProfileKeyCredential(recipientId
);
142 * @param givenName if null, the previous givenName will be kept
143 * @param familyName if null, the previous familyName will be kept
144 * @param about if null, the previous about text will be kept
145 * @param aboutEmoji if null, the previous about emoji will be kept
146 * @param avatar if avatar is null the image from the local avatar store is used (if present),
148 public void setProfile(
150 final String familyName
,
153 Optional
<File
> avatar
,
154 byte[] mobileCoinAddress
155 ) throws IOException
{
156 setProfile(true, false, givenName
, familyName
, about
, aboutEmoji
, avatar
, mobileCoinAddress
);
159 public void setProfile(
160 boolean uploadProfile
,
161 boolean forceUploadAvatar
,
163 final String familyName
,
166 Optional
<File
> avatar
,
167 byte[] mobileCoinAddress
168 ) throws IOException
{
169 var profile
= getSelfProfile();
170 var builder
= profile
== null ? Profile
.newBuilder() : Profile
.newBuilder(profile
);
171 if (givenName
!= null) {
172 builder
.withGivenName(givenName
);
174 if (familyName
!= null) {
175 builder
.withFamilyName(familyName
);
178 builder
.withAbout(about
);
180 if (aboutEmoji
!= null) {
181 builder
.withAboutEmoji(aboutEmoji
);
183 if (mobileCoinAddress
!= null) {
184 builder
.withMobileCoinAddress(mobileCoinAddress
);
186 var newProfile
= builder
.build();
189 final var streamDetails
= avatar
!= null && avatar
.isPresent()
190 ? Utils
.createStreamDetailsFromFile(avatar
.get())
191 : forceUploadAvatar
&& avatar
== null ? context
.getAvatarStore()
192 .retrieveProfileAvatar(account
.getSelfRecipientAddress()) : null;
193 try (streamDetails
) {
194 final var avatarUploadParams
= streamDetails
!= null
195 ? AvatarUploadParams
.forAvatar(streamDetails
)
196 : avatar
== null ? AvatarUploadParams
.unchanged(true) : AvatarUploadParams
.unchanged(false);
197 final var paymentsAddress
= Optional
.ofNullable(newProfile
.getMobileCoinAddress())
198 .map(address
-> PaymentUtils
.signPaymentsAddress(address
,
199 account
.getAciIdentityKeyPair().getPrivateKey()));
200 logger
.debug("Uploading new profile");
201 final var avatarPath
= dependencies
.getAccountManager()
202 .setVersionedProfile(account
.getAci(),
203 account
.getProfileKey(),
204 newProfile
.getInternalServiceName(),
205 newProfile
.getAbout() == null ?
"" : newProfile
.getAbout(),
206 newProfile
.getAboutEmoji() == null ?
"" : newProfile
.getAboutEmoji(),
209 List
.of(/* TODO implement support for badges */));
210 if (!avatarUploadParams
.keepTheSame
) {
211 builder
.withAvatarUrlPath(avatarPath
.orElse(null));
213 newProfile
= builder
.build();
217 if (avatar
!= null) {
218 if (avatar
.isPresent()) {
219 context
.getAvatarStore()
220 .storeProfileAvatar(account
.getSelfRecipientAddress(),
221 outputStream
-> IOUtils
.copyFileToStream(avatar
.get(), outputStream
));
223 context
.getAvatarStore().deleteProfileAvatar(account
.getSelfRecipientAddress());
226 account
.getProfileStore().storeProfile(account
.getSelfRecipientId(), newProfile
);
229 public Profile
getSelfProfile() {
230 return getRecipientProfile(account
.getSelfRecipientId());
233 private List
<Profile
> getRecipientProfiles(Collection
<RecipientId
> recipientIds
, boolean force
) {
234 final var profileStore
= account
.getProfileStore();
236 account
.getRecipientStore().setBulkUpdating(true);
237 final var profileFetches
= Flowable
.fromIterable(recipientIds
)
238 .filter(recipientId
-> force
|| isProfileRefreshRequired(profileStore
.getProfile(recipientId
)))
239 .map(recipientId
-> retrieveProfile(recipientId
,
240 SignalServiceProfile
.RequestType
.PROFILE
).onErrorComplete());
241 Maybe
.merge(profileFetches
, 10).blockingSubscribe();
243 account
.getRecipientStore().setBulkUpdating(false);
246 return recipientIds
.stream().map(profileStore
::getProfile
).toList();
249 private Profile
getRecipientProfile(RecipientId recipientId
, boolean force
) {
250 var profile
= account
.getProfileStore().getProfile(recipientId
);
252 if (!force
&& !isProfileRefreshRequired(profile
)) {
257 blockingGetProfile(retrieveProfile(recipientId
, SignalServiceProfile
.RequestType
.PROFILE
));
258 } catch (IOException e
) {
259 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
262 return account
.getProfileStore().getProfile(recipientId
);
265 private boolean isProfileRefreshRequired(final Profile profile
) {
266 if (profile
== null) {
269 // Profiles are cached for 6h before retrieving them again, unless forced
270 final var now
= System
.currentTimeMillis();
271 return now
- profile
.getLastUpdateTimestamp() >= 6 * 60 * 60 * 1000;
274 private SignalServiceProfile
retrieveProfileSync(String username
) throws IOException
{
275 final var locale
= Utils
.getDefaultLocale(Locale
.US
);
276 return dependencies
.getMessageReceiver().retrieveProfileByUsername(username
, Optional
.empty(), locale
);
279 private Profile
decryptProfileAndDownloadAvatar(
280 final RecipientId recipientId
, final ProfileKey profileKey
, final SignalServiceProfile encryptedProfile
282 final var avatarPath
= encryptedProfile
.getAvatar();
283 downloadProfileAvatar(recipientId
, avatarPath
, profileKey
);
285 return ProfileUtils
.decryptProfile(profileKey
, encryptedProfile
);
288 public void downloadProfileAvatar(
289 final RecipientId recipientId
, final String avatarPath
, final ProfileKey profileKey
291 var profile
= account
.getProfileStore().getProfile(recipientId
);
292 if (profile
== null || !Objects
.equals(avatarPath
, profile
.getAvatarUrlPath())) {
293 logger
.trace("Downloading profile avatar for {}", recipientId
);
294 downloadProfileAvatar(account
.getRecipientAddressResolver().resolveRecipientAddress(recipientId
),
297 var builder
= profile
== null ? Profile
.newBuilder() : Profile
.newBuilder(profile
);
298 account
.getProfileStore().storeProfile(recipientId
, builder
.withAvatarUrlPath(avatarPath
).build());
302 private ProfileAndCredential
blockingGetProfile(Single
<ProfileAndCredential
> profile
) throws IOException
{
304 return profile
.blockingGet();
305 } catch (RuntimeException e
) {
306 if (e
.getCause() instanceof PushNetworkException
) {
307 throw (PushNetworkException
) e
.getCause();
308 } else if (e
.getCause() instanceof NotFoundException
) {
309 throw (NotFoundException
) e
.getCause();
311 throw new IOException(e
);
316 private Single
<ProfileAndCredential
> retrieveProfile(
317 RecipientId recipientId
, SignalServiceProfile
.RequestType requestType
319 var unidentifiedAccess
= getUnidentifiedAccess(recipientId
);
320 var profileKey
= Optional
.ofNullable(account
.getProfileStore().getProfileKey(recipientId
));
322 logger
.trace("Retrieving profile for {} {}",
324 profileKey
.isPresent() ?
"with profile key" : "without profile key");
325 final var address
= context
.getRecipientHelper().resolveSignalServiceAddress(recipientId
);
326 return retrieveProfile(address
, profileKey
, unidentifiedAccess
, requestType
).doOnSuccess(p
-> {
327 logger
.trace("Got new profile for {}", recipientId
);
328 final var encryptedProfile
= p
.getProfile();
330 if (requestType
== SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
331 || account
.getProfileStore().getProfileKeyCredential(recipientId
) == null) {
332 logger
.trace("Storing profile credential");
333 final var profileKeyCredential
= p
.getProfileKeyCredential().orElse(null);
334 account
.getProfileStore().storeProfileKeyCredential(recipientId
, profileKeyCredential
);
337 final var profile
= account
.getProfileStore().getProfile(recipientId
);
339 Profile newProfile
= null;
340 if (profileKey
.isPresent()) {
341 logger
.trace("Decrypting profile");
342 newProfile
= decryptProfileAndDownloadAvatar(recipientId
, profileKey
.get(), encryptedProfile
);
345 if (newProfile
== null) {
347 profile
== null ? Profile
.newBuilder() : Profile
.newBuilder(profile
)
348 ).withLastUpdateTimestamp(System
.currentTimeMillis())
349 .withUnidentifiedAccessMode(ProfileUtils
.getUnidentifiedAccessMode(encryptedProfile
, null))
350 .withCapabilities(ProfileUtils
.getCapabilities(encryptedProfile
))
355 logger
.trace("Storing identity");
356 final var identityKey
= new IdentityKey(Base64
.getDecoder().decode(encryptedProfile
.getIdentityKey()));
357 account
.getIdentityKeyStore().saveIdentity(recipientId
, identityKey
, new Date());
358 } catch (InvalidKeyException ignored
) {
359 logger
.warn("Got invalid identity key in profile for {}",
360 context
.getRecipientHelper().resolveSignalServiceAddress(recipientId
).getIdentifier());
363 logger
.trace("Storing profile");
364 account
.getProfileStore().storeProfile(recipientId
, newProfile
);
366 logger
.trace("Done handling retrieved profile");
368 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
369 final var profile
= account
.getProfileStore().getProfile(recipientId
);
370 final var newProfile
= (
371 profile
== null ? Profile
.newBuilder() : Profile
.newBuilder(profile
)
372 ).withLastUpdateTimestamp(System
.currentTimeMillis())
373 .withUnidentifiedAccessMode(Profile
.UnidentifiedAccessMode
.UNKNOWN
)
374 .withCapabilities(Set
.of())
377 account
.getProfileStore().storeProfile(recipientId
, newProfile
);
381 private Single
<ProfileAndCredential
> retrieveProfile(
382 SignalServiceAddress address
,
383 Optional
<ProfileKey
> profileKey
,
384 Optional
<UnidentifiedAccess
> unidentifiedAccess
,
385 SignalServiceProfile
.RequestType requestType
387 final var profileService
= dependencies
.getProfileService();
388 final var locale
= Utils
.getDefaultLocale(Locale
.US
);
390 return profileService
.getProfile(address
, profileKey
, unidentifiedAccess
, requestType
, locale
).map(pair
-> {
391 var processor
= new ProfileService
.ProfileResponseProcessor(pair
);
392 if (processor
.hasResult()) {
393 return processor
.getResult();
394 } else if (processor
.notFound()) {
395 throw new NotFoundException("Profile not found");
397 throw pair
.getExecutionError()
398 .or(pair
::getApplicationError
)
399 .orElseThrow(() -> new IOException("Unknown error while retrieving profile"));
404 private void downloadProfileAvatar(
405 RecipientAddress address
, String avatarPath
, ProfileKey profileKey
407 if (avatarPath
== null) {
409 context
.getAvatarStore().deleteProfileAvatar(address
);
410 } catch (IOException e
) {
411 logger
.warn("Failed to delete local profile avatar, ignoring: {}", e
.getMessage());
417 context
.getAvatarStore()
418 .storeProfileAvatar(address
,
419 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
420 } catch (Throwable e
) {
421 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
425 private void retrieveProfileAvatar(
426 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
427 ) throws IOException
{
428 var tmpFile
= IOUtils
.createTempFile();
429 try (var input
= dependencies
.getMessageReceiver()
430 .retrieveProfileAvatar(avatarPath
,
433 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
434 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
435 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
438 Files
.delete(tmpFile
.toPath());
439 } catch (IOException e
) {
440 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
447 private Optional
<UnidentifiedAccess
> getUnidentifiedAccess(RecipientId recipientId
) {
448 var unidentifiedAccess
= context
.getUnidentifiedAccessHelper().getAccessFor(recipientId
, true);
450 if (unidentifiedAccess
.isPresent()) {
451 return unidentifiedAccess
.get().getTargetUnidentifiedAccess();
454 return Optional
.empty();