1 package org
.asamk
.signal
.manager
.helper
;
3 import com
.google
.protobuf
.InvalidProtocolBufferException
;
5 import org
.asamk
.signal
.manager
.SignalDependencies
;
6 import org
.asamk
.signal
.manager
.config
.ServiceConfig
;
7 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
8 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
9 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientAddress
;
10 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
11 import org
.asamk
.signal
.manager
.util
.IOUtils
;
12 import org
.asamk
.signal
.manager
.util
.ProfileUtils
;
13 import org
.asamk
.signal
.manager
.util
.Utils
;
14 import org
.signal
.libsignal
.protocol
.IdentityKey
;
15 import org
.signal
.libsignal
.protocol
.InvalidKeyException
;
16 import org
.signal
.libsignal
.zkgroup
.profiles
.ProfileKey
;
17 import org
.signal
.libsignal
.zkgroup
.profiles
.ProfileKeyCredential
;
18 import org
.slf4j
.Logger
;
19 import org
.slf4j
.LoggerFactory
;
20 import org
.whispersystems
.signalservice
.api
.crypto
.UnidentifiedAccess
;
21 import org
.whispersystems
.signalservice
.api
.profiles
.AvatarUploadParams
;
22 import org
.whispersystems
.signalservice
.api
.profiles
.ProfileAndCredential
;
23 import org
.whispersystems
.signalservice
.api
.profiles
.SignalServiceProfile
;
24 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
25 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.NotFoundException
;
26 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.PushNetworkException
;
27 import org
.whispersystems
.signalservice
.api
.services
.ProfileService
;
28 import org
.whispersystems
.signalservice
.internal
.push
.SignalServiceProtos
;
31 import java
.io
.IOException
;
32 import java
.io
.OutputStream
;
33 import java
.nio
.file
.Files
;
34 import java
.util
.Base64
;
35 import java
.util
.Date
;
36 import java
.util
.List
;
37 import java
.util
.Locale
;
38 import java
.util
.Objects
;
39 import java
.util
.Optional
;
42 import io
.reactivex
.rxjava3
.core
.Flowable
;
43 import io
.reactivex
.rxjava3
.core
.Maybe
;
44 import io
.reactivex
.rxjava3
.core
.Single
;
46 public final class ProfileHelper
{
48 private final static Logger logger
= LoggerFactory
.getLogger(ProfileHelper
.class);
50 private final SignalAccount account
;
51 private final SignalDependencies dependencies
;
52 private final Context context
;
54 public ProfileHelper(final Context context
) {
55 this.account
= context
.getAccount();
56 this.dependencies
= context
.getDependencies();
57 this.context
= context
;
60 public Profile
getRecipientProfile(RecipientId recipientId
) {
61 return getRecipientProfile(recipientId
, false);
64 public void refreshRecipientProfile(RecipientId recipientId
) {
65 getRecipientProfile(recipientId
, true);
68 public List
<ProfileKeyCredential
> getRecipientProfileKeyCredential(List
<RecipientId
> recipientIds
) {
70 account
.getRecipientStore().setBulkUpdating(true);
71 final var profileFetches
= Flowable
.fromIterable(recipientIds
)
72 .filter(recipientId
-> account
.getProfileStore().getProfileKeyCredential(recipientId
) == null)
73 .map(recipientId
-> retrieveProfile(recipientId
,
74 SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
).onErrorComplete());
75 Maybe
.merge(profileFetches
, 10).blockingSubscribe();
77 account
.getRecipientStore().setBulkUpdating(false);
80 return recipientIds
.stream().map(r
-> account
.getProfileStore().getProfileKeyCredential(r
)).toList();
83 public ProfileKeyCredential
getRecipientProfileKeyCredential(RecipientId recipientId
) {
84 var profileKeyCredential
= account
.getProfileStore().getProfileKeyCredential(recipientId
);
85 if (profileKeyCredential
!= null) {
86 return profileKeyCredential
;
90 blockingGetProfile(retrieveProfile(recipientId
, SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
));
91 } catch (IOException e
) {
92 logger
.warn("Failed to retrieve profile key credential, ignoring: {}", e
.getMessage());
96 return account
.getProfileStore().getProfileKeyCredential(recipientId
);
100 * @param givenName if null, the previous givenName will be kept
101 * @param familyName if null, the previous familyName will be kept
102 * @param about if null, the previous about text will be kept
103 * @param aboutEmoji if null, the previous about emoji will be kept
104 * @param avatar if avatar is null the image from the local avatar store is used (if present),
106 public void setProfile(
107 String givenName
, final String familyName
, String about
, String aboutEmoji
, Optional
<File
> avatar
108 ) throws IOException
{
109 setProfile(true, givenName
, familyName
, about
, aboutEmoji
, avatar
);
112 public void setProfile(
113 boolean uploadProfile
,
115 final String familyName
,
118 Optional
<File
> avatar
119 ) throws IOException
{
120 var profile
= getSelfProfile();
121 var builder
= profile
== null ? Profile
.newBuilder() : Profile
.newBuilder(profile
);
122 if (givenName
!= null) {
123 builder
.withGivenName(givenName
);
125 if (familyName
!= null) {
126 builder
.withFamilyName(familyName
);
129 builder
.withAbout(about
);
131 if (aboutEmoji
!= null) {
132 builder
.withAboutEmoji(aboutEmoji
);
134 var newProfile
= builder
.build();
137 try (final var streamDetails
= avatar
!= null && avatar
.isPresent() ? Utils
.createStreamDetailsFromFile(
138 avatar
.get()) : null) {
139 final var avatarUploadParams
= avatar
== null
140 ? AvatarUploadParams
.unchanged(true)
142 ? AvatarUploadParams
.forAvatar(streamDetails
)
143 : AvatarUploadParams
.unchanged(false);
144 final var paymentsAddress
= Optional
.ofNullable(newProfile
.getPaymentAddress()).map(data
-> {
146 return SignalServiceProtos
.PaymentAddress
.parseFrom(data
);
147 } catch (InvalidProtocolBufferException e
) {
151 final var avatarPath
= dependencies
.getAccountManager()
152 .setVersionedProfile(account
.getAci(),
153 account
.getProfileKey(),
154 newProfile
.getInternalServiceName(),
155 newProfile
.getAbout() == null ?
"" : newProfile
.getAbout(),
156 newProfile
.getAboutEmoji() == null ?
"" : newProfile
.getAboutEmoji(),
159 List
.of(/* TODO */));
160 builder
.withAvatarUrlPath(avatarPath
.orElse(null));
161 newProfile
= builder
.build();
165 if (avatar
!= null) {
166 if (avatar
.isPresent()) {
167 context
.getAvatarStore()
168 .storeProfileAvatar(account
.getSelfRecipientAddress(),
169 outputStream
-> IOUtils
.copyFileToStream(avatar
.get(), outputStream
));
171 context
.getAvatarStore().deleteProfileAvatar(account
.getSelfRecipientAddress());
174 account
.getProfileStore().storeProfile(account
.getSelfRecipientId(), newProfile
);
177 public Profile
getSelfProfile() {
178 return getRecipientProfile(account
.getSelfRecipientId());
181 public List
<Profile
> getRecipientProfile(List
<RecipientId
> recipientIds
) {
183 account
.getRecipientStore().setBulkUpdating(true);
184 final var profileFetches
= Flowable
.fromIterable(recipientIds
)
185 .filter(recipientId
-> isProfileRefreshRequired(account
.getProfileStore().getProfile(recipientId
)))
186 .map(recipientId
-> retrieveProfile(recipientId
,
187 SignalServiceProfile
.RequestType
.PROFILE
).onErrorComplete());
188 Maybe
.merge(profileFetches
, 10).blockingSubscribe();
190 account
.getRecipientStore().setBulkUpdating(false);
193 return recipientIds
.stream().map(r
-> account
.getProfileStore().getProfile(r
)).toList();
196 private Profile
getRecipientProfile(RecipientId recipientId
, boolean force
) {
197 var profile
= account
.getProfileStore().getProfile(recipientId
);
199 if (!force
&& !isProfileRefreshRequired(profile
)) {
204 blockingGetProfile(retrieveProfile(recipientId
, SignalServiceProfile
.RequestType
.PROFILE
));
205 } catch (IOException e
) {
206 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
209 return account
.getProfileStore().getProfile(recipientId
);
212 private boolean isProfileRefreshRequired(final Profile profile
) {
213 if (profile
== null) {
216 // Profiles are cached for 6h before retrieving them again, unless forced
217 final var now
= System
.currentTimeMillis();
218 return now
- profile
.getLastUpdateTimestamp() >= 6 * 60 * 60 * 1000;
221 private SignalServiceProfile
retrieveProfileSync(String username
) throws IOException
{
222 final var locale
= Utils
.getDefaultLocale(Locale
.US
);
223 return dependencies
.getMessageReceiver().retrieveProfileByUsername(username
, Optional
.empty(), locale
);
226 private Profile
decryptProfileAndDownloadAvatar(
227 final RecipientId recipientId
, final ProfileKey profileKey
, final SignalServiceProfile encryptedProfile
229 final var avatarPath
= encryptedProfile
.getAvatar();
230 downloadProfileAvatar(recipientId
, avatarPath
, profileKey
);
232 return ProfileUtils
.decryptProfile(profileKey
, encryptedProfile
);
235 public void downloadProfileAvatar(
236 final RecipientId recipientId
, final String avatarPath
, final ProfileKey profileKey
238 var profile
= account
.getProfileStore().getProfile(recipientId
);
239 if (profile
== null || !Objects
.equals(avatarPath
, profile
.getAvatarUrlPath())) {
240 logger
.trace("Downloading profile avatar for {}", recipientId
);
241 downloadProfileAvatar(account
.getRecipientStore().resolveRecipientAddress(recipientId
),
244 var builder
= profile
== null ? Profile
.newBuilder() : Profile
.newBuilder(profile
);
245 account
.getProfileStore().storeProfile(recipientId
, builder
.withAvatarUrlPath(avatarPath
).build());
249 private ProfileAndCredential
blockingGetProfile(Single
<ProfileAndCredential
> profile
) throws IOException
{
251 return profile
.blockingGet();
252 } catch (RuntimeException e
) {
253 if (e
.getCause() instanceof PushNetworkException
) {
254 throw (PushNetworkException
) e
.getCause();
255 } else if (e
.getCause() instanceof NotFoundException
) {
256 throw (NotFoundException
) e
.getCause();
258 throw new IOException(e
);
263 private Single
<ProfileAndCredential
> retrieveProfile(
264 RecipientId recipientId
, SignalServiceProfile
.RequestType requestType
266 var unidentifiedAccess
= getUnidentifiedAccess(recipientId
);
267 var profileKey
= Optional
.ofNullable(account
.getProfileStore().getProfileKey(recipientId
));
269 logger
.trace("Retrieving profile for {} {}",
271 profileKey
.isPresent() ?
"with profile key" : "without profile key");
272 final var address
= context
.getRecipientHelper().resolveSignalServiceAddress(recipientId
);
273 return retrieveProfile(address
, profileKey
, unidentifiedAccess
, requestType
).doOnSuccess(p
-> {
274 logger
.trace("Got new profile for {}", recipientId
);
275 final var encryptedProfile
= p
.getProfile();
277 if (requestType
== SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
278 || account
.getProfileStore().getProfileKeyCredential(recipientId
) == null) {
279 logger
.trace("Storing profile credential");
280 final var profileKeyCredential
= p
.getProfileKeyCredential().orElse(null);
281 account
.getProfileStore().storeProfileKeyCredential(recipientId
, profileKeyCredential
);
284 final var profile
= account
.getProfileStore().getProfile(recipientId
);
286 Profile newProfile
= null;
287 if (profileKey
.isPresent()) {
288 logger
.trace("Decrypting profile");
289 newProfile
= decryptProfileAndDownloadAvatar(recipientId
, profileKey
.get(), encryptedProfile
);
292 if (newProfile
== null) {
294 profile
== null ? Profile
.newBuilder() : Profile
.newBuilder(profile
)
295 ).withLastUpdateTimestamp(System
.currentTimeMillis())
296 .withUnidentifiedAccessMode(ProfileUtils
.getUnidentifiedAccessMode(encryptedProfile
, null))
297 .withCapabilities(ProfileUtils
.getCapabilities(encryptedProfile
))
302 logger
.trace("Storing identity");
303 final var identityKey
= new IdentityKey(Base64
.getDecoder().decode(encryptedProfile
.getIdentityKey()));
304 account
.getIdentityKeyStore().saveIdentity(recipientId
, identityKey
, new Date());
305 } catch (InvalidKeyException ignored
) {
306 logger
.warn("Got invalid identity key in profile for {}",
307 context
.getRecipientHelper().resolveSignalServiceAddress(recipientId
).getIdentifier());
310 logger
.trace("Storing profile");
311 account
.getProfileStore().storeProfile(recipientId
, newProfile
);
313 logger
.trace("Done handling retrieved profile");
315 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
316 final var profile
= account
.getProfileStore().getProfile(recipientId
);
317 final var newProfile
= (
318 profile
== null ? Profile
.newBuilder() : Profile
.newBuilder(profile
)
319 ).withLastUpdateTimestamp(System
.currentTimeMillis())
320 .withUnidentifiedAccessMode(Profile
.UnidentifiedAccessMode
.UNKNOWN
)
321 .withCapabilities(Set
.of())
324 account
.getProfileStore().storeProfile(recipientId
, newProfile
);
328 private Single
<ProfileAndCredential
> retrieveProfile(
329 SignalServiceAddress address
,
330 Optional
<ProfileKey
> profileKey
,
331 Optional
<UnidentifiedAccess
> unidentifiedAccess
,
332 SignalServiceProfile
.RequestType requestType
334 final var profileService
= dependencies
.getProfileService();
335 final var locale
= Utils
.getDefaultLocale(Locale
.US
);
337 return profileService
.getProfile(address
, profileKey
, unidentifiedAccess
, requestType
, locale
).map(pair
-> {
338 var processor
= new ProfileService
.ProfileResponseProcessor(pair
);
339 if (processor
.hasResult()) {
340 return processor
.getResult();
341 } else if (processor
.notFound()) {
342 throw new NotFoundException("Profile not found");
344 throw pair
.getExecutionError()
345 .or(pair
::getApplicationError
)
346 .orElseThrow(() -> new IOException("Unknown error while retrieving profile"));
351 private void downloadProfileAvatar(
352 RecipientAddress address
, String avatarPath
, ProfileKey profileKey
354 if (avatarPath
== null) {
356 context
.getAvatarStore().deleteProfileAvatar(address
);
357 } catch (IOException e
) {
358 logger
.warn("Failed to delete local profile avatar, ignoring: {}", e
.getMessage());
364 context
.getAvatarStore()
365 .storeProfileAvatar(address
,
366 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
367 } catch (Throwable e
) {
368 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
372 private void retrieveProfileAvatar(
373 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
374 ) throws IOException
{
375 var tmpFile
= IOUtils
.createTempFile();
376 try (var input
= dependencies
.getMessageReceiver()
377 .retrieveProfileAvatar(avatarPath
,
380 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
381 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
382 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
385 Files
.delete(tmpFile
.toPath());
386 } catch (IOException e
) {
387 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
394 private Optional
<UnidentifiedAccess
> getUnidentifiedAccess(RecipientId recipientId
) {
395 var unidentifiedAccess
= context
.getUnidentifiedAccessHelper().getAccessFor(recipientId
, true);
397 if (unidentifiedAccess
.isPresent()) {
398 return unidentifiedAccess
.get().getTargetUnidentifiedAccess();
401 return Optional
.empty();