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
.storage
.SignalAccount
;
6 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
7 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientAddress
;
8 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
9 import org
.asamk
.signal
.manager
.util
.IOUtils
;
10 import org
.asamk
.signal
.manager
.util
.ProfileUtils
;
11 import org
.asamk
.signal
.manager
.util
.Utils
;
12 import org
.signal
.libsignal
.protocol
.IdentityKey
;
13 import org
.signal
.libsignal
.protocol
.InvalidKeyException
;
14 import org
.signal
.libsignal
.zkgroup
.profiles
.ProfileKey
;
15 import org
.signal
.libsignal
.zkgroup
.profiles
.ProfileKeyCredential
;
16 import org
.slf4j
.Logger
;
17 import org
.slf4j
.LoggerFactory
;
18 import org
.whispersystems
.signalservice
.api
.crypto
.UnidentifiedAccess
;
19 import org
.whispersystems
.signalservice
.api
.profiles
.AvatarUploadParams
;
20 import org
.whispersystems
.signalservice
.api
.profiles
.ProfileAndCredential
;
21 import org
.whispersystems
.signalservice
.api
.profiles
.SignalServiceProfile
;
22 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
23 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.NotFoundException
;
24 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.PushNetworkException
;
25 import org
.whispersystems
.signalservice
.api
.services
.ProfileService
;
28 import java
.io
.IOException
;
29 import java
.io
.OutputStream
;
30 import java
.nio
.file
.Files
;
31 import java
.util
.Base64
;
32 import java
.util
.Date
;
33 import java
.util
.List
;
34 import java
.util
.Locale
;
35 import java
.util
.Objects
;
36 import java
.util
.Optional
;
39 import io
.reactivex
.rxjava3
.core
.Flowable
;
40 import io
.reactivex
.rxjava3
.core
.Maybe
;
41 import io
.reactivex
.rxjava3
.core
.Single
;
43 public final class ProfileHelper
{
45 private final static Logger logger
= LoggerFactory
.getLogger(ProfileHelper
.class);
47 private final SignalAccount account
;
48 private final SignalDependencies dependencies
;
49 private final Context context
;
51 public ProfileHelper(final Context context
) {
52 this.account
= context
.getAccount();
53 this.dependencies
= context
.getDependencies();
54 this.context
= context
;
57 public Profile
getRecipientProfile(RecipientId recipientId
) {
58 return getRecipientProfile(recipientId
, false);
61 public void refreshRecipientProfile(RecipientId recipientId
) {
62 getRecipientProfile(recipientId
, true);
65 public List
<ProfileKeyCredential
> getRecipientProfileKeyCredential(List
<RecipientId
> recipientIds
) {
67 account
.getRecipientStore().setBulkUpdating(true);
68 final var profileFetches
= Flowable
.fromIterable(recipientIds
)
69 .filter(recipientId
-> account
.getProfileStore().getProfileKeyCredential(recipientId
) == null)
70 .map(recipientId
-> retrieveProfile(recipientId
,
71 SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
).onErrorComplete());
72 Maybe
.merge(profileFetches
, 10).blockingSubscribe();
74 account
.getRecipientStore().setBulkUpdating(false);
77 return recipientIds
.stream().map(r
-> account
.getProfileStore().getProfileKeyCredential(r
)).toList();
80 public ProfileKeyCredential
getRecipientProfileKeyCredential(RecipientId recipientId
) {
81 var profileKeyCredential
= account
.getProfileStore().getProfileKeyCredential(recipientId
);
82 if (profileKeyCredential
!= null) {
83 return profileKeyCredential
;
87 blockingGetProfile(retrieveProfile(recipientId
, SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
));
88 } catch (IOException e
) {
89 logger
.warn("Failed to retrieve profile key credential, ignoring: {}", e
.getMessage());
93 return account
.getProfileStore().getProfileKeyCredential(recipientId
);
97 * @param givenName if null, the previous givenName will be kept
98 * @param familyName if null, the previous familyName will be kept
99 * @param about if null, the previous about text will be kept
100 * @param aboutEmoji if null, the previous about emoji will be kept
101 * @param avatar if avatar is null the image from the local avatar store is used (if present),
103 public void setProfile(
104 String givenName
, final String familyName
, String about
, String aboutEmoji
, Optional
<File
> avatar
105 ) throws IOException
{
106 setProfile(true, givenName
, familyName
, about
, aboutEmoji
, avatar
);
109 public void setProfile(
110 boolean uploadProfile
,
112 final String familyName
,
115 Optional
<File
> avatar
116 ) throws IOException
{
117 var profile
= getRecipientProfile(account
.getSelfRecipientId());
118 var builder
= profile
== null ? Profile
.newBuilder() : Profile
.newBuilder(profile
);
119 if (givenName
!= null) {
120 builder
.withGivenName(givenName
);
122 if (familyName
!= null) {
123 builder
.withFamilyName(familyName
);
126 builder
.withAbout(about
);
128 if (aboutEmoji
!= null) {
129 builder
.withAboutEmoji(aboutEmoji
);
131 var newProfile
= builder
.build();
134 try (final var streamDetails
= avatar
!= null && avatar
.isPresent() ? Utils
.createStreamDetailsFromFile(
135 avatar
.get()) : null) {
136 final var avatarUploadParams
= avatar
== null
137 ? AvatarUploadParams
.unchanged(true)
139 ? AvatarUploadParams
.forAvatar(streamDetails
)
140 : AvatarUploadParams
.unchanged(false);
141 final var avatarPath
= dependencies
.getAccountManager()
142 .setVersionedProfile(account
.getAci(),
143 account
.getProfileKey(),
144 newProfile
.getInternalServiceName(),
145 newProfile
.getAbout() == null ?
"" : newProfile
.getAbout(),
146 newProfile
.getAboutEmoji() == null ?
"" : newProfile
.getAboutEmoji(),
149 List
.of(/* TODO */));
150 builder
.withAvatarUrlPath(avatarPath
.orElse(null));
151 newProfile
= builder
.build();
155 if (avatar
!= null) {
156 if (avatar
.isPresent()) {
157 context
.getAvatarStore()
158 .storeProfileAvatar(account
.getSelfRecipientAddress(),
159 outputStream
-> IOUtils
.copyFileToStream(avatar
.get(), outputStream
));
161 context
.getAvatarStore().deleteProfileAvatar(account
.getSelfRecipientAddress());
164 account
.getProfileStore().storeProfile(account
.getSelfRecipientId(), newProfile
);
167 public List
<Profile
> getRecipientProfile(List
<RecipientId
> recipientIds
) {
169 account
.getRecipientStore().setBulkUpdating(true);
170 final var profileFetches
= Flowable
.fromIterable(recipientIds
)
171 .filter(recipientId
-> isProfileRefreshRequired(account
.getProfileStore().getProfile(recipientId
)))
172 .map(recipientId
-> retrieveProfile(recipientId
,
173 SignalServiceProfile
.RequestType
.PROFILE
).onErrorComplete());
174 Maybe
.merge(profileFetches
, 10).blockingSubscribe();
176 account
.getRecipientStore().setBulkUpdating(false);
179 return recipientIds
.stream().map(r
-> account
.getProfileStore().getProfile(r
)).toList();
182 private Profile
getRecipientProfile(RecipientId recipientId
, boolean force
) {
183 var profile
= account
.getProfileStore().getProfile(recipientId
);
185 if (!force
&& !isProfileRefreshRequired(profile
)) {
190 blockingGetProfile(retrieveProfile(recipientId
, SignalServiceProfile
.RequestType
.PROFILE
));
191 } catch (IOException e
) {
192 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
195 return account
.getProfileStore().getProfile(recipientId
);
198 private boolean isProfileRefreshRequired(final Profile profile
) {
199 if (profile
== null) {
202 // Profiles are cached for 6h before retrieving them again, unless forced
203 final var now
= System
.currentTimeMillis();
204 return now
- profile
.getLastUpdateTimestamp() >= 6 * 60 * 60 * 1000;
207 private SignalServiceProfile
retrieveProfileSync(String username
) throws IOException
{
208 final var locale
= Utils
.getDefaultLocale(Locale
.US
);
209 return dependencies
.getMessageReceiver().retrieveProfileByUsername(username
, Optional
.empty(), locale
);
212 private Profile
decryptProfileAndDownloadAvatar(
213 final RecipientId recipientId
, final ProfileKey profileKey
, final SignalServiceProfile encryptedProfile
215 final var avatarPath
= encryptedProfile
.getAvatar();
216 downloadProfileAvatar(recipientId
, avatarPath
, profileKey
);
218 return ProfileUtils
.decryptProfile(profileKey
, encryptedProfile
);
221 public void downloadProfileAvatar(
222 final RecipientId recipientId
, final String avatarPath
, final ProfileKey profileKey
224 var profile
= account
.getProfileStore().getProfile(recipientId
);
225 if (profile
== null || !Objects
.equals(avatarPath
, profile
.getAvatarUrlPath())) {
226 logger
.trace("Downloading profile avatar for {}", recipientId
);
227 downloadProfileAvatar(account
.getRecipientStore().resolveRecipientAddress(recipientId
),
230 var builder
= profile
== null ? Profile
.newBuilder() : Profile
.newBuilder(profile
);
231 account
.getProfileStore().storeProfile(recipientId
, builder
.withAvatarUrlPath(avatarPath
).build());
235 private ProfileAndCredential
blockingGetProfile(Single
<ProfileAndCredential
> profile
) throws IOException
{
237 return profile
.blockingGet();
238 } catch (RuntimeException e
) {
239 if (e
.getCause() instanceof PushNetworkException
) {
240 throw (PushNetworkException
) e
.getCause();
241 } else if (e
.getCause() instanceof NotFoundException
) {
242 throw (NotFoundException
) e
.getCause();
244 throw new IOException(e
);
249 private Single
<ProfileAndCredential
> retrieveProfile(
250 RecipientId recipientId
, SignalServiceProfile
.RequestType requestType
252 var unidentifiedAccess
= getUnidentifiedAccess(recipientId
);
253 var profileKey
= Optional
.ofNullable(account
.getProfileStore().getProfileKey(recipientId
));
255 logger
.trace("Retrieving profile for {} {}",
257 profileKey
.isPresent() ?
"with profile key" : "without profile key");
258 final var address
= context
.getRecipientHelper().resolveSignalServiceAddress(recipientId
);
259 return retrieveProfile(address
, profileKey
, unidentifiedAccess
, requestType
).doOnSuccess(p
-> {
260 logger
.trace("Got new profile for {}", recipientId
);
261 final var encryptedProfile
= p
.getProfile();
263 if (requestType
== SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
264 || account
.getProfileStore().getProfileKeyCredential(recipientId
) == null) {
265 logger
.trace("Storing profile credential");
266 final var profileKeyCredential
= p
.getProfileKeyCredential().orElse(null);
267 account
.getProfileStore().storeProfileKeyCredential(recipientId
, profileKeyCredential
);
270 final var profile
= account
.getProfileStore().getProfile(recipientId
);
272 Profile newProfile
= null;
273 if (profileKey
.isPresent()) {
274 logger
.trace("Decrypting profile");
275 newProfile
= decryptProfileAndDownloadAvatar(recipientId
, profileKey
.get(), encryptedProfile
);
278 if (newProfile
== null) {
280 profile
== null ? Profile
.newBuilder() : Profile
.newBuilder(profile
)
281 ).withLastUpdateTimestamp(System
.currentTimeMillis())
282 .withUnidentifiedAccessMode(ProfileUtils
.getUnidentifiedAccessMode(encryptedProfile
, null))
283 .withCapabilities(ProfileUtils
.getCapabilities(encryptedProfile
))
288 logger
.trace("Storing identity");
289 final var identityKey
= new IdentityKey(Base64
.getDecoder().decode(encryptedProfile
.getIdentityKey()));
290 account
.getIdentityKeyStore().saveIdentity(recipientId
, identityKey
, new Date());
291 } catch (InvalidKeyException ignored
) {
292 logger
.warn("Got invalid identity key in profile for {}",
293 context
.getRecipientHelper().resolveSignalServiceAddress(recipientId
).getIdentifier());
296 logger
.trace("Storing profile");
297 account
.getProfileStore().storeProfile(recipientId
, newProfile
);
299 logger
.trace("Done handling retrieved profile");
301 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
302 final var profile
= account
.getProfileStore().getProfile(recipientId
);
303 final var newProfile
= (
304 profile
== null ? Profile
.newBuilder() : Profile
.newBuilder(profile
)
305 ).withLastUpdateTimestamp(System
.currentTimeMillis())
306 .withUnidentifiedAccessMode(Profile
.UnidentifiedAccessMode
.UNKNOWN
)
307 .withCapabilities(Set
.of())
310 account
.getProfileStore().storeProfile(recipientId
, newProfile
);
314 private Single
<ProfileAndCredential
> retrieveProfile(
315 SignalServiceAddress address
,
316 Optional
<ProfileKey
> profileKey
,
317 Optional
<UnidentifiedAccess
> unidentifiedAccess
,
318 SignalServiceProfile
.RequestType requestType
320 final var profileService
= dependencies
.getProfileService();
321 final var locale
= Utils
.getDefaultLocale(Locale
.US
);
323 return profileService
.getProfile(address
, profileKey
, unidentifiedAccess
, requestType
, locale
).map(pair
-> {
324 var processor
= new ProfileService
.ProfileResponseProcessor(pair
);
325 if (processor
.hasResult()) {
326 return processor
.getResult();
327 } else if (processor
.notFound()) {
328 throw new NotFoundException("Profile not found");
330 throw pair
.getExecutionError()
331 .or(pair
::getApplicationError
)
332 .orElseThrow(() -> new IOException("Unknown error while retrieving profile"));
337 private void downloadProfileAvatar(
338 RecipientAddress address
, String avatarPath
, ProfileKey profileKey
340 if (avatarPath
== null) {
342 context
.getAvatarStore().deleteProfileAvatar(address
);
343 } catch (IOException e
) {
344 logger
.warn("Failed to delete local profile avatar, ignoring: {}", e
.getMessage());
350 context
.getAvatarStore()
351 .storeProfileAvatar(address
,
352 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
353 } catch (Throwable e
) {
354 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
358 private void retrieveProfileAvatar(
359 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
360 ) throws IOException
{
361 var tmpFile
= IOUtils
.createTempFile();
362 try (var input
= dependencies
.getMessageReceiver()
363 .retrieveProfileAvatar(avatarPath
,
366 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
367 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
368 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
371 Files
.delete(tmpFile
.toPath());
372 } catch (IOException e
) {
373 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
380 private Optional
<UnidentifiedAccess
> getUnidentifiedAccess(RecipientId recipientId
) {
381 var unidentifiedAccess
= context
.getUnidentifiedAccessHelper().getAccessFor(recipientId
, true);
383 if (unidentifiedAccess
.isPresent()) {
384 return unidentifiedAccess
.get().getTargetUnidentifiedAccess();
387 return Optional
.empty();