1 package org
.asamk
.signal
.manager
.helper
;
3 import org
.asamk
.signal
.manager
.AvatarStore
;
4 import org
.asamk
.signal
.manager
.SignalDependencies
;
5 import org
.asamk
.signal
.manager
.config
.ServiceConfig
;
6 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
7 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
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
.zkgroup
.profiles
.ProfileKey
;
13 import org
.signal
.zkgroup
.profiles
.ProfileKeyCredential
;
14 import org
.slf4j
.Logger
;
15 import org
.slf4j
.LoggerFactory
;
16 import org
.whispersystems
.libsignal
.IdentityKey
;
17 import org
.whispersystems
.libsignal
.InvalidKeyException
;
18 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
19 import org
.whispersystems
.signalservice
.api
.crypto
.UnidentifiedAccess
;
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
;
26 import org
.whispersystems
.signalservice
.internal
.ServiceResponse
;
29 import java
.io
.IOException
;
30 import java
.io
.OutputStream
;
31 import java
.nio
.file
.Files
;
32 import java
.util
.Base64
;
33 import java
.util
.Date
;
34 import java
.util
.HashSet
;
35 import java
.util
.List
;
36 import java
.util
.Objects
;
39 import io
.reactivex
.rxjava3
.core
.Single
;
41 public final class ProfileHelper
{
43 private final static Logger logger
= LoggerFactory
.getLogger(ProfileHelper
.class);
45 private final SignalAccount account
;
46 private final SignalDependencies dependencies
;
47 private final AvatarStore avatarStore
;
48 private final UnidentifiedAccessProvider unidentifiedAccessProvider
;
49 private final SignalServiceAddressResolver addressResolver
;
52 final SignalAccount account
,
53 final SignalDependencies dependencies
,
54 final AvatarStore avatarStore
,
55 final UnidentifiedAccessProvider unidentifiedAccessProvider
,
56 final SignalServiceAddressResolver addressResolver
58 this.account
= account
;
59 this.dependencies
= dependencies
;
60 this.avatarStore
= avatarStore
;
61 this.unidentifiedAccessProvider
= unidentifiedAccessProvider
;
62 this.addressResolver
= addressResolver
;
65 public Profile
getRecipientProfile(RecipientId recipientId
) {
66 return getRecipientProfile(recipientId
, false);
69 public void refreshRecipientProfile(RecipientId recipientId
) {
70 getRecipientProfile(recipientId
, true);
73 public ProfileKeyCredential
getRecipientProfileKeyCredential(RecipientId recipientId
) {
74 var profileKeyCredential
= account
.getProfileStore().getProfileKeyCredential(recipientId
);
75 if (profileKeyCredential
!= null) {
76 return profileKeyCredential
;
79 ProfileAndCredential profileAndCredential
;
81 profileAndCredential
= retrieveProfileAndCredential(recipientId
,
82 SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
);
83 } catch (IOException e
) {
84 logger
.warn("Failed to retrieve profile key credential, ignoring: {}", e
.getMessage());
88 profileKeyCredential
= profileAndCredential
.getProfileKeyCredential().orNull();
89 account
.getProfileStore().storeProfileKeyCredential(recipientId
, profileKeyCredential
);
91 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
92 if (profileKey
!= null) {
93 final var profile
= decryptProfileAndDownloadAvatar(recipientId
,
95 profileAndCredential
.getProfile());
96 account
.getProfileStore().storeProfile(recipientId
, profile
);
99 return profileKeyCredential
;
103 * @param givenName if null, the previous givenName will be kept
104 * @param familyName if null, the previous familyName will be kept
105 * @param about if null, the previous about text will be kept
106 * @param aboutEmoji if null, the previous about emoji will be kept
107 * @param avatar if avatar is null the image from the local avatar store is used (if present),
109 public void setProfile(
110 String givenName
, final String familyName
, String about
, String aboutEmoji
, Optional
<File
> avatar
111 ) throws IOException
{
112 setProfile(true, givenName
, familyName
, about
, aboutEmoji
, avatar
);
115 public void setProfile(
116 boolean uploadProfile
,
118 final String familyName
,
121 Optional
<File
> avatar
122 ) throws IOException
{
123 var profile
= getRecipientProfile(account
.getSelfRecipientId());
124 var builder
= profile
== null ? Profile
.newBuilder() : Profile
.newBuilder(profile
);
125 if (givenName
!= null) {
126 builder
.withGivenName(givenName
);
128 if (familyName
!= null) {
129 builder
.withFamilyName(familyName
);
132 builder
.withAbout(about
);
134 if (aboutEmoji
!= null) {
135 builder
.withAboutEmoji(aboutEmoji
);
137 var newProfile
= builder
.build();
140 try (final var streamDetails
= avatar
== null
141 ? avatarStore
.retrieveProfileAvatar(account
.getSelfAddress())
142 : avatar
.isPresent() ? Utils
.createStreamDetailsFromFile(avatar
.get()) : null) {
143 final var avatarPath
= dependencies
.getAccountManager()
144 .setVersionedProfile(account
.getUuid(),
145 account
.getProfileKey(),
146 newProfile
.getInternalServiceName(),
147 newProfile
.getAbout() == null ?
"" : newProfile
.getAbout(),
148 newProfile
.getAboutEmoji() == null ?
"" : newProfile
.getAboutEmoji(),
151 List
.of(/* TODO */));
152 builder
.withAvatarUrlPath(avatarPath
.orNull());
153 newProfile
= builder
.build();
157 if (avatar
!= null) {
158 if (avatar
.isPresent()) {
159 avatarStore
.storeProfileAvatar(account
.getSelfAddress(),
160 outputStream
-> IOUtils
.copyFileToStream(avatar
.get(), outputStream
));
162 avatarStore
.deleteProfileAvatar(account
.getSelfAddress());
165 account
.getProfileStore().storeProfile(account
.getSelfRecipientId(), newProfile
);
168 private final Set
<RecipientId
> pendingProfileRequest
= new HashSet
<>();
170 private Profile
getRecipientProfile(RecipientId recipientId
, boolean force
) {
171 var profile
= account
.getProfileStore().getProfile(recipientId
);
173 var now
= System
.currentTimeMillis();
174 // Profiles are cached for 24h before retrieving them again, unless forced
175 if (!force
&& profile
!= null && now
- profile
.getLastUpdateTimestamp() < 24 * 60 * 60 * 1000) {
179 synchronized (pendingProfileRequest
) {
180 if (pendingProfileRequest
.contains(recipientId
)) {
183 pendingProfileRequest
.add(recipientId
);
185 final SignalServiceProfile encryptedProfile
;
187 encryptedProfile
= retrieveEncryptedProfile(recipientId
);
189 synchronized (pendingProfileRequest
) {
190 pendingProfileRequest
.remove(recipientId
);
193 if (encryptedProfile
== null) {
197 profile
= decryptProfileIfKeyKnown(recipientId
, encryptedProfile
);
198 account
.getProfileStore().storeProfile(recipientId
, profile
);
203 private Profile
decryptProfileIfKeyKnown(
204 final RecipientId recipientId
, final SignalServiceProfile encryptedProfile
206 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
207 if (profileKey
== null) {
208 return new Profile(System
.currentTimeMillis(),
214 ProfileUtils
.getUnidentifiedAccessMode(encryptedProfile
, null),
215 ProfileUtils
.getCapabilities(encryptedProfile
));
218 return decryptProfileAndDownloadAvatar(recipientId
, profileKey
, encryptedProfile
);
221 private SignalServiceProfile
retrieveEncryptedProfile(RecipientId recipientId
) {
223 return retrieveProfileAndCredential(recipientId
, SignalServiceProfile
.RequestType
.PROFILE
).getProfile();
224 } catch (IOException e
) {
225 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
230 private SignalServiceProfile
retrieveProfileSync(String username
) throws IOException
{
231 return dependencies
.getMessageReceiver().retrieveProfileByUsername(username
, Optional
.absent());
234 private ProfileAndCredential
retrieveProfileAndCredential(
235 final RecipientId recipientId
, final SignalServiceProfile
.RequestType requestType
236 ) throws IOException
{
237 final var profileAndCredential
= retrieveProfileSync(recipientId
, requestType
);
238 final var profile
= profileAndCredential
.getProfile();
241 var newIdentity
= account
.getIdentityKeyStore()
242 .saveIdentity(recipientId
,
243 new IdentityKey(Base64
.getDecoder().decode(profile
.getIdentityKey())),
247 account
.getSessionStore().archiveSessions(recipientId
);
249 } catch (InvalidKeyException ignored
) {
250 logger
.warn("Got invalid identity key in profile for {}",
251 addressResolver
.resolveSignalServiceAddress(recipientId
).getIdentifier());
253 return profileAndCredential
;
256 private Profile
decryptProfileAndDownloadAvatar(
257 final RecipientId recipientId
, final ProfileKey profileKey
, final SignalServiceProfile encryptedProfile
259 final var avatarPath
= encryptedProfile
.getAvatar();
260 downloadProfileAvatar(recipientId
, avatarPath
, profileKey
);
262 return ProfileUtils
.decryptProfile(profileKey
, encryptedProfile
);
265 public void downloadProfileAvatar(
266 final RecipientId recipientId
, final String avatarPath
, final ProfileKey profileKey
268 var profile
= account
.getProfileStore().getProfile(recipientId
);
269 if (profile
== null || !Objects
.equals(avatarPath
, profile
.getAvatarUrlPath())) {
270 downloadProfileAvatar(addressResolver
.resolveSignalServiceAddress(recipientId
), avatarPath
, profileKey
);
271 var builder
= profile
== null ? Profile
.newBuilder() : Profile
.newBuilder(profile
);
272 account
.getProfileStore().storeProfile(recipientId
, builder
.withAvatarUrlPath(avatarPath
).build());
276 private ProfileAndCredential
retrieveProfileSync(
277 RecipientId recipientId
, SignalServiceProfile
.RequestType requestType
278 ) throws IOException
{
280 return retrieveProfile(recipientId
, requestType
).blockingGet();
281 } catch (RuntimeException e
) {
282 if (e
.getCause() instanceof PushNetworkException
) {
283 throw (PushNetworkException
) e
.getCause();
284 } else if (e
.getCause() instanceof NotFoundException
) {
285 throw (NotFoundException
) e
.getCause();
287 throw new IOException(e
);
292 private Single
<ProfileAndCredential
> retrieveProfile(
293 RecipientId recipientId
, SignalServiceProfile
.RequestType requestType
295 var unidentifiedAccess
= getUnidentifiedAccess(recipientId
);
296 var profileKey
= Optional
.fromNullable(account
.getProfileStore().getProfileKey(recipientId
));
298 final var address
= addressResolver
.resolveSignalServiceAddress(recipientId
);
299 return retrieveProfile(address
, profileKey
, unidentifiedAccess
, requestType
);
302 private Single
<ProfileAndCredential
> retrieveProfile(
303 SignalServiceAddress address
,
304 Optional
<ProfileKey
> profileKey
,
305 Optional
<UnidentifiedAccess
> unidentifiedAccess
,
306 SignalServiceProfile
.RequestType requestType
308 var profileService
= dependencies
.getProfileService();
310 Single
<ServiceResponse
<ProfileAndCredential
>> responseSingle
;
312 responseSingle
= profileService
.getProfile(address
, profileKey
, unidentifiedAccess
, requestType
);
313 } catch (NoClassDefFoundError e
) {
314 // Native zkgroup lib not available for ProfileKey
315 responseSingle
= profileService
.getProfile(address
, Optional
.absent(), unidentifiedAccess
, requestType
);
318 return responseSingle
.map(pair
-> {
319 var processor
= new ProfileService
.ProfileResponseProcessor(pair
);
320 if (processor
.hasResult()) {
321 return processor
.getResult();
322 } else if (processor
.notFound()) {
323 throw new NotFoundException("Profile not found");
325 throw pair
.getExecutionError()
326 .or(pair
.getApplicationError())
327 .or(new IOException("Unknown error while retrieving profile"));
332 private void downloadProfileAvatar(
333 SignalServiceAddress address
, String avatarPath
, ProfileKey profileKey
335 if (avatarPath
== null) {
337 avatarStore
.deleteProfileAvatar(address
);
338 } catch (IOException e
) {
339 logger
.warn("Failed to delete local profile avatar, ignoring: {}", e
.getMessage());
345 avatarStore
.storeProfileAvatar(address
,
346 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
347 } catch (Throwable e
) {
348 if (e
instanceof AssertionError
&& e
.getCause() instanceof InterruptedException
) {
349 Thread
.currentThread().interrupt();
351 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
355 private void retrieveProfileAvatar(
356 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
357 ) throws IOException
{
358 var tmpFile
= IOUtils
.createTempFile();
359 try (var input
= dependencies
.getMessageReceiver()
360 .retrieveProfileAvatar(avatarPath
,
363 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
364 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
365 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
368 Files
.delete(tmpFile
.toPath());
369 } catch (IOException e
) {
370 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
377 private Optional
<UnidentifiedAccess
> getUnidentifiedAccess(RecipientId recipientId
) {
378 var unidentifiedAccess
= unidentifiedAccessProvider
.getAccessFor(recipientId
);
380 if (unidentifiedAccess
.isPresent()) {
381 return unidentifiedAccess
.get().getTargetUnidentifiedAccess();
384 return Optional
.absent();