]> nmode's Git Repositories - signal-cli/blob - lib/src/main/java/org/asamk/signal/manager/helper/ProfileHelper.java
Store payment address of profiles
[signal-cli] / lib / src / main / java / org / asamk / signal / manager / helper / ProfileHelper.java
1 package org.asamk.signal.manager.helper;
2
3 import com.google.protobuf.InvalidProtocolBufferException;
4
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;
29
30 import java.io.File;
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;
40 import java.util.Set;
41
42 import io.reactivex.rxjava3.core.Flowable;
43 import io.reactivex.rxjava3.core.Maybe;
44 import io.reactivex.rxjava3.core.Single;
45
46 public final class ProfileHelper {
47
48 private final static Logger logger = LoggerFactory.getLogger(ProfileHelper.class);
49
50 private final SignalAccount account;
51 private final SignalDependencies dependencies;
52 private final Context context;
53
54 public ProfileHelper(final Context context) {
55 this.account = context.getAccount();
56 this.dependencies = context.getDependencies();
57 this.context = context;
58 }
59
60 public Profile getRecipientProfile(RecipientId recipientId) {
61 return getRecipientProfile(recipientId, false);
62 }
63
64 public void refreshRecipientProfile(RecipientId recipientId) {
65 getRecipientProfile(recipientId, true);
66 }
67
68 public List<ProfileKeyCredential> getRecipientProfileKeyCredential(List<RecipientId> recipientIds) {
69 try {
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();
76 } finally {
77 account.getRecipientStore().setBulkUpdating(false);
78 }
79
80 return recipientIds.stream().map(r -> account.getProfileStore().getProfileKeyCredential(r)).toList();
81 }
82
83 public ProfileKeyCredential getRecipientProfileKeyCredential(RecipientId recipientId) {
84 var profileKeyCredential = account.getProfileStore().getProfileKeyCredential(recipientId);
85 if (profileKeyCredential != null) {
86 return profileKeyCredential;
87 }
88
89 try {
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());
93 return null;
94 }
95
96 return account.getProfileStore().getProfileKeyCredential(recipientId);
97 }
98
99 /**
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),
105 */
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);
110 }
111
112 public void setProfile(
113 boolean uploadProfile,
114 String givenName,
115 final String familyName,
116 String about,
117 String aboutEmoji,
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);
124 }
125 if (familyName != null) {
126 builder.withFamilyName(familyName);
127 }
128 if (about != null) {
129 builder.withAbout(about);
130 }
131 if (aboutEmoji != null) {
132 builder.withAboutEmoji(aboutEmoji);
133 }
134 var newProfile = builder.build();
135
136 if (uploadProfile) {
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)
141 : avatar.isPresent()
142 ? AvatarUploadParams.forAvatar(streamDetails)
143 : AvatarUploadParams.unchanged(false);
144 final var paymentsAddress = Optional.ofNullable(newProfile.getPaymentAddress()).map(data -> {
145 try {
146 return SignalServiceProtos.PaymentAddress.parseFrom(data);
147 } catch (InvalidProtocolBufferException e) {
148 return null;
149 }
150 });
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(),
157 paymentsAddress,
158 avatarUploadParams,
159 List.of(/* TODO */));
160 builder.withAvatarUrlPath(avatarPath.orElse(null));
161 newProfile = builder.build();
162 }
163 }
164
165 if (avatar != null) {
166 if (avatar.isPresent()) {
167 context.getAvatarStore()
168 .storeProfileAvatar(account.getSelfRecipientAddress(),
169 outputStream -> IOUtils.copyFileToStream(avatar.get(), outputStream));
170 } else {
171 context.getAvatarStore().deleteProfileAvatar(account.getSelfRecipientAddress());
172 }
173 }
174 account.getProfileStore().storeProfile(account.getSelfRecipientId(), newProfile);
175 }
176
177 public Profile getSelfProfile() {
178 return getRecipientProfile(account.getSelfRecipientId());
179 }
180
181 public List<Profile> getRecipientProfile(List<RecipientId> recipientIds) {
182 try {
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();
189 } finally {
190 account.getRecipientStore().setBulkUpdating(false);
191 }
192
193 return recipientIds.stream().map(r -> account.getProfileStore().getProfile(r)).toList();
194 }
195
196 private Profile getRecipientProfile(RecipientId recipientId, boolean force) {
197 var profile = account.getProfileStore().getProfile(recipientId);
198
199 if (!force && !isProfileRefreshRequired(profile)) {
200 return profile;
201 }
202
203 try {
204 blockingGetProfile(retrieveProfile(recipientId, SignalServiceProfile.RequestType.PROFILE));
205 } catch (IOException e) {
206 logger.warn("Failed to retrieve profile, ignoring: {}", e.getMessage());
207 }
208
209 return account.getProfileStore().getProfile(recipientId);
210 }
211
212 private boolean isProfileRefreshRequired(final Profile profile) {
213 if (profile == null) {
214 return true;
215 }
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;
219 }
220
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);
224 }
225
226 private Profile decryptProfileAndDownloadAvatar(
227 final RecipientId recipientId, final ProfileKey profileKey, final SignalServiceProfile encryptedProfile
228 ) {
229 final var avatarPath = encryptedProfile.getAvatar();
230 downloadProfileAvatar(recipientId, avatarPath, profileKey);
231
232 return ProfileUtils.decryptProfile(profileKey, encryptedProfile);
233 }
234
235 public void downloadProfileAvatar(
236 final RecipientId recipientId, final String avatarPath, final ProfileKey profileKey
237 ) {
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),
242 avatarPath,
243 profileKey);
244 var builder = profile == null ? Profile.newBuilder() : Profile.newBuilder(profile);
245 account.getProfileStore().storeProfile(recipientId, builder.withAvatarUrlPath(avatarPath).build());
246 }
247 }
248
249 private ProfileAndCredential blockingGetProfile(Single<ProfileAndCredential> profile) throws IOException {
250 try {
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();
257 } else {
258 throw new IOException(e);
259 }
260 }
261 }
262
263 private Single<ProfileAndCredential> retrieveProfile(
264 RecipientId recipientId, SignalServiceProfile.RequestType requestType
265 ) {
266 var unidentifiedAccess = getUnidentifiedAccess(recipientId);
267 var profileKey = Optional.ofNullable(account.getProfileStore().getProfileKey(recipientId));
268
269 logger.trace("Retrieving profile for {} {}",
270 recipientId,
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();
276
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);
282 }
283
284 final var profile = account.getProfileStore().getProfile(recipientId);
285
286 Profile newProfile = null;
287 if (profileKey.isPresent()) {
288 logger.trace("Decrypting profile");
289 newProfile = decryptProfileAndDownloadAvatar(recipientId, profileKey.get(), encryptedProfile);
290 }
291
292 if (newProfile == null) {
293 newProfile = (
294 profile == null ? Profile.newBuilder() : Profile.newBuilder(profile)
295 ).withLastUpdateTimestamp(System.currentTimeMillis())
296 .withUnidentifiedAccessMode(ProfileUtils.getUnidentifiedAccessMode(encryptedProfile, null))
297 .withCapabilities(ProfileUtils.getCapabilities(encryptedProfile))
298 .build();
299 }
300
301 try {
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());
308 }
309
310 logger.trace("Storing profile");
311 account.getProfileStore().storeProfile(recipientId, newProfile);
312
313 logger.trace("Done handling retrieved profile");
314 }).doOnError(e -> {
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())
322 .build();
323
324 account.getProfileStore().storeProfile(recipientId, newProfile);
325 });
326 }
327
328 private Single<ProfileAndCredential> retrieveProfile(
329 SignalServiceAddress address,
330 Optional<ProfileKey> profileKey,
331 Optional<UnidentifiedAccess> unidentifiedAccess,
332 SignalServiceProfile.RequestType requestType
333 ) {
334 final var profileService = dependencies.getProfileService();
335 final var locale = Utils.getDefaultLocale(Locale.US);
336
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");
343 } else {
344 throw pair.getExecutionError()
345 .or(pair::getApplicationError)
346 .orElseThrow(() -> new IOException("Unknown error while retrieving profile"));
347 }
348 });
349 }
350
351 private void downloadProfileAvatar(
352 RecipientAddress address, String avatarPath, ProfileKey profileKey
353 ) {
354 if (avatarPath == null) {
355 try {
356 context.getAvatarStore().deleteProfileAvatar(address);
357 } catch (IOException e) {
358 logger.warn("Failed to delete local profile avatar, ignoring: {}", e.getMessage());
359 }
360 return;
361 }
362
363 try {
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());
369 }
370 }
371
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,
378 tmpFile,
379 profileKey,
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);
383 } finally {
384 try {
385 Files.delete(tmpFile.toPath());
386 } catch (IOException e) {
387 logger.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
388 tmpFile,
389 e.getMessage());
390 }
391 }
392 }
393
394 private Optional<UnidentifiedAccess> getUnidentifiedAccess(RecipientId recipientId) {
395 var unidentifiedAccess = context.getUnidentifiedAccessHelper().getAccessFor(recipientId, true);
396
397 if (unidentifiedAccess.isPresent()) {
398 return unidentifiedAccess.get().getTargetUnidentifiedAccess();
399 }
400
401 return Optional.empty();
402 }
403 }