]> nmode's Git Repositories - signal-cli/blob - lib/src/main/java/org/asamk/signal/manager/helper/ProfileHelper.java
Update libsignal-service-java
[signal-cli] / lib / src / main / java / org / asamk / signal / manager / helper / ProfileHelper.java
1 package org.asamk.signal.manager.helper;
2
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;
26
27 import java.io.File;
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;
37 import java.util.Set;
38
39 import io.reactivex.rxjava3.core.Flowable;
40 import io.reactivex.rxjava3.core.Maybe;
41 import io.reactivex.rxjava3.core.Single;
42
43 public final class ProfileHelper {
44
45 private final static Logger logger = LoggerFactory.getLogger(ProfileHelper.class);
46
47 private final SignalAccount account;
48 private final SignalDependencies dependencies;
49 private final Context context;
50
51 public ProfileHelper(final Context context) {
52 this.account = context.getAccount();
53 this.dependencies = context.getDependencies();
54 this.context = context;
55 }
56
57 public Profile getRecipientProfile(RecipientId recipientId) {
58 return getRecipientProfile(recipientId, false);
59 }
60
61 public void refreshRecipientProfile(RecipientId recipientId) {
62 getRecipientProfile(recipientId, true);
63 }
64
65 public List<ProfileKeyCredential> getRecipientProfileKeyCredential(List<RecipientId> recipientIds) {
66 try {
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();
73 } finally {
74 account.getRecipientStore().setBulkUpdating(false);
75 }
76
77 return recipientIds.stream().map(r -> account.getProfileStore().getProfileKeyCredential(r)).toList();
78 }
79
80 public ProfileKeyCredential getRecipientProfileKeyCredential(RecipientId recipientId) {
81 var profileKeyCredential = account.getProfileStore().getProfileKeyCredential(recipientId);
82 if (profileKeyCredential != null) {
83 return profileKeyCredential;
84 }
85
86 try {
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());
90 return null;
91 }
92
93 return account.getProfileStore().getProfileKeyCredential(recipientId);
94 }
95
96 /**
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),
102 */
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);
107 }
108
109 public void setProfile(
110 boolean uploadProfile,
111 String givenName,
112 final String familyName,
113 String about,
114 String aboutEmoji,
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);
121 }
122 if (familyName != null) {
123 builder.withFamilyName(familyName);
124 }
125 if (about != null) {
126 builder.withAbout(about);
127 }
128 if (aboutEmoji != null) {
129 builder.withAboutEmoji(aboutEmoji);
130 }
131 var newProfile = builder.build();
132
133 if (uploadProfile) {
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)
138 : avatar.isPresent()
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(),
147 Optional.empty(),
148 avatarUploadParams,
149 List.of(/* TODO */));
150 builder.withAvatarUrlPath(avatarPath.orElse(null));
151 newProfile = builder.build();
152 }
153 }
154
155 if (avatar != null) {
156 if (avatar.isPresent()) {
157 context.getAvatarStore()
158 .storeProfileAvatar(account.getSelfRecipientAddress(),
159 outputStream -> IOUtils.copyFileToStream(avatar.get(), outputStream));
160 } else {
161 context.getAvatarStore().deleteProfileAvatar(account.getSelfRecipientAddress());
162 }
163 }
164 account.getProfileStore().storeProfile(account.getSelfRecipientId(), newProfile);
165 }
166
167 public List<Profile> getRecipientProfile(List<RecipientId> recipientIds) {
168 try {
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();
175 } finally {
176 account.getRecipientStore().setBulkUpdating(false);
177 }
178
179 return recipientIds.stream().map(r -> account.getProfileStore().getProfile(r)).toList();
180 }
181
182 private Profile getRecipientProfile(RecipientId recipientId, boolean force) {
183 var profile = account.getProfileStore().getProfile(recipientId);
184
185 if (!force && !isProfileRefreshRequired(profile)) {
186 return profile;
187 }
188
189 try {
190 blockingGetProfile(retrieveProfile(recipientId, SignalServiceProfile.RequestType.PROFILE));
191 } catch (IOException e) {
192 logger.warn("Failed to retrieve profile, ignoring: {}", e.getMessage());
193 }
194
195 return account.getProfileStore().getProfile(recipientId);
196 }
197
198 private boolean isProfileRefreshRequired(final Profile profile) {
199 if (profile == null) {
200 return true;
201 }
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;
205 }
206
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);
210 }
211
212 private Profile decryptProfileAndDownloadAvatar(
213 final RecipientId recipientId, final ProfileKey profileKey, final SignalServiceProfile encryptedProfile
214 ) {
215 final var avatarPath = encryptedProfile.getAvatar();
216 downloadProfileAvatar(recipientId, avatarPath, profileKey);
217
218 return ProfileUtils.decryptProfile(profileKey, encryptedProfile);
219 }
220
221 public void downloadProfileAvatar(
222 final RecipientId recipientId, final String avatarPath, final ProfileKey profileKey
223 ) {
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),
228 avatarPath,
229 profileKey);
230 var builder = profile == null ? Profile.newBuilder() : Profile.newBuilder(profile);
231 account.getProfileStore().storeProfile(recipientId, builder.withAvatarUrlPath(avatarPath).build());
232 }
233 }
234
235 private ProfileAndCredential blockingGetProfile(Single<ProfileAndCredential> profile) throws IOException {
236 try {
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();
243 } else {
244 throw new IOException(e);
245 }
246 }
247 }
248
249 private Single<ProfileAndCredential> retrieveProfile(
250 RecipientId recipientId, SignalServiceProfile.RequestType requestType
251 ) {
252 var unidentifiedAccess = getUnidentifiedAccess(recipientId);
253 var profileKey = Optional.ofNullable(account.getProfileStore().getProfileKey(recipientId));
254
255 logger.trace("Retrieving profile for {} {}",
256 recipientId,
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();
262
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);
268 }
269
270 final var profile = account.getProfileStore().getProfile(recipientId);
271
272 Profile newProfile = null;
273 if (profileKey.isPresent()) {
274 logger.trace("Decrypting profile");
275 newProfile = decryptProfileAndDownloadAvatar(recipientId, profileKey.get(), encryptedProfile);
276 }
277
278 if (newProfile == null) {
279 newProfile = (
280 profile == null ? Profile.newBuilder() : Profile.newBuilder(profile)
281 ).withLastUpdateTimestamp(System.currentTimeMillis())
282 .withUnidentifiedAccessMode(ProfileUtils.getUnidentifiedAccessMode(encryptedProfile, null))
283 .withCapabilities(ProfileUtils.getCapabilities(encryptedProfile))
284 .build();
285 }
286
287 try {
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());
294 }
295
296 logger.trace("Storing profile");
297 account.getProfileStore().storeProfile(recipientId, newProfile);
298
299 logger.trace("Done handling retrieved profile");
300 }).doOnError(e -> {
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())
308 .build();
309
310 account.getProfileStore().storeProfile(recipientId, newProfile);
311 });
312 }
313
314 private Single<ProfileAndCredential> retrieveProfile(
315 SignalServiceAddress address,
316 Optional<ProfileKey> profileKey,
317 Optional<UnidentifiedAccess> unidentifiedAccess,
318 SignalServiceProfile.RequestType requestType
319 ) {
320 final var profileService = dependencies.getProfileService();
321 final var locale = Utils.getDefaultLocale(Locale.US);
322
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");
329 } else {
330 throw pair.getExecutionError()
331 .or(pair::getApplicationError)
332 .orElseThrow(() -> new IOException("Unknown error while retrieving profile"));
333 }
334 });
335 }
336
337 private void downloadProfileAvatar(
338 RecipientAddress address, String avatarPath, ProfileKey profileKey
339 ) {
340 if (avatarPath == null) {
341 try {
342 context.getAvatarStore().deleteProfileAvatar(address);
343 } catch (IOException e) {
344 logger.warn("Failed to delete local profile avatar, ignoring: {}", e.getMessage());
345 }
346 return;
347 }
348
349 try {
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());
355 }
356 }
357
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,
364 tmpFile,
365 profileKey,
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);
369 } finally {
370 try {
371 Files.delete(tmpFile.toPath());
372 } catch (IOException e) {
373 logger.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
374 tmpFile,
375 e.getMessage());
376 }
377 }
378 }
379
380 private Optional<UnidentifiedAccess> getUnidentifiedAccess(RecipientId recipientId) {
381 var unidentifiedAccess = context.getUnidentifiedAccessHelper().getAccessFor(recipientId, true);
382
383 if (unidentifiedAccess.isPresent()) {
384 return unidentifiedAccess.get().getTargetUnidentifiedAccess();
385 }
386
387 return Optional.empty();
388 }
389 }