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
@@ -133,7 +133,7 @@ public sealed class MaxBridgeSyncService(
update.LastMessageIsOutgoing != true &&
update.Messages.Count == 0 &&
HasListClockTime(update.LastMessageTimeText);
var lastKnownOutgoingMessages = !shouldLoadLastKnownMessage
var lastKnownOutgoingCandidates = !shouldLoadLastKnownMessage
? []
: await db.Messages
.AsNoTracking()
@@ -142,9 +142,11 @@ public sealed class MaxBridgeSyncService(
x.ChatId == chat.Id &&
x.DeletedAt == null &&
x.Direction == MessageDirection.Outgoing)
.OrderByDescending(x => x.SentAt)
.Take(5)
.ToListAsync(cancellationToken);
var lastKnownOutgoingMessages = lastKnownOutgoingCandidates
.OrderByDescending(x => x.SentAt)
.Take(5)
.ToList();
var lastKnownMessage = lastKnownOutgoingMessages
.Select(x => new LastKnownMessageSnapshot(
x.Direction,
@@ -605,6 +607,17 @@ public sealed class MaxBridgeSyncService(
foreach (var incomingAttachment in incomingAttachments)
{
if (TryMergeOutgoingRemoteEchoIntoLocalAttachment(
message,
incoming,
knownAttachments,
incomingAttachment,
out var echoChanged))
{
changed |= echoChanged;
continue;
}
if (HasAttachment(knownAttachments, incomingAttachment))
{
continue;
@@ -621,6 +634,54 @@ public sealed class MaxBridgeSyncService(
return new MessageMergeResult(changed, addedAttachments);
}
private static bool TryMergeOutgoingRemoteEchoIntoLocalAttachment(
Message message,
MaxMessageUpdate incoming,
IEnumerable<MessageAttachment> attachments,
MaxAttachmentUpdate incomingAttachment,
out bool changed)
{
changed = false;
if (message.Direction != MessageDirection.Outgoing || !incoming.IsOutgoing)
{
return false;
}
if (string.IsNullOrWhiteSpace(incomingAttachment.ExternalId) &&
string.IsNullOrWhiteSpace(incomingAttachment.RemoteUrl))
{
return false;
}
var kind = ResolveKind(incomingAttachment) ?? AttachmentKind.File;
var localUpload = attachments.FirstOrDefault(attachment =>
attachment.SortOrder == incomingAttachment.SortOrder &&
attachment.Kind == kind &&
string.IsNullOrWhiteSpace(attachment.ExternalId) &&
string.IsNullOrWhiteSpace(attachment.RemoteUrl));
if (localUpload is null)
{
return false;
}
if (!string.IsNullOrWhiteSpace(incomingAttachment.ExternalId) &&
!string.Equals(localUpload.ExternalId, incomingAttachment.ExternalId, StringComparison.Ordinal))
{
localUpload.ExternalId = incomingAttachment.ExternalId;
changed = true;
}
if (!string.IsNullOrWhiteSpace(incomingAttachment.RemoteUrl) &&
!string.Equals(localUpload.RemoteUrl, incomingAttachment.RemoteUrl, StringComparison.Ordinal))
{
localUpload.RemoteUrl = incomingAttachment.RemoteUrl;
changed = true;
}
return true;
}
private static IReadOnlyList<MaxAttachmentUpdate> DistinctAttachments(IReadOnlyList<MaxAttachmentUpdate> attachments)
{
if (attachments.Count <= 1)