]> nmode's Git Repositories - signal-cli/blob - lib/src/main/java/org/asamk/signal/manager/helper/ProfileHelper.java
Add mobile-coin-address to updateProfile command
[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.groups.GroupNotFoundException;
6 import org.asamk.signal.manager.groups.NotAGroupMemberException;
7 import org.asamk.signal.manager.storage.SignalAccount;
8 import org.asamk.signal.manager.storage.groups.GroupInfoV2;
9 import org.asamk.signal.manager.storage.recipients.Profile;
10 import org.asamk.signal.manager.storage.recipients.RecipientAddress;
11 import org.asamk.signal.manager.storage.recipients.RecipientId;
12 import org.asamk.signal.manager.util.IOUtils;
13 import org.asamk.signal.manager.util.KeyUtils;
14 import org.asamk.signal.manager.util.PaymentUtils;
15 import org.asamk.signal.manager.util.ProfileUtils;
16 import org.asamk.signal.manager.util.Utils;
17 import org.signal.libsignal.protocol.IdentityKey;
18 import org.signal.libsignal.protocol.InvalidKeyException;
19 import org.signal.libsignal.zkgroup.profiles.ProfileKey;
20 import org.signal.libsignal.zkgroup.profiles.ProfileKeyCredential;
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
23 import org.whispersystems.signalservice.api.crypto.UnidentifiedAccess;
24 import org.whispersystems.signalservice.api.profiles.AvatarUploadParams;
25 import org.whispersystems.signalservice.api.profiles.ProfileAndCredential;
26 import org.whispersystems.signalservice.api.profiles.SignalServiceProfile;
27 import org.whispersystems.signalservice.api.push.SignalServiceAddress;
28 import org.whispersystems.signalservice.api.push.exceptions.NotFoundException;
29 import org.whispersystems.signalservice.api.push.exceptions.PushNetworkException;
30 import org.whispersystems.signalservice.api.services.ProfileService;
31
32 import java.io.File;
33 import java.io.IOException;
34 import java.io.OutputStream;
35 import java.nio.file.Files;
36 import java.util.Base64;
37 import java.util.Collection;
38 import java.util.Date;
39 import java.util.List;
40 import java.util.Locale;
41 import java.util.Objects;
42 import java.util.Optional;
43 import java.util.Set;
44
45 import io.reactivex.rxjava3.core.Flowable;
46 import io.reactivex.rxjava3.core.Maybe;
47 import io.reactivex.rxjava3.core.Single;
48
49 public final class ProfileHelper {
50
51 private final static Logger logger = LoggerFactory.getLogger(ProfileHelper.class);
52
53 private final SignalAccount account;
54 private final SignalDependencies dependencies;
55 private final Context context;
56
57 public ProfileHelper(final Context context) {
58 this.account = context.getAccount();
59 this.dependencies = context.getDependencies();
60 this.context = context;
61 }
62
63 public void rotateProfileKey() throws IOException {
64 var profileKey = KeyUtils.createProfileKey();
65 account.setProfileKey(profileKey);
66 context.getAccountHelper().updateAccountAttributes();
67 setProfile(true, true, null, null, null, null, null, null);
68 // TODO update profile key in storage
69
70 final var recipientIds = account.getRecipientStore().getRecipientIdsWithEnabledProfileSharing();
71 for (final var recipientId : recipientIds) {
72 context.getSendHelper().sendProfileKey(recipientId);
73 }
74
75 final var selfRecipientId = account.getSelfRecipientId();
76 final var activeGroupIds = account.getGroupStore()
77 .getGroups()
78 .stream()
79 .filter(g -> g instanceof GroupInfoV2 && g.isMember(selfRecipientId))
80 .map(g -> (GroupInfoV2) g)
81 .map(GroupInfoV2::getGroupId)
82 .toList();
83 for (final var groupId : activeGroupIds) {
84 try {
85 context.getGroupHelper().updateGroupProfileKey(groupId);
86 } catch (GroupNotFoundException | NotAGroupMemberException | IOException e) {
87 logger.warn("Failed to update group profile key: {}", e.getMessage());
88 }
89 }
90 }
91
92 public Profile getRecipientProfile(RecipientId recipientId) {
93 return getRecipientProfile(recipientId, false);
94 }
95
96 public List<Profile> getRecipientProfiles(Collection<RecipientId> recipientIds) {
97 return getRecipientProfiles(recipientIds, false);
98 }
99
100 public void refreshRecipientProfile(RecipientId recipientId) {
101 getRecipientProfile(recipientId, true);
102 }
103
104 public void refreshRecipientProfiles(Collection<RecipientId> recipientIds) {
105 getRecipientProfiles(recipientIds, true);
106 }
107
108 public List<ProfileKeyCredential> getRecipientProfileKeyCredential(List<RecipientId> recipientIds) {
109 try {
110 account.getRecipientStore().setBulkUpdating(true);
111 final var profileFetches = Flowable.fromIterable(recipientIds)
112 .filter(recipientId -> account.getProfileStore().getProfileKeyCredential(recipientId) == null)
113 .map(recipientId -> retrieveProfile(recipientId,
114 SignalServiceProfile.RequestType.PROFILE_AND_CREDENTIAL).onErrorComplete());
115 Maybe.merge(profileFetches, 10).blockingSubscribe();
116 } finally {
117 account.getRecipientStore().setBulkUpdating(false);
118 }
119
120 return recipientIds.stream().map(r -> account.getProfileStore().getProfileKeyCredential(r)).toList();
121 }
122
123 public ProfileKeyCredential getRecipientProfileKeyCredential(RecipientId recipientId) {
124 var profileKeyCredential = account.getProfileStore().getProfileKeyCredential(recipientId);
125 if (profileKeyCredential != null) {
126 return profileKeyCredential;
127 }
128
129 try {
130 blockingGetProfile(retrieveProfile(recipientId, SignalServiceProfile.RequestType.PROFILE_AND_CREDENTIAL));
131 } catch (IOException e) {
132 logger.warn("Failed to retrieve profile key credential, ignoring: {}", e.getMessage());
133 return null;
134 }
135
136 return account.getProfileStore().getProfileKeyCredential(recipientId);
137 }
138
139 /**
140 * @param givenName if null, the previous givenName will be kept
141 * @param familyName if null, the previous familyName will be kept
142 * @param about if null, the previous about text will be kept
143 * @param aboutEmoji if null, the previous about emoji will be kept
144 * @param avatar if avatar is null the image from the local avatar store is used (if present),
145 */
146 public void setProfile(
147 String givenName,
148 final String familyName,
149 String about,
150 String aboutEmoji,
151 Optional<File> avatar,
152 byte[] mobileCoinAddress
153 ) throws IOException {
154 setProfile(true, false, givenName, familyName, about, aboutEmoji, avatar, mobileCoinAddress);
155 }
156
157 public void setProfile(
158 boolean uploadProfile,
159 boolean forceUploadAvatar,
160 String givenName,
161 final String familyName,
162 String about,
163 String aboutEmoji,
164 Optional<File> avatar,
165 byte[] mobileCoinAddress
166 ) throws IOException {
167 var profile = getSelfProfile();
168 var builder = profile == null ? Profile.newBuilder() : Profile.newBuilder(profile);
169 if (givenName != null) {
170 builder.withGivenName(givenName);
171 }
172 if (familyName != null) {
173 builder.withFamilyName(familyName);
174 }
175 if (about != null) {
176 builder.withAbout(about);
177 }
178 if (aboutEmoji != null) {
179 builder.withAboutEmoji(aboutEmoji);
180 }
181 if (mobileCoinAddress != null) {
182 builder.withMobileCoinAddress(mobileCoinAddress);
183 }
184 var newProfile = builder.build();
185
186 if (uploadProfile) {
187 final var streamDetails = avatar != null && avatar.isPresent()
188 ? Utils.createStreamDetailsFromFile(avatar.get())
189 : forceUploadAvatar && avatar == null ? context.getAvatarStore()
190 .retrieveProfileAvatar(account.getSelfRecipientAddress()) : null;
191 try (streamDetails) {
192 final var avatarUploadParams = streamDetails != null
193 ? AvatarUploadParams.forAvatar(streamDetails)
194 : avatar == null ? AvatarUploadParams.unchanged(true) : AvatarUploadParams.unchanged(false);
195 final var paymentsAddress = Optional.ofNullable(newProfile.getMobileCoinAddress())
196 .map(address -> PaymentUtils.signPaymentsAddress(address,
197 account.getAciIdentityKeyPair().getPrivateKey()));
198 logger.debug("Uploading new profile");
199 final var avatarPath = dependencies.getAccountManager()
200 .setVersionedProfile(account.getAci(),
201 account.getProfileKey(),
202 newProfile.getInternalServiceName(),
203 newProfile.getAbout() == null ? "" : newProfile.getAbout(),
204 newProfile.getAboutEmoji() == null ? "" : newProfile.getAboutEmoji(),
205 paymentsAddress,
206 avatarUploadParams,
207 List.of(/* TODO implement support for badges */));
208 if (!avatarUploadParams.keepTheSame) {
209 builder.withAvatarUrlPath(avatarPath.orElse(null));
210 }
211 newProfile = builder.build();
212 }
213 }
214
215 if (avatar != null) {
216 if (avatar.isPresent()) {
217 context.getAvatarStore()
218 .storeProfileAvatar(account.getSelfRecipientAddress(),
219 outputStream -> IOUtils.copyFileToStream(avatar.get(), outputStream));
220 } else {
221 context.getAvatarStore().deleteProfileAvatar(account.getSelfRecipientAddress());
222 }
223 }
224 account.getProfileStore().storeProfile(account.getSelfRecipientId(), newProfile);
225 }
226
227 public Profile getSelfProfile() {
228 return getRecipientProfile(account.getSelfRecipientId());
229 }
230
231 private List<Profile> getRecipientProfiles(Collection<RecipientId> recipientIds, boolean force) {
232 final var profileStore = account.getProfileStore();
233 try {
234 account.getRecipientStore().setBulkUpdating(true);
235 final var profileFetches = Flowable.fromIterable(recipientIds)
236 .filter(recipientId -> force || isProfileRefreshRequired(profileStore.getProfile(recipientId)))
237 .map(recipientId -> retrieveProfile(recipientId,
238 SignalServiceProfile.RequestType.PROFILE).onErrorComplete());
239 Maybe.merge(profileFetches, 10).blockingSubscribe();
240 } finally {
241 account.getRecipientStore().setBulkUpdating(false);
242 }
243
244 return recipientIds.stream().map(profileStore::getProfile).toList();
245 }
246
247 private Profile getRecipientProfile(RecipientId recipientId, boolean force) {
248 var profile = account.getProfileStore().getProfile(recipientId);
249
250 if (!force && !isProfileRefreshRequired(profile)) {
251 return profile;
252 }
253
254 try {
255 blockingGetProfile(retrieveProfile(recipientId, SignalServiceProfile.RequestType.PROFILE));
256 } catch (IOException e) {
257 logger.warn("Failed to retrieve profile, ignoring: {}", e.getMessage());
258 }
259
260 return account.getProfileStore().getProfile(recipientId);
261 }
262
263 private boolean isProfileRefreshRequired(final Profile profile) {
264 if (profile == null) {
265 return true;
266 }
267 // Profiles are cached for 6h before retrieving them again, unless forced
268 final var now = System.currentTimeMillis();
269 return now - profile.getLastUpdateTimestamp() >= 6 * 60 * 60 * 1000;
270 }
271
272 private SignalServiceProfile retrieveProfileSync(String username) throws IOException {
273 final var locale = Utils.getDefaultLocale(Locale.US);
274 return dependencies.getMessageReceiver().retrieveProfileByUsername(username, Optional.empty(), locale);
275 }
276
277 private Profile decryptProfileAndDownloadAvatar(
278 final RecipientId recipientId, final ProfileKey profileKey, final SignalServiceProfile encryptedProfile
279 ) {
280 final var avatarPath = encryptedProfile.getAvatar();
281 downloadProfileAvatar(recipientId, avatarPath, profileKey);
282
283 return ProfileUtils.decryptProfile(profileKey, encryptedProfile);
284 }
285
286 public void downloadProfileAvatar(
287 final RecipientId recipientId, final String avatarPath, final ProfileKey profileKey
288 ) {
289 var profile = account.getProfileStore().getProfile(recipientId);
290 if (profile == null || !Objects.equals(avatarPath, profile.getAvatarUrlPath())) {
291 logger.trace("Downloading profile avatar for {}", recipientId);
292 downloadProfileAvatar(account.getRecipientStore().resolveRecipientAddress(recipientId),
293 avatarPath,
294 profileKey);
295 var builder = profile == null ? Profile.newBuilder() : Profile.newBuilder(profile);
296 account.getProfileStore().storeProfile(recipientId, builder.withAvatarUrlPath(avatarPath).build());
297 }
298 }
299
300 private ProfileAndCredential blockingGetProfile(Single<ProfileAndCredential> profile) throws IOException {
301 try {
302 return profile.blockingGet();
303 } catch (RuntimeException e) {
304 if (e.getCause() instanceof PushNetworkException) {
305 throw (PushNetworkException) e.getCause();
306 } else if (e.getCause() instanceof NotFoundException) {
307 throw (NotFoundException) e.getCause();
308 } else {
309 throw new IOException(e);
310 }
311 }
312 }
313
314 private Single<ProfileAndCredential> retrieveProfile(
315 RecipientId recipientId, SignalServiceProfile.RequestType requestType
316 ) {
317 var unidentifiedAccess = getUnidentifiedAccess(recipientId);
318 var profileKey = Optional.ofNullable(account.getProfileStore().getProfileKey(recipientId));
319
320 logger.trace("Retrieving profile for {} {}",
321 recipientId,
322 profileKey.isPresent() ? "with profile key" : "without profile key");
323 final var address = context.getRecipientHelper().resolveSignalServiceAddress(recipientId);
324 return retrieveProfile(address, profileKey, unidentifiedAccess, requestType).doOnSuccess(p -> {
325 logger.trace("Got new profile for {}", recipientId);
326 final var encryptedProfile = p.getProfile();
327
328 if (requestType == SignalServiceProfile.RequestType.PROFILE_AND_CREDENTIAL
329 || account.getProfileStore().getProfileKeyCredential(recipientId) == null) {
330 logger.trace("Storing profile credential");
331 final var profileKeyCredential = p.getProfileKeyCredential().orElse(null);
332 account.getProfileStore().storeProfileKeyCredential(recipientId, profileKeyCredential);
333 }
334
335 final var profile = account.getProfileStore().getProfile(recipientId);
336
337 Profile newProfile = null;
338 if (profileKey.isPresent()) {
339 logger.trace("Decrypting profile");
340 newProfile = decryptProfileAndDownloadAvatar(recipientId, profileKey.get(), encryptedProfile);
341 }
342
343 if (newProfile == null) {
344 newProfile = (
345 profile == null ? Profile.newBuilder() : Profile.newBuilder(profile)
346 ).withLastUpdateTimestamp(System.currentTimeMillis())
347 .withUnidentifiedAccessMode(ProfileUtils.getUnidentifiedAccessMode(encryptedProfile, null))
348 .withCapabilities(ProfileUtils.getCapabilities(encryptedProfile))
349 .build();
350 }
351
352 try {
353 logger.trace("Storing identity");
354 final var identityKey = new IdentityKey(Base64.getDecoder().decode(encryptedProfile.getIdentityKey()));
355 account.getIdentityKeyStore().saveIdentity(recipientId, identityKey, new Date());
356 } catch (InvalidKeyException ignored) {
357 logger.warn("Got invalid identity key in profile for {}",
358 context.getRecipientHelper().resolveSignalServiceAddress(recipientId).getIdentifier());
359 }
360
361 logger.trace("Storing profile");
362 account.getProfileStore().storeProfile(recipientId, newProfile);
363
364 logger.trace("Done handling retrieved profile");
365 }).doOnError(e -> {
366 logger.warn("Failed to retrieve profile, ignoring: {}", e.getMessage());
367 final var profile = account.getProfileStore().getProfile(recipientId);
368 final var newProfile = (
369 profile == null ? Profile.newBuilder() : Profile.newBuilder(profile)
370 ).withLastUpdateTimestamp(System.currentTimeMillis())
371 .withUnidentifiedAccessMode(Profile.UnidentifiedAccessMode.UNKNOWN)
372 .withCapabilities(Set.of())
373 .build();
374
375 account.getProfileStore().storeProfile(recipientId, newProfile);
376 });
377 }
378
379 private Single<ProfileAndCredential> retrieveProfile(
380 SignalServiceAddress address,
381 Optional<ProfileKey> profileKey,
382 Optional<UnidentifiedAccess> unidentifiedAccess,
383 SignalServiceProfile.RequestType requestType
384 ) {
385 final var profileService = dependencies.getProfileService();
386 final var locale = Utils.getDefaultLocale(Locale.US);
387
388 return profileService.getProfile(address, profileKey, unidentifiedAccess, requestType, locale).map(pair -> {
389 var processor = new ProfileService.ProfileResponseProcessor(pair);
390 if (processor.hasResult()) {
391 return processor.getResult();
392 } else if (processor.notFound()) {
393 throw new NotFoundException("Profile not found");
394 } else {
395 throw pair.getExecutionError()
396 .or(pair::getApplicationError)
397 .orElseThrow(() -> new IOException("Unknown error while retrieving profile"));
398 }
399 });
400 }
401
402 private void downloadProfileAvatar(
403 RecipientAddress address, String avatarPath, ProfileKey profileKey
404 ) {
405 if (avatarPath == null) {
406 try {
407 context.getAvatarStore().deleteProfileAvatar(address);
408 } catch (IOException e) {
409 logger.warn("Failed to delete local profile avatar, ignoring: {}", e.getMessage());
410 }
411 return;
412 }
413
414 try {
415 context.getAvatarStore()
416 .storeProfileAvatar(address,
417 outputStream -> retrieveProfileAvatar(avatarPath, profileKey, outputStream));
418 } catch (Throwable e) {
419 logger.warn("Failed to download profile avatar, ignoring: {}", e.getMessage());
420 }
421 }
422
423 private void retrieveProfileAvatar(
424 String avatarPath, ProfileKey profileKey, OutputStream outputStream
425 ) throws IOException {
426 var tmpFile = IOUtils.createTempFile();
427 try (var input = dependencies.getMessageReceiver()
428 .retrieveProfileAvatar(avatarPath,
429 tmpFile,
430 profileKey,
431 ServiceConfig.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE)) {
432 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
433 IOUtils.copyStream(input, outputStream, (int) ServiceConfig.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE);
434 } finally {
435 try {
436 Files.delete(tmpFile.toPath());
437 } catch (IOException e) {
438 logger.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
439 tmpFile,
440 e.getMessage());
441 }
442 }
443 }
444
445 private Optional<UnidentifiedAccess> getUnidentifiedAccess(RecipientId recipientId) {
446 var unidentifiedAccess = context.getUnidentifiedAccessHelper().getAccessFor(recipientId, true);
447
448 if (unidentifiedAccess.isPresent()) {
449 return unidentifiedAccess.get().getTargetUnidentifiedAccess();
450 }
451
452 return Optional.empty();
453 }
454 }