Merge outgoing photo echo attachments

This commit is contained in:
sevenhill
2026-07-05 08:58:38 +03:00
parent b518f22a09
commit 5d33320e3d
4 changed files with 355 additions and 3 deletions
@@ -51,6 +51,66 @@ public static class QMaxDatabaseCleanup
await db.Database.ExecuteSqlRawAsync("DROP TABLE IF EXISTS temp.LegacyWebFileMessageIds;");
}
public static async Task MergeOutgoingRemoteAttachmentEchoesAsync(QMaxDbContext db)
{
var connection = db.Database.GetDbConnection();
if (connection.State != System.Data.ConnectionState.Open)
{
await connection.OpenAsync();
}
await db.Database.ExecuteSqlRawAsync("DROP TABLE IF EXISTS temp.OutgoingAttachmentEchoMerges;");
await db.Database.ExecuteSqlRawAsync("""
CREATE TEMP TABLE OutgoingAttachmentEchoMerges (
LocalId TEXT NOT NULL PRIMARY KEY,
RemoteId TEXT NOT NULL,
ExternalId TEXT NULL,
RemoteUrl TEXT NULL
);
""");
await db.Database.ExecuteSqlRawAsync("""
INSERT OR IGNORE INTO OutgoingAttachmentEchoMerges (LocalId, RemoteId, ExternalId, RemoteUrl)
SELECT localAttachment.Id,
remoteAttachment.Id,
remoteAttachment.ExternalId,
remoteAttachment.RemoteUrl
FROM Messages AS message
INNER JOIN MessageAttachments AS localAttachment ON localAttachment.MessageId = message.Id
INNER JOIN MessageAttachments AS remoteAttachment ON remoteAttachment.MessageId = message.Id
WHERE message.Direction = 'Outgoing'
AND localAttachment.Id <> remoteAttachment.Id
AND localAttachment.SortOrder = remoteAttachment.SortOrder
AND localAttachment.Kind = remoteAttachment.Kind
AND (localAttachment.ExternalId IS NULL OR trim(localAttachment.ExternalId) = '')
AND (localAttachment.RemoteUrl IS NULL OR trim(localAttachment.RemoteUrl) = '')
AND localAttachment.StorageFileName NOT LIKE 'remote-%'
AND (
(remoteAttachment.ExternalId IS NOT NULL AND trim(remoteAttachment.ExternalId) <> '') OR
(remoteAttachment.RemoteUrl IS NOT NULL AND trim(remoteAttachment.RemoteUrl) <> '') OR
remoteAttachment.StorageFileName LIKE 'remote-%'
);
""");
await db.Database.ExecuteSqlRawAsync("""
DELETE FROM MessageAttachments
WHERE Id IN (SELECT RemoteId FROM OutgoingAttachmentEchoMerges);
""");
await db.Database.ExecuteSqlRawAsync("""
UPDATE MessageAttachments
SET ExternalId = COALESCE(NULLIF(ExternalId, ''), (
SELECT ExternalId
FROM OutgoingAttachmentEchoMerges
WHERE LocalId = MessageAttachments.Id
)),
RemoteUrl = COALESCE(NULLIF(RemoteUrl, ''), (
SELECT RemoteUrl
FROM OutgoingAttachmentEchoMerges
WHERE LocalId = MessageAttachments.Id
))
WHERE Id IN (SELECT LocalId FROM OutgoingAttachmentEchoMerges);
""");
await db.Database.ExecuteSqlRawAsync("DROP TABLE IF EXISTS temp.OutgoingAttachmentEchoMerges;");
}
public static async Task ClearUnreadCountsForLatestOutgoingChatsAsync(QMaxDbContext db)
{
var unreadChats = await db.Chats
@@ -90,4 +150,5 @@ public static class QMaxDatabaseCleanup
await db.SaveChangesAsync();
}
}
}