1 package org
.asamk
.signal
.manager
.storage
.sendLog
;
3 import org
.asamk
.signal
.manager
.groups
.GroupId
;
4 import org
.asamk
.signal
.manager
.groups
.GroupUtils
;
5 import org
.asamk
.signal
.manager
.storage
.Database
;
6 import org
.asamk
.signal
.manager
.storage
.Utils
;
7 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
8 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientResolver
;
9 import org
.signal
.libsignal
.zkgroup
.InvalidInputException
;
10 import org
.signal
.libsignal
.zkgroup
.groups
.GroupMasterKey
;
11 import org
.slf4j
.Logger
;
12 import org
.slf4j
.LoggerFactory
;
13 import org
.whispersystems
.signalservice
.api
.crypto
.ContentHint
;
14 import org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
;
15 import org
.whispersystems
.signalservice
.internal
.push
.SignalServiceProtos
;
17 import java
.io
.IOException
;
18 import java
.sql
.Connection
;
19 import java
.sql
.SQLException
;
20 import java
.time
.Duration
;
21 import java
.util
.List
;
22 import java
.util
.Objects
;
23 import java
.util
.Optional
;
25 public class MessageSendLogStore
implements AutoCloseable
{
27 private static final Logger logger
= LoggerFactory
.getLogger(MessageSendLogStore
.class);
29 private static final String TABLE_MESSAGE_SEND_LOG
= "message_send_log";
30 private static final String TABLE_MESSAGE_SEND_LOG_CONTENT
= "message_send_log_content";
32 private static final Duration LOG_DURATION
= Duration
.ofDays(1);
34 private final RecipientResolver recipientResolver
;
35 private final Database database
;
36 private final Thread cleanupThread
;
38 public MessageSendLogStore(
39 final RecipientResolver recipientResolver
, final Database database
41 this.recipientResolver
= recipientResolver
;
42 this.database
= database
;
43 this.cleanupThread
= new Thread(() -> {
45 final var interval
= Duration
.ofHours(1).toMillis();
46 while (!Thread
.interrupted()) {
47 try (final var connection
= database
.getConnection()) {
48 deleteOutdatedEntries(connection
);
49 } catch (SQLException e
) {
50 logger
.warn("Deleting outdated entries failed");
53 Thread
.sleep(interval
);
55 } catch (InterruptedException e
) {
56 logger
.debug("Stopping msl cleanup thread");
59 cleanupThread
.setName("msl-cleanup");
60 cleanupThread
.setDaemon(true);
61 cleanupThread
.start();
64 public static void createSql(Connection connection
) throws SQLException
{
65 // When modifying the CREATE statement here, also add a migration in AccountDatabase.java
66 try (final var statement
= connection
.createStatement()) {
67 statement
.executeUpdate("""
68 CREATE TABLE message_send_log (
69 _id INTEGER PRIMARY KEY,
70 content_id INTEGER NOT NULL REFERENCES message_send_log_content (_id) ON DELETE CASCADE,
71 recipient_id INTEGER NOT NULL REFERENCES recipient (_id) ON DELETE CASCADE,
72 device_id INTEGER NOT NULL
74 CREATE TABLE message_send_log_content (
75 _id INTEGER PRIMARY KEY,
77 timestamp INTEGER NOT NULL,
78 content BLOB NOT NULL,
79 content_hint INTEGER NOT NULL
81 CREATE INDEX mslc_timestamp_index ON message_send_log_content (timestamp);
82 CREATE INDEX msl_recipient_index ON message_send_log (recipient_id, device_id, content_id);
83 CREATE INDEX msl_content_index ON message_send_log (content_id);
88 public List
<MessageSendLogEntry
> findMessages(
89 final RecipientId recipientId
, final int deviceId
, final long timestamp
, final boolean isSenderKey
92 SELECT group_id, content, content_hint
94 INNER JOIN %s lc ON l.content_id = lc._id
95 WHERE l.recipient_id = ? AND l.device_id = ? AND lc.timestamp = ?
96 """.formatted(TABLE_MESSAGE_SEND_LOG
, TABLE_MESSAGE_SEND_LOG_CONTENT
);
97 try (final var connection
= database
.getConnection()) {
98 deleteOutdatedEntries(connection
);
100 try (final var statement
= connection
.prepareStatement(sql
)) {
101 statement
.setLong(1, recipientId
.id());
102 statement
.setInt(2, deviceId
);
103 statement
.setLong(3, timestamp
);
104 try (var result
= Utils
.executeQueryForStream(statement
, resultSet
-> {
105 final var groupId
= Optional
.ofNullable(resultSet
.getBytes("group_id"))
106 .map(GroupId
::unknownVersion
);
107 final SignalServiceProtos
.Content content
;
109 content
= SignalServiceProtos
.Content
.parseFrom(resultSet
.getBinaryStream("content"));
110 } catch (IOException e
) {
111 logger
.warn("Failed to parse content from message send log", e
);
114 final var contentHint
= ContentHint
.fromType(resultSet
.getInt("content_hint"));
115 final var urgent
= true; // TODO
116 return new MessageSendLogEntry(groupId
, content
, contentHint
, urgent
);
118 return result
.filter(Objects
::nonNull
)
119 .filter(e
-> !isSenderKey
|| e
.groupId().isPresent())
123 } catch (SQLException e
) {
124 logger
.warn("Failed read from message send log", e
);
129 public long insertIfPossible(
130 long sentTimestamp
, SendMessageResult sendMessageResult
, ContentHint contentHint
, boolean urgent
132 final RecipientDevices recipientDevice
= getRecipientDevices(sendMessageResult
);
133 if (recipientDevice
== null) {
137 return insert(List
.of(recipientDevice
),
139 sendMessageResult
.getSuccess().getContent().get(),
144 public long insertIfPossible(
145 long sentTimestamp
, List
<SendMessageResult
> sendMessageResults
, ContentHint contentHint
, boolean urgent
147 final var recipientDevices
= sendMessageResults
.stream()
148 .map(this::getRecipientDevices
)
149 .filter(Objects
::nonNull
)
151 if (recipientDevices
.isEmpty()) {
155 final var content
= sendMessageResults
.stream()
156 .filter(r
-> r
.isSuccess() && r
.getSuccess().getContent().isPresent())
157 .map(r
-> r
.getSuccess().getContent().get())
161 return insert(recipientDevices
, sentTimestamp
, content
, contentHint
, urgent
);
164 public void addRecipientToExistingEntryIfPossible(final long contentId
, final SendMessageResult sendMessageResult
) {
165 final RecipientDevices recipientDevice
= getRecipientDevices(sendMessageResult
);
166 if (recipientDevice
== null) {
170 insertRecipientsForExistingContent(contentId
, List
.of(recipientDevice
));
173 public void addRecipientToExistingEntryIfPossible(
174 final long contentId
, final List
<SendMessageResult
> sendMessageResults
176 final var recipientDevices
= sendMessageResults
.stream()
177 .map(this::getRecipientDevices
)
178 .filter(Objects
::nonNull
)
180 if (recipientDevices
.isEmpty()) {
184 insertRecipientsForExistingContent(contentId
, recipientDevices
);
187 public void deleteEntryForGroup(long sentTimestamp
, GroupId groupId
) {
190 WHERE lc.timestamp = ? AND lc.group_id = ?
191 """.formatted(TABLE_MESSAGE_SEND_LOG_CONTENT
);
192 try (final var connection
= database
.getConnection()) {
193 try (final var statement
= connection
.prepareStatement(sql
)) {
194 statement
.setLong(1, sentTimestamp
);
195 statement
.setBytes(2, groupId
.serialize());
196 statement
.executeUpdate();
198 } catch (SQLException e
) {
199 logger
.warn("Failed delete from message send log", e
);
203 public void deleteEntryForRecipientNonGroup(long sentTimestamp
, RecipientId recipientId
) {
206 WHERE lc.timestamp = ? AND lc.group_id IS NULL AND lc._id IN (SELECT content_id FROM %s l WHERE l.recipient_id = ?)
207 """.formatted(TABLE_MESSAGE_SEND_LOG_CONTENT
, TABLE_MESSAGE_SEND_LOG
);
208 try (final var connection
= database
.getConnection()) {
209 connection
.setAutoCommit(false);
210 try (final var statement
= connection
.prepareStatement(sql
)) {
211 statement
.setLong(1, sentTimestamp
);
212 statement
.setLong(2, recipientId
.id());
213 statement
.executeUpdate();
216 deleteOrphanedLogContents(connection
);
218 } catch (SQLException e
) {
219 logger
.warn("Failed delete from message send log", e
);
223 public void deleteEntryForRecipient(long sentTimestamp
, RecipientId recipientId
, int deviceId
) {
224 deleteEntriesForRecipient(List
.of(sentTimestamp
), recipientId
, deviceId
);
227 public void deleteEntriesForRecipient(List
<Long
> sentTimestamps
, RecipientId recipientId
, int deviceId
) {
230 WHERE l.content_id IN (SELECT _id FROM %s lc WHERE lc.timestamp = ?) AND l.recipient_id = ? AND l.device_id = ?
231 """.formatted(TABLE_MESSAGE_SEND_LOG
, TABLE_MESSAGE_SEND_LOG_CONTENT
);
232 try (final var connection
= database
.getConnection()) {
233 connection
.setAutoCommit(false);
234 try (final var statement
= connection
.prepareStatement(sql
)) {
235 for (final var sentTimestamp
: sentTimestamps
) {
236 statement
.setLong(1, sentTimestamp
);
237 statement
.setLong(2, recipientId
.id());
238 statement
.setInt(3, deviceId
);
239 statement
.executeUpdate();
243 deleteOrphanedLogContents(connection
);
245 } catch (SQLException e
) {
246 logger
.warn("Failed delete from message send log", e
);
251 public void close() {
252 cleanupThread
.interrupt();
254 cleanupThread
.join();
255 } catch (InterruptedException ignored
) {
259 private RecipientDevices
getRecipientDevices(final SendMessageResult sendMessageResult
) {
260 if (sendMessageResult
.isSuccess() && sendMessageResult
.getSuccess().getContent().isPresent()) {
261 final var recipientId
= recipientResolver
.resolveRecipient(sendMessageResult
.getAddress());
262 return new RecipientDevices(recipientId
, sendMessageResult
.getSuccess().getDevices());
269 final List
<RecipientDevices
> recipientDevices
,
270 final long sentTimestamp
,
271 final SignalServiceProtos
.Content content
,
272 final ContentHint contentHint
,
275 byte[] groupId
= getGroupId(content
);
279 INSERT INTO %s (timestamp, group_id, content, content_hint)
281 """.formatted(TABLE_MESSAGE_SEND_LOG_CONTENT
);
282 try (final var connection
= database
.getConnection()) {
283 connection
.setAutoCommit(false);
284 final long contentId
;
285 try (final var statement
= connection
.prepareStatement(sql
)) {
286 statement
.setLong(1, sentTimestamp
);
287 statement
.setBytes(2, groupId
);
288 statement
.setBytes(3, content
.toByteArray());
289 statement
.setInt(4, contentHint
.getType());
290 statement
.executeUpdate();
291 final var generatedKeys
= statement
.getGeneratedKeys();
292 if (generatedKeys
.next()) {
293 contentId
= generatedKeys
.getLong(1);
298 if (contentId
== -1) {
299 logger
.warn("Failed to insert message send log content");
302 insertRecipientsForExistingContent(contentId
, recipientDevices
, connection
);
306 } catch (SQLException e
) {
307 logger
.warn("Failed to insert into message send log", e
);
312 private byte[] getGroupId(final SignalServiceProtos
.Content content
) {
314 return !content
.hasDataMessage()
316 : content
.getDataMessage().hasGroup()
317 ? content
.getDataMessage().getGroup().getId().toByteArray()
318 : content
.getDataMessage().hasGroupV2()
319 ? GroupUtils
.getGroupIdV2(new GroupMasterKey(content
.getDataMessage()
322 .toByteArray())).serialize()
324 } catch (InvalidInputException e
) {
325 logger
.warn("Failed to parse groupId id from content");
330 private void insertRecipientsForExistingContent(
331 final long contentId
, final List
<RecipientDevices
> recipientDevices
333 try (final var connection
= database
.getConnection()) {
334 connection
.setAutoCommit(false);
335 insertRecipientsForExistingContent(contentId
, recipientDevices
, connection
);
337 } catch (SQLException e
) {
338 logger
.warn("Failed to append recipients to message send log", e
);
342 private void insertRecipientsForExistingContent(
343 final long contentId
, final List
<RecipientDevices
> recipientDevices
, final Connection connection
344 ) throws SQLException
{
346 INSERT INTO %s (recipient_id, device_id, content_id)
348 """.formatted(TABLE_MESSAGE_SEND_LOG
);
349 try (final var statement
= connection
.prepareStatement(sql
)) {
350 for (final var recipientDevice
: recipientDevices
) {
351 for (final var deviceId
: recipientDevice
.deviceIds()) {
352 statement
.setLong(1, recipientDevice
.recipientId().id());
353 statement
.setInt(2, deviceId
);
354 statement
.setLong(3, contentId
);
355 statement
.executeUpdate();
361 private void deleteOutdatedEntries(final Connection connection
) throws SQLException
{
365 """.formatted(TABLE_MESSAGE_SEND_LOG_CONTENT
);
366 try (final var statement
= connection
.prepareStatement(sql
)) {
367 statement
.setLong(1, System
.currentTimeMillis() - LOG_DURATION
.toMillis());
368 final var rowCount
= statement
.executeUpdate();
370 logger
.debug("Removed {} outdated entries from the message send log", rowCount
);
372 logger
.trace("No outdated entries to be removed from message send log.");
377 private void deleteOrphanedLogContents(final Connection connection
) throws SQLException
{
380 WHERE _id NOT IN (SELECT content_id FROM %s)
381 """.formatted(TABLE_MESSAGE_SEND_LOG_CONTENT
, TABLE_MESSAGE_SEND_LOG
);
382 try (final var statement
= connection
.prepareStatement(sql
)) {
383 statement
.executeUpdate();
387 private record RecipientDevices(RecipientId recipientId
, List
<Integer
> deviceIds
) {}