1 package org
.asamk
.signal
.manager
.storage
.recipients
;
3 import org
.asamk
.signal
.manager
.api
.Contact
;
4 import org
.asamk
.signal
.manager
.api
.Pair
;
5 import org
.asamk
.signal
.manager
.api
.Profile
;
6 import org
.asamk
.signal
.manager
.api
.UnregisteredRecipientException
;
7 import org
.asamk
.signal
.manager
.storage
.Database
;
8 import org
.asamk
.signal
.manager
.storage
.Utils
;
9 import org
.asamk
.signal
.manager
.storage
.contacts
.ContactsStore
;
10 import org
.asamk
.signal
.manager
.storage
.profiles
.ProfileStore
;
11 import org
.signal
.libsignal
.zkgroup
.InvalidInputException
;
12 import org
.signal
.libsignal
.zkgroup
.profiles
.ExpiringProfileKeyCredential
;
13 import org
.signal
.libsignal
.zkgroup
.profiles
.ProfileKey
;
14 import org
.slf4j
.Logger
;
15 import org
.slf4j
.LoggerFactory
;
16 import org
.whispersystems
.signalservice
.api
.push
.ServiceId
;
17 import org
.whispersystems
.signalservice
.api
.push
.ServiceId
.ACI
;
18 import org
.whispersystems
.signalservice
.api
.push
.ServiceId
.PNI
;
19 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
20 import org
.whispersystems
.signalservice
.api
.util
.UuidUtil
;
22 import java
.sql
.Connection
;
23 import java
.sql
.ResultSet
;
24 import java
.sql
.SQLException
;
25 import java
.util
.ArrayList
;
26 import java
.util
.Arrays
;
27 import java
.util
.Collection
;
28 import java
.util
.HashMap
;
29 import java
.util
.List
;
31 import java
.util
.Objects
;
32 import java
.util
.Optional
;
34 import java
.util
.function
.Supplier
;
35 import java
.util
.stream
.Collectors
;
37 public class RecipientStore
implements RecipientIdCreator
, RecipientResolver
, RecipientTrustedResolver
, ContactsStore
, ProfileStore
{
39 private final static Logger logger
= LoggerFactory
.getLogger(RecipientStore
.class);
40 private static final String TABLE_RECIPIENT
= "recipient";
41 private static final String SQL_IS_CONTACT
= "r.given_name IS NOT NULL OR r.family_name IS NOT NULL OR r.expiration_time > 0 OR r.profile_sharing = TRUE OR r.color IS NOT NULL OR r.blocked = TRUE OR r.archived = TRUE";
43 private final RecipientMergeHandler recipientMergeHandler
;
44 private final SelfAddressProvider selfAddressProvider
;
45 private final Database database
;
47 private final Object recipientsLock
= new Object();
48 private final Map
<Long
, Long
> recipientsMerged
= new HashMap
<>();
50 private final Map
<ServiceId
, RecipientWithAddress
> recipientAddressCache
= new HashMap
<>();
52 public static void createSql(Connection connection
) throws SQLException
{
53 // When modifying the CREATE statement here, also add a migration in AccountDatabase.java
54 try (final var statement
= connection
.createStatement()) {
55 statement
.executeUpdate("""
56 CREATE TABLE recipient (
57 _id INTEGER PRIMARY KEY AUTOINCREMENT,
63 profile_key_credential BLOB,
69 expiration_time INTEGER NOT NULL DEFAULT 0,
70 blocked INTEGER NOT NULL DEFAULT FALSE,
71 archived INTEGER NOT NULL DEFAULT FALSE,
72 profile_sharing INTEGER NOT NULL DEFAULT FALSE,
74 profile_last_update_timestamp INTEGER NOT NULL DEFAULT 0,
75 profile_given_name TEXT,
76 profile_family_name TEXT,
78 profile_about_emoji TEXT,
79 profile_avatar_url_path TEXT,
80 profile_mobile_coin_address BLOB,
81 profile_unidentified_access_mode TEXT,
82 profile_capabilities TEXT
88 public RecipientStore(
89 final RecipientMergeHandler recipientMergeHandler
,
90 final SelfAddressProvider selfAddressProvider
,
91 final Database database
93 this.recipientMergeHandler
= recipientMergeHandler
;
94 this.selfAddressProvider
= selfAddressProvider
;
95 this.database
= database
;
98 public RecipientAddress
resolveRecipientAddress(RecipientId recipientId
) {
101 SELECT r.number, r.uuid, r.pni, r.username
105 ).formatted(TABLE_RECIPIENT
);
106 try (final var connection
= database
.getConnection()) {
107 try (final var statement
= connection
.prepareStatement(sql
)) {
108 statement
.setLong(1, recipientId
.id());
109 return Utils
.executeQuerySingleRow(statement
, this::getRecipientAddressFromResultSet
);
111 } catch (SQLException e
) {
112 throw new RuntimeException("Failed read from recipient store", e
);
116 public Collection
<RecipientId
> getRecipientIdsWithEnabledProfileSharing() {
121 WHERE r.blocked = FALSE AND r.profile_sharing = TRUE
123 ).formatted(TABLE_RECIPIENT
);
124 try (final var connection
= database
.getConnection()) {
125 try (final var statement
= connection
.prepareStatement(sql
)) {
126 try (var result
= Utils
.executeQueryForStream(statement
, this::getRecipientIdFromResultSet
)) {
127 return result
.toList();
130 } catch (SQLException e
) {
131 throw new RuntimeException("Failed read from recipient store", e
);
136 public RecipientId
resolveRecipient(final long rawRecipientId
) {
143 ).formatted(TABLE_RECIPIENT
);
144 try (final var connection
= database
.getConnection()) {
145 try (final var statement
= connection
.prepareStatement(sql
)) {
146 statement
.setLong(1, rawRecipientId
);
147 return Utils
.executeQueryForOptional(statement
, this::getRecipientIdFromResultSet
).orElse(null);
149 } catch (SQLException e
) {
150 throw new RuntimeException("Failed read from recipient store", e
);
155 public RecipientId
resolveRecipient(final String identifier
) {
156 final var serviceId
= ServiceId
.parseOrNull(identifier
);
157 if (serviceId
!= null) {
158 return resolveRecipient(serviceId
);
160 return resolveRecipientByNumber(identifier
);
164 private RecipientId
resolveRecipientByNumber(final String number
) {
165 synchronized (recipientsLock
) {
166 final RecipientId recipientId
;
167 try (final var connection
= database
.getConnection()) {
168 connection
.setAutoCommit(false);
169 recipientId
= resolveRecipientLocked(connection
, number
);
171 } catch (SQLException e
) {
172 throw new RuntimeException("Failed read recipient store", e
);
179 public RecipientId
resolveRecipient(final ServiceId serviceId
) {
180 synchronized (recipientsLock
) {
181 final var recipientWithAddress
= recipientAddressCache
.get(serviceId
);
182 if (recipientWithAddress
!= null) {
183 return recipientWithAddress
.id();
185 try (final var connection
= database
.getConnection()) {
186 connection
.setAutoCommit(false);
187 final var recipientId
= resolveRecipientLocked(connection
, serviceId
);
190 } catch (SQLException e
) {
191 throw new RuntimeException("Failed read recipient store", e
);
197 * Should only be used for recipientIds from the database.
198 * Where the foreign key relations ensure a valid recipientId.
201 public RecipientId
create(final long recipientId
) {
202 return new RecipientId(recipientId
, this);
205 public RecipientId
resolveRecipientByNumber(
206 final String number
, Supplier
<ServiceId
> serviceIdSupplier
207 ) throws UnregisteredRecipientException
{
208 final Optional
<RecipientWithAddress
> byNumber
;
209 try (final var connection
= database
.getConnection()) {
210 byNumber
= findByNumber(connection
, number
);
211 } catch (SQLException e
) {
212 throw new RuntimeException("Failed read from recipient store", e
);
214 if (byNumber
.isEmpty() || byNumber
.get().address().serviceId().isEmpty()) {
215 final var serviceId
= serviceIdSupplier
.get();
216 if (serviceId
== null) {
217 throw new UnregisteredRecipientException(new org
.asamk
.signal
.manager
.api
.RecipientAddress(null,
221 return resolveRecipient(serviceId
);
223 return byNumber
.get().id();
226 public Optional
<RecipientId
> resolveRecipientByNumberOptional(final String number
) {
227 final Optional
<RecipientWithAddress
> byNumber
;
228 try (final var connection
= database
.getConnection()) {
229 byNumber
= findByNumber(connection
, number
);
230 } catch (SQLException e
) {
231 throw new RuntimeException("Failed read from recipient store", e
);
233 return byNumber
.map(RecipientWithAddress
::id
);
236 public RecipientId
resolveRecipientByUsername(
237 final String username
, Supplier
<ACI
> aciSupplier
238 ) throws UnregisteredRecipientException
{
239 final Optional
<RecipientWithAddress
> byUsername
;
240 try (final var connection
= database
.getConnection()) {
241 byUsername
= findByUsername(connection
, username
);
242 } catch (SQLException e
) {
243 throw new RuntimeException("Failed read from recipient store", e
);
245 if (byUsername
.isEmpty() || byUsername
.get().address().serviceId().isEmpty()) {
246 final var aci
= aciSupplier
.get();
248 throw new UnregisteredRecipientException(new org
.asamk
.signal
.manager
.api
.RecipientAddress(null,
253 return resolveRecipientTrusted(aci
, username
);
255 return byUsername
.get().id();
258 public RecipientId
resolveRecipient(RecipientAddress address
) {
259 synchronized (recipientsLock
) {
260 final RecipientId recipientId
;
261 try (final var connection
= database
.getConnection()) {
262 connection
.setAutoCommit(false);
263 recipientId
= resolveRecipientLocked(connection
, address
);
265 } catch (SQLException e
) {
266 throw new RuntimeException("Failed read recipient store", e
);
273 public RecipientId
resolveSelfRecipientTrusted(RecipientAddress address
) {
274 return resolveRecipientTrusted(address
, true);
277 public RecipientId
resolveRecipientTrusted(RecipientAddress address
) {
278 return resolveRecipientTrusted(address
, false);
282 public RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
283 return resolveRecipientTrusted(new RecipientAddress(address
), false);
287 public RecipientId
resolveRecipientTrusted(
288 final Optional
<ACI
> aci
, final Optional
<PNI
> pni
, final Optional
<String
> number
290 final var serviceId
= aci
.map(a
-> (ServiceId
) a
).or(() -> pni
);
291 return resolveRecipientTrusted(new RecipientAddress(serviceId
, pni
, number
, Optional
.empty()), false);
295 public RecipientId
resolveRecipientTrusted(final ACI aci
, final String username
) {
296 return resolveRecipientTrusted(new RecipientAddress(aci
, null, null, username
), false);
300 public void storeContact(RecipientId recipientId
, final Contact contact
) {
301 try (final var connection
= database
.getConnection()) {
302 storeContact(connection
, recipientId
, contact
);
303 } catch (SQLException e
) {
304 throw new RuntimeException("Failed update recipient store", e
);
309 public Contact
getContact(RecipientId recipientId
) {
310 try (final var connection
= database
.getConnection()) {
311 return getContact(connection
, recipientId
);
312 } catch (SQLException e
) {
313 throw new RuntimeException("Failed read from recipient store", e
);
318 public List
<Pair
<RecipientId
, Contact
>> getContacts() {
321 SELECT r._id, r.given_name, r.family_name, r.expiration_time, r.profile_sharing, r.color, r.blocked, r.archived
323 WHERE (r.number IS NOT NULL OR r.uuid IS NOT NULL) AND %s
325 ).formatted(TABLE_RECIPIENT
, SQL_IS_CONTACT
);
326 try (final var connection
= database
.getConnection()) {
327 try (final var statement
= connection
.prepareStatement(sql
)) {
328 try (var result
= Utils
.executeQueryForStream(statement
,
329 resultSet
-> new Pair
<>(getRecipientIdFromResultSet(resultSet
),
330 getContactFromResultSet(resultSet
)))) {
331 return result
.toList();
334 } catch (SQLException e
) {
335 throw new RuntimeException("Failed read from recipient store", e
);
339 public List
<Recipient
> getRecipients(
340 boolean onlyContacts
, Optional
<Boolean
> blocked
, Set
<RecipientId
> recipientIds
, Optional
<String
> name
342 final var sqlWhere
= new ArrayList
<String
>();
344 sqlWhere
.add("(" + SQL_IS_CONTACT
+ ")");
346 if (blocked
.isPresent()) {
347 sqlWhere
.add("r.blocked = ?");
349 if (!recipientIds
.isEmpty()) {
350 final var recipientIdsCommaSeparated
= recipientIds
.stream()
351 .map(recipientId
-> String
.valueOf(recipientId
.id()))
352 .collect(Collectors
.joining(","));
353 sqlWhere
.add("r._id IN (" + recipientIdsCommaSeparated
+ ")");
358 r.number, r.uuid, r.pni, r.username,
359 r.profile_key, r.profile_key_credential,
360 r.given_name, r.family_name, r.expiration_time, r.profile_sharing, r.color, r.blocked, r.archived,
361 r.profile_last_update_timestamp, r.profile_given_name, r.profile_family_name, r.profile_about, r.profile_about_emoji, r.profile_avatar_url_path, r.profile_mobile_coin_address, r.profile_unidentified_access_mode, r.profile_capabilities
363 WHERE (r.number IS NOT NULL OR r.uuid IS NOT NULL) AND %s
365 ).formatted(TABLE_RECIPIENT
, sqlWhere
.isEmpty() ?
"TRUE" : String
.join(" AND ", sqlWhere
));
366 try (final var connection
= database
.getConnection()) {
367 try (final var statement
= connection
.prepareStatement(sql
)) {
368 if (blocked
.isPresent()) {
369 statement
.setBoolean(1, blocked
.get());
371 try (var result
= Utils
.executeQueryForStream(statement
, this::getRecipientFromResultSet
)) {
372 return result
.filter(r
-> name
.isEmpty() || (
373 r
.getContact() != null && name
.get().equals(r
.getContact().getName())
374 ) || (r
.getProfile() != null && name
.get().equals(r
.getProfile().getDisplayName()))).toList();
377 } catch (SQLException e
) {
378 throw new RuntimeException("Failed read from recipient store", e
);
382 public Set
<String
> getAllNumbers() {
387 WHERE r.number IS NOT NULL
389 ).formatted(TABLE_RECIPIENT
);
390 try (final var connection
= database
.getConnection()) {
391 try (final var statement
= connection
.prepareStatement(sql
)) {
392 return Utils
.executeQueryForStream(statement
, resultSet
-> resultSet
.getString("number"))
393 .filter(Objects
::nonNull
)
398 } catch (NumberFormatException e
) {
402 .collect(Collectors
.toSet());
404 } catch (SQLException e
) {
405 throw new RuntimeException("Failed read from recipient store", e
);
409 public Map
<ServiceId
, ProfileKey
> getServiceIdToProfileKeyMap() {
412 SELECT r.uuid, r.profile_key
414 WHERE r.uuid IS NOT NULL AND r.profile_key IS NOT NULL
416 ).formatted(TABLE_RECIPIENT
);
417 try (final var connection
= database
.getConnection()) {
418 try (final var statement
= connection
.prepareStatement(sql
)) {
419 return Utils
.executeQueryForStream(statement
, resultSet
-> {
420 final var serviceId
= ServiceId
.parseOrThrow(resultSet
.getBytes("uuid"));
421 final var profileKey
= getProfileKeyFromResultSet(resultSet
);
422 return new Pair
<>(serviceId
, profileKey
);
423 }).filter(Objects
::nonNull
).collect(Collectors
.toMap(Pair
::first
, Pair
::second
));
425 } catch (SQLException e
) {
426 throw new RuntimeException("Failed read from recipient store", e
);
431 public void deleteContact(RecipientId recipientId
) {
432 storeContact(recipientId
, null);
435 public void deleteRecipientData(RecipientId recipientId
) {
436 logger
.debug("Deleting recipient data for {}", recipientId
);
437 synchronized (recipientsLock
) {
438 recipientAddressCache
.entrySet().removeIf(e
-> e
.getValue().id().equals(recipientId
));
439 try (final var connection
= database
.getConnection()) {
440 connection
.setAutoCommit(false);
441 storeContact(connection
, recipientId
, null);
442 storeProfile(connection
, recipientId
, null);
443 storeProfileKey(connection
, recipientId
, null, false);
444 storeExpiringProfileKeyCredential(connection
, recipientId
, null);
445 deleteRecipient(connection
, recipientId
);
447 } catch (SQLException e
) {
448 throw new RuntimeException("Failed update recipient store", e
);
454 public Profile
getProfile(final RecipientId recipientId
) {
455 try (final var connection
= database
.getConnection()) {
456 return getProfile(connection
, recipientId
);
457 } catch (SQLException e
) {
458 throw new RuntimeException("Failed read from recipient store", e
);
463 public ProfileKey
getProfileKey(final RecipientId recipientId
) {
464 try (final var connection
= database
.getConnection()) {
465 return getProfileKey(connection
, recipientId
);
466 } catch (SQLException e
) {
467 throw new RuntimeException("Failed read from recipient store", e
);
472 public ExpiringProfileKeyCredential
getExpiringProfileKeyCredential(final RecipientId recipientId
) {
473 try (final var connection
= database
.getConnection()) {
474 return getExpiringProfileKeyCredential(connection
, recipientId
);
475 } catch (SQLException e
) {
476 throw new RuntimeException("Failed read from recipient store", e
);
481 public void storeProfile(RecipientId recipientId
, final Profile profile
) {
482 try (final var connection
= database
.getConnection()) {
483 storeProfile(connection
, recipientId
, profile
);
484 } catch (SQLException e
) {
485 throw new RuntimeException("Failed update recipient store", e
);
490 public void storeSelfProfileKey(final RecipientId recipientId
, final ProfileKey profileKey
) {
491 try (final var connection
= database
.getConnection()) {
492 storeProfileKey(connection
, recipientId
, profileKey
, false);
493 } catch (SQLException e
) {
494 throw new RuntimeException("Failed update recipient store", e
);
499 public void storeProfileKey(RecipientId recipientId
, final ProfileKey profileKey
) {
500 try (final var connection
= database
.getConnection()) {
501 storeProfileKey(connection
, recipientId
, profileKey
, true);
502 } catch (SQLException e
) {
503 throw new RuntimeException("Failed update recipient store", e
);
508 public void storeExpiringProfileKeyCredential(
509 RecipientId recipientId
, final ExpiringProfileKeyCredential profileKeyCredential
511 try (final var connection
= database
.getConnection()) {
512 storeExpiringProfileKeyCredential(connection
, recipientId
, profileKeyCredential
);
513 } catch (SQLException e
) {
514 throw new RuntimeException("Failed update recipient store", e
);
518 void addLegacyRecipients(final Map
<RecipientId
, Recipient
> recipients
) {
519 logger
.debug("Migrating legacy recipients to database");
520 long start
= System
.nanoTime();
523 INSERT INTO %s (_id, number, uuid)
526 ).formatted(TABLE_RECIPIENT
);
527 try (final var connection
= database
.getConnection()) {
528 connection
.setAutoCommit(false);
529 try (final var statement
= connection
.prepareStatement("DELETE FROM %s".formatted(TABLE_RECIPIENT
))) {
530 statement
.executeUpdate();
532 try (final var statement
= connection
.prepareStatement(sql
)) {
533 for (final var recipient
: recipients
.values()) {
534 statement
.setLong(1, recipient
.getRecipientId().id());
535 statement
.setString(2, recipient
.getAddress().number().orElse(null));
536 statement
.setBytes(3,
537 recipient
.getAddress()
539 .map(ServiceId
::getRawUuid
)
540 .map(UuidUtil
::toByteArray
)
542 statement
.executeUpdate();
545 logger
.debug("Initial inserts took {}ms", (System
.nanoTime() - start
) / 1000000);
547 for (final var recipient
: recipients
.values()) {
548 if (recipient
.getContact() != null) {
549 storeContact(connection
, recipient
.getRecipientId(), recipient
.getContact());
551 if (recipient
.getProfile() != null) {
552 storeProfile(connection
, recipient
.getRecipientId(), recipient
.getProfile());
554 if (recipient
.getProfileKey() != null) {
555 storeProfileKey(connection
, recipient
.getRecipientId(), recipient
.getProfileKey(), false);
557 if (recipient
.getExpiringProfileKeyCredential() != null) {
558 storeExpiringProfileKeyCredential(connection
,
559 recipient
.getRecipientId(),
560 recipient
.getExpiringProfileKeyCredential());
564 } catch (SQLException e
) {
565 throw new RuntimeException("Failed update recipient store", e
);
567 logger
.debug("Complete recipients migration took {}ms", (System
.nanoTime() - start
) / 1000000);
570 long getActualRecipientId(long recipientId
) {
571 while (recipientsMerged
.containsKey(recipientId
)) {
572 final var newRecipientId
= recipientsMerged
.get(recipientId
);
573 logger
.debug("Using {} instead of {}, because recipients have been merged", newRecipientId
, recipientId
);
574 recipientId
= newRecipientId
;
579 private void storeContact(
580 final Connection connection
, final RecipientId recipientId
, final Contact contact
581 ) throws SQLException
{
585 SET given_name = ?, family_name = ?, expiration_time = ?, profile_sharing = ?, color = ?, blocked = ?, archived = ?
588 ).formatted(TABLE_RECIPIENT
);
589 try (final var statement
= connection
.prepareStatement(sql
)) {
590 statement
.setString(1, contact
== null ?
null : contact
.getGivenName());
591 statement
.setString(2, contact
== null ?
null : contact
.getFamilyName());
592 statement
.setInt(3, contact
== null ?
0 : contact
.getMessageExpirationTime());
593 statement
.setBoolean(4, contact
!= null && contact
.isProfileSharingEnabled());
594 statement
.setString(5, contact
== null ?
null : contact
.getColor());
595 statement
.setBoolean(6, contact
!= null && contact
.isBlocked());
596 statement
.setBoolean(7, contact
!= null && contact
.isArchived());
597 statement
.setLong(8, recipientId
.id());
598 statement
.executeUpdate();
602 private void storeExpiringProfileKeyCredential(
603 final Connection connection
,
604 final RecipientId recipientId
,
605 final ExpiringProfileKeyCredential profileKeyCredential
606 ) throws SQLException
{
610 SET profile_key_credential = ?
613 ).formatted(TABLE_RECIPIENT
);
614 try (final var statement
= connection
.prepareStatement(sql
)) {
615 statement
.setBytes(1, profileKeyCredential
== null ?
null : profileKeyCredential
.serialize());
616 statement
.setLong(2, recipientId
.id());
617 statement
.executeUpdate();
621 private void storeProfile(
622 final Connection connection
, final RecipientId recipientId
, final Profile profile
623 ) throws SQLException
{
627 SET profile_last_update_timestamp = ?, profile_given_name = ?, profile_family_name = ?, profile_about = ?, profile_about_emoji = ?, profile_avatar_url_path = ?, profile_mobile_coin_address = ?, profile_unidentified_access_mode = ?, profile_capabilities = ?
630 ).formatted(TABLE_RECIPIENT
);
631 try (final var statement
= connection
.prepareStatement(sql
)) {
632 statement
.setLong(1, profile
== null ?
0 : profile
.getLastUpdateTimestamp());
633 statement
.setString(2, profile
== null ?
null : profile
.getGivenName());
634 statement
.setString(3, profile
== null ?
null : profile
.getFamilyName());
635 statement
.setString(4, profile
== null ?
null : profile
.getAbout());
636 statement
.setString(5, profile
== null ?
null : profile
.getAboutEmoji());
637 statement
.setString(6, profile
== null ?
null : profile
.getAvatarUrlPath());
638 statement
.setBytes(7, profile
== null ?
null : profile
.getMobileCoinAddress());
639 statement
.setString(8, profile
== null ?
null : profile
.getUnidentifiedAccessMode().name());
640 statement
.setString(9,
643 : profile
.getCapabilities().stream().map(Enum
::name
).collect(Collectors
.joining(",")));
644 statement
.setLong(10, recipientId
.id());
645 statement
.executeUpdate();
649 private void storeProfileKey(
650 Connection connection
, RecipientId recipientId
, final ProfileKey profileKey
, boolean resetProfile
651 ) throws SQLException
{
652 if (profileKey
!= null) {
653 final var recipientProfileKey
= getProfileKey(recipientId
);
654 if (profileKey
.equals(recipientProfileKey
)) {
655 final var recipientProfile
= getProfile(recipientId
);
656 if (recipientProfile
== null || (
657 recipientProfile
.getUnidentifiedAccessMode() != Profile
.UnidentifiedAccessMode
.UNKNOWN
658 && recipientProfile
.getUnidentifiedAccessMode()
659 != Profile
.UnidentifiedAccessMode
.DISABLED
669 SET profile_key = ?, profile_key_credential = NULL%s
672 ).formatted(TABLE_RECIPIENT
, resetProfile ?
", profile_last_update_timestamp = 0" : "");
673 try (final var statement
= connection
.prepareStatement(sql
)) {
674 statement
.setBytes(1, profileKey
== null ?
null : profileKey
.serialize());
675 statement
.setLong(2, recipientId
.id());
676 statement
.executeUpdate();
680 private RecipientId
resolveRecipientTrusted(RecipientAddress address
, boolean isSelf
) {
681 final Pair
<RecipientId
, List
<RecipientId
>> pair
;
682 synchronized (recipientsLock
) {
683 try (final var connection
= database
.getConnection()) {
684 connection
.setAutoCommit(false);
685 if (address
.hasSingleIdentifier() || (
686 !isSelf
&& selfAddressProvider
.getSelfAddress().matches(address
)
688 pair
= new Pair
<>(resolveRecipientLocked(connection
, address
), List
.of());
690 pair
= MergeRecipientHelper
.resolveRecipientTrustedLocked(new HelperStore(connection
), address
);
692 for (final var toBeMergedRecipientId
: pair
.second()) {
693 mergeRecipientsLocked(connection
, pair
.first(), toBeMergedRecipientId
);
697 } catch (SQLException e
) {
698 throw new RuntimeException("Failed update recipient store", e
);
702 if (!pair
.second().isEmpty()) {
703 try (final var connection
= database
.getConnection()) {
704 for (final var toBeMergedRecipientId
: pair
.second()) {
705 recipientMergeHandler
.mergeRecipients(connection
, pair
.first(), toBeMergedRecipientId
);
706 deleteRecipient(connection
, toBeMergedRecipientId
);
707 synchronized (recipientsLock
) {
708 recipientAddressCache
.entrySet().removeIf(e
-> e
.getValue().id().equals(toBeMergedRecipientId
));
711 } catch (SQLException e
) {
712 throw new RuntimeException("Failed update recipient store", e
);
718 private RecipientId
resolveRecipientLocked(
719 Connection connection
, RecipientAddress address
720 ) throws SQLException
{
721 final var byServiceId
= address
.serviceId().isEmpty()
722 ? Optional
.<RecipientWithAddress
>empty()
723 : findByServiceId(connection
, address
.serviceId().get());
725 if (byServiceId
.isPresent()) {
726 return byServiceId
.get().id();
729 final var byPni
= address
.pni().isEmpty()
730 ? Optional
.<RecipientWithAddress
>empty()
731 : findByServiceId(connection
, address
.pni().get());
733 if (byPni
.isPresent()) {
734 return byPni
.get().id();
737 final var byNumber
= address
.number().isEmpty()
738 ? Optional
.<RecipientWithAddress
>empty()
739 : findByNumber(connection
, address
.number().get());
741 if (byNumber
.isPresent()) {
742 return byNumber
.get().id();
745 logger
.debug("Got new recipient, both serviceId and number are unknown");
747 if (address
.serviceId().isEmpty()) {
748 return addNewRecipient(connection
, address
);
751 return addNewRecipient(connection
, new RecipientAddress(address
.serviceId().get()));
754 private RecipientId
resolveRecipientLocked(Connection connection
, ServiceId serviceId
) throws SQLException
{
755 final var recipient
= findByServiceId(connection
, serviceId
);
757 if (recipient
.isEmpty()) {
758 logger
.debug("Got new recipient, serviceId is unknown");
759 return addNewRecipient(connection
, new RecipientAddress(serviceId
));
762 return recipient
.get().id();
765 private RecipientId
resolveRecipientLocked(Connection connection
, String number
) throws SQLException
{
766 final var recipient
= findByNumber(connection
, number
);
768 if (recipient
.isEmpty()) {
769 logger
.debug("Got new recipient, number is unknown");
770 return addNewRecipient(connection
, new RecipientAddress(null, number
));
773 return recipient
.get().id();
776 private RecipientId
addNewRecipient(
777 final Connection connection
, final RecipientAddress address
778 ) throws SQLException
{
781 INSERT INTO %s (number, uuid, pni)
785 ).formatted(TABLE_RECIPIENT
);
786 try (final var statement
= connection
.prepareStatement(sql
)) {
787 statement
.setString(1, address
.number().orElse(null));
788 statement
.setBytes(2,
789 address
.serviceId().map(ServiceId
::getRawUuid
).map(UuidUtil
::toByteArray
).orElse(null));
790 statement
.setBytes(3, address
.pni().map(PNI
::getRawUuid
).map(UuidUtil
::toByteArray
).orElse(null));
791 final var generatedKey
= Utils
.executeQueryForOptional(statement
, Utils
::getIdMapper
);
792 if (generatedKey
.isPresent()) {
793 final var recipientId
= new RecipientId(generatedKey
.get(), this);
794 logger
.debug("Added new recipient {} with address {}", recipientId
, address
);
797 throw new RuntimeException("Failed to add new recipient to database");
802 private void removeRecipientAddress(Connection connection
, RecipientId recipientId
) throws SQLException
{
803 synchronized (recipientsLock
) {
804 recipientAddressCache
.entrySet().removeIf(e
-> e
.getValue().id().equals(recipientId
));
808 SET number = NULL, uuid = NULL, pni = NULL
811 ).formatted(TABLE_RECIPIENT
);
812 try (final var statement
= connection
.prepareStatement(sql
)) {
813 statement
.setLong(1, recipientId
.id());
814 statement
.executeUpdate();
819 private void updateRecipientAddress(
820 Connection connection
, RecipientId recipientId
, final RecipientAddress address
821 ) throws SQLException
{
822 synchronized (recipientsLock
) {
823 recipientAddressCache
.entrySet().removeIf(e
-> e
.getValue().id().equals(recipientId
));
827 SET number = ?, uuid = ?, pni = ?, username = ?
830 ).formatted(TABLE_RECIPIENT
);
831 try (final var statement
= connection
.prepareStatement(sql
)) {
832 statement
.setString(1, address
.number().orElse(null));
833 statement
.setBytes(2,
834 address
.serviceId().map(ServiceId
::getRawUuid
).map(UuidUtil
::toByteArray
).orElse(null));
835 statement
.setBytes(3, address
.pni().map(PNI
::getRawUuid
).map(UuidUtil
::toByteArray
).orElse(null));
836 statement
.setString(4, address
.username().orElse(null));
837 statement
.setLong(5, recipientId
.id());
838 statement
.executeUpdate();
843 private void deleteRecipient(final Connection connection
, final RecipientId recipientId
) throws SQLException
{
849 ).formatted(TABLE_RECIPIENT
);
850 try (final var statement
= connection
.prepareStatement(sql
)) {
851 statement
.setLong(1, recipientId
.id());
852 statement
.executeUpdate();
856 private void mergeRecipientsLocked(
857 Connection connection
, RecipientId recipientId
, RecipientId toBeMergedRecipientId
858 ) throws SQLException
{
859 final var contact
= getContact(connection
, recipientId
);
860 if (contact
== null) {
861 final var toBeMergedContact
= getContact(connection
, toBeMergedRecipientId
);
862 storeContact(connection
, recipientId
, toBeMergedContact
);
865 final var profileKey
= getProfileKey(connection
, recipientId
);
866 if (profileKey
== null) {
867 final var toBeMergedProfileKey
= getProfileKey(connection
, toBeMergedRecipientId
);
868 storeProfileKey(connection
, recipientId
, toBeMergedProfileKey
, false);
871 final var profileKeyCredential
= getExpiringProfileKeyCredential(connection
, recipientId
);
872 if (profileKeyCredential
== null) {
873 final var toBeMergedProfileKeyCredential
= getExpiringProfileKeyCredential(connection
,
874 toBeMergedRecipientId
);
875 storeExpiringProfileKeyCredential(connection
, recipientId
, toBeMergedProfileKeyCredential
);
878 final var profile
= getProfile(connection
, recipientId
);
879 if (profile
== null) {
880 final var toBeMergedProfile
= getProfile(connection
, toBeMergedRecipientId
);
881 storeProfile(connection
, recipientId
, toBeMergedProfile
);
884 recipientsMerged
.put(toBeMergedRecipientId
.id(), recipientId
.id());
887 private Optional
<RecipientWithAddress
> findByNumber(
888 final Connection connection
, final String number
889 ) throws SQLException
{
891 SELECT r._id, r.number, r.uuid, r.pni, r.username
895 """.formatted(TABLE_RECIPIENT
);
896 try (final var statement
= connection
.prepareStatement(sql
)) {
897 statement
.setString(1, number
);
898 return Utils
.executeQueryForOptional(statement
, this::getRecipientWithAddressFromResultSet
);
902 private Optional
<RecipientWithAddress
> findByUsername(
903 final Connection connection
, final String username
904 ) throws SQLException
{
906 SELECT r._id, r.number, r.uuid, r.pni, r.username
910 """.formatted(TABLE_RECIPIENT
);
911 try (final var statement
= connection
.prepareStatement(sql
)) {
912 statement
.setString(1, username
);
913 return Utils
.executeQueryForOptional(statement
, this::getRecipientWithAddressFromResultSet
);
917 private Optional
<RecipientWithAddress
> findByServiceId(
918 final Connection connection
, final ServiceId serviceId
919 ) throws SQLException
{
920 var recipientWithAddress
= Optional
.ofNullable(recipientAddressCache
.get(serviceId
));
921 if (recipientWithAddress
.isPresent()) {
922 return recipientWithAddress
;
925 SELECT r._id, r.number, r.uuid, r.pni, r.username
927 WHERE r.uuid = ?1 OR r.pni = ?1
929 """.formatted(TABLE_RECIPIENT
);
930 try (final var statement
= connection
.prepareStatement(sql
)) {
931 statement
.setBytes(1, UuidUtil
.toByteArray(serviceId
.getRawUuid()));
932 recipientWithAddress
= Utils
.executeQueryForOptional(statement
, this::getRecipientWithAddressFromResultSet
);
933 recipientWithAddress
.ifPresent(r
-> recipientAddressCache
.put(serviceId
, r
));
934 return recipientWithAddress
;
938 private Set
<RecipientWithAddress
> findAllByAddress(
939 final Connection connection
, final RecipientAddress address
940 ) throws SQLException
{
942 SELECT r._id, r.number, r.uuid, r.pni, r.username
944 WHERE r.uuid = ?1 OR r.pni = ?1 OR
945 r.uuid = ?2 OR r.pni = ?2 OR
948 """.formatted(TABLE_RECIPIENT
);
949 try (final var statement
= connection
.prepareStatement(sql
)) {
950 statement
.setBytes(1,
951 address
.serviceId().map(ServiceId
::getRawUuid
).map(UuidUtil
::toByteArray
).orElse(null));
952 statement
.setBytes(2, address
.pni().map(ServiceId
::getRawUuid
).map(UuidUtil
::toByteArray
).orElse(null));
953 statement
.setString(3, address
.number().orElse(null));
954 statement
.setString(4, address
.username().orElse(null));
955 return Utils
.executeQueryForStream(statement
, this::getRecipientWithAddressFromResultSet
)
956 .collect(Collectors
.toSet());
960 private Contact
getContact(final Connection connection
, final RecipientId recipientId
) throws SQLException
{
963 SELECT r.given_name, r.family_name, r.expiration_time, r.profile_sharing, r.color, r.blocked, r.archived
965 WHERE r._id = ? AND (%s)
967 ).formatted(TABLE_RECIPIENT
, SQL_IS_CONTACT
);
968 try (final var statement
= connection
.prepareStatement(sql
)) {
969 statement
.setLong(1, recipientId
.id());
970 return Utils
.executeQueryForOptional(statement
, this::getContactFromResultSet
).orElse(null);
974 private ProfileKey
getProfileKey(final Connection connection
, final RecipientId recipientId
) throws SQLException
{
981 ).formatted(TABLE_RECIPIENT
);
982 try (final var statement
= connection
.prepareStatement(sql
)) {
983 statement
.setLong(1, recipientId
.id());
984 return Utils
.executeQueryForOptional(statement
, this::getProfileKeyFromResultSet
).orElse(null);
988 private ExpiringProfileKeyCredential
getExpiringProfileKeyCredential(
989 final Connection connection
, final RecipientId recipientId
990 ) throws SQLException
{
993 SELECT r.profile_key_credential
997 ).formatted(TABLE_RECIPIENT
);
998 try (final var statement
= connection
.prepareStatement(sql
)) {
999 statement
.setLong(1, recipientId
.id());
1000 return Utils
.executeQueryForOptional(statement
, this::getExpiringProfileKeyCredentialFromResultSet
)
1005 private Profile
getProfile(final Connection connection
, final RecipientId recipientId
) throws SQLException
{
1008 SELECT r.profile_last_update_timestamp, r.profile_given_name, r.profile_family_name, r.profile_about, r.profile_about_emoji, r.profile_avatar_url_path, r.profile_mobile_coin_address, r.profile_unidentified_access_mode, r.profile_capabilities
1010 WHERE r._id = ? AND r.profile_capabilities IS NOT NULL
1012 ).formatted(TABLE_RECIPIENT
);
1013 try (final var statement
= connection
.prepareStatement(sql
)) {
1014 statement
.setLong(1, recipientId
.id());
1015 return Utils
.executeQueryForOptional(statement
, this::getProfileFromResultSet
).orElse(null);
1019 private RecipientAddress
getRecipientAddressFromResultSet(ResultSet resultSet
) throws SQLException
{
1020 final var pni
= Optional
.ofNullable(resultSet
.getBytes("pni")).map(UuidUtil
::parseOrNull
).map(PNI
::from
);
1021 final var serviceIdUuid
= Optional
.ofNullable(resultSet
.getBytes("uuid")).map(UuidUtil
::parseOrNull
);
1022 final var serviceId
= serviceIdUuid
.isPresent() && pni
.isPresent() && serviceIdUuid
.get()
1023 .equals(pni
.get().getRawUuid()) ? pni
.<ServiceId
>map(p
-> p
) : serviceIdUuid
.<ServiceId
>map(ACI
::from
);
1024 final var number
= Optional
.ofNullable(resultSet
.getString("number"));
1025 final var username
= Optional
.ofNullable(resultSet
.getString("username"));
1026 return new RecipientAddress(serviceId
, pni
, number
, username
);
1029 private RecipientId
getRecipientIdFromResultSet(ResultSet resultSet
) throws SQLException
{
1030 return new RecipientId(resultSet
.getLong("_id"), this);
1033 private RecipientWithAddress
getRecipientWithAddressFromResultSet(final ResultSet resultSet
) throws SQLException
{
1034 return new RecipientWithAddress(getRecipientIdFromResultSet(resultSet
),
1035 getRecipientAddressFromResultSet(resultSet
));
1038 private Recipient
getRecipientFromResultSet(final ResultSet resultSet
) throws SQLException
{
1039 return new Recipient(getRecipientIdFromResultSet(resultSet
),
1040 getRecipientAddressFromResultSet(resultSet
),
1041 getContactFromResultSet(resultSet
),
1042 getProfileKeyFromResultSet(resultSet
),
1043 getExpiringProfileKeyCredentialFromResultSet(resultSet
),
1044 getProfileFromResultSet(resultSet
));
1047 private Contact
getContactFromResultSet(ResultSet resultSet
) throws SQLException
{
1048 return new Contact(resultSet
.getString("given_name"),
1049 resultSet
.getString("family_name"),
1050 resultSet
.getString("color"),
1051 resultSet
.getInt("expiration_time"),
1052 resultSet
.getBoolean("blocked"),
1053 resultSet
.getBoolean("archived"),
1054 resultSet
.getBoolean("profile_sharing"));
1057 private Profile
getProfileFromResultSet(ResultSet resultSet
) throws SQLException
{
1058 final var profileCapabilities
= resultSet
.getString("profile_capabilities");
1059 final var profileUnidentifiedAccessMode
= resultSet
.getString("profile_unidentified_access_mode");
1060 return new Profile(resultSet
.getLong("profile_last_update_timestamp"),
1061 resultSet
.getString("profile_given_name"),
1062 resultSet
.getString("profile_family_name"),
1063 resultSet
.getString("profile_about"),
1064 resultSet
.getString("profile_about_emoji"),
1065 resultSet
.getString("profile_avatar_url_path"),
1066 resultSet
.getBytes("profile_mobile_coin_address"),
1067 profileUnidentifiedAccessMode
== null
1068 ? Profile
.UnidentifiedAccessMode
.UNKNOWN
1069 : Profile
.UnidentifiedAccessMode
.valueOfOrUnknown(profileUnidentifiedAccessMode
),
1070 profileCapabilities
== null
1072 : Arrays
.stream(profileCapabilities
.split(","))
1073 .map(Profile
.Capability
::valueOfOrNull
)
1074 .filter(Objects
::nonNull
)
1075 .collect(Collectors
.toSet()));
1078 private ProfileKey
getProfileKeyFromResultSet(ResultSet resultSet
) throws SQLException
{
1079 final var profileKey
= resultSet
.getBytes("profile_key");
1081 if (profileKey
== null) {
1085 return new ProfileKey(profileKey
);
1086 } catch (InvalidInputException ignored
) {
1091 private ExpiringProfileKeyCredential
getExpiringProfileKeyCredentialFromResultSet(ResultSet resultSet
) throws SQLException
{
1092 final var profileKeyCredential
= resultSet
.getBytes("profile_key_credential");
1094 if (profileKeyCredential
== null) {
1098 return new ExpiringProfileKeyCredential(profileKeyCredential
);
1099 } catch (Throwable ignored
) {
1104 public interface RecipientMergeHandler
{
1106 void mergeRecipients(
1107 final Connection connection
, RecipientId recipientId
, RecipientId toBeMergedRecipientId
1108 ) throws SQLException
;
1111 private class HelperStore
implements MergeRecipientHelper
.Store
{
1113 private final Connection connection
;
1115 public HelperStore(final Connection connection
) {
1116 this.connection
= connection
;
1120 public Set
<RecipientWithAddress
> findAllByAddress(final RecipientAddress address
) throws SQLException
{
1121 return RecipientStore
.this.findAllByAddress(connection
, address
);
1125 public RecipientId
addNewRecipient(final RecipientAddress address
) throws SQLException
{
1126 return RecipientStore
.this.addNewRecipient(connection
, address
);
1130 public void updateRecipientAddress(
1131 final RecipientId recipientId
, final RecipientAddress address
1132 ) throws SQLException
{
1133 RecipientStore
.this.updateRecipientAddress(connection
, recipientId
, address
);
1137 public void removeRecipientAddress(final RecipientId recipientId
) throws SQLException
{
1138 RecipientStore
.this.removeRecipientAddress(connection
, recipientId
);