// SPDX-FileCopyrightText: 2026 Matvey Shcherbinin // SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL #include "ChatModel.h" #include "HistoryManager.h" #include "ReactionStore.h" #include "UnreadManager.h" #include #include #include #include #include namespace { // The row kinds the timeline draws beyond a picture: audio is what the music // row plays, video gets the inline player, and anything else stays a file. // Matched on the extension only - over the LAN the two ends share nothing // about a file but the name it was announced under. QString attachmentKindFor(const QString &path) { const QString ext = QFileInfo(path).suffix().toLower(); if (ext == QLatin1String("mp3") || ext == QLatin1String("m4a") || ext == QLatin1String("m4b") || ext == QLatin1String("aac") || ext == QLatin1String("flac") || ext == QLatin1String("ogg") || ext == QLatin1String("oga") || ext == QLatin1String("opus") || ext == QLatin1String("wav") || ext == QLatin1String("wma") || ext == QLatin1String("caf") || ext == QLatin1String("aiff")) return QStringLiteral("audio"); if (ext == QLatin1String("mp4") || ext == QLatin1String("m4v") || ext == QLatin1String("mkv") || ext == QLatin1String("webm") || ext == QLatin1String("avi") || ext == QLatin1String("mov") || ext == QLatin1String("wmv") || ext == QLatin1String("mpg") || ext == QLatin1String("mpeg") || ext == QLatin1String("3gp")) return QStringLiteral("video"); return QString(); } // Telegram sends an outgoing message twice: first under a negative placeholder // id, then under the real server id. Which one arrives first is not guaranteed - // a chat-list update can carry the final message before the new-message update // does. Knowing which id is temporary lets both orders collapse to one row. // The timestamp form is KOutNet's own optimistic row from transports that do // not own the timeline; it is temporary for the same reason. bool isProvisionalId(const QString &id, double ts) { if (id.isEmpty()) return false; if (id.startsWith(QLatin1Char('-'))) return true; return id == QString::number(ts, 'f', 3); } // A duplicate written by an older build is still on disk after the fix: reload() // puts both rows back and the live dedup has nothing left to merge. Clean the // stored log once on load. Two final ids are left alone - that can be somebody // sending the same words twice - but a temporary row with a final twin is the // same message by definition. bool dropStoredProvisionalDuplicates(QVector &rows, const QString &chatId) { // Telegram can publish the same outgoing message through more than one // update, and an older build wrote both rows. Its timestamps are whole // seconds and the text is the same bytes, so that pair is unmistakable. // Other transports keep the stricter rule: only a temporary id with a // final twin is removed, never two real messages that happen to match. const bool telegram = chatId.startsWith(QLatin1String("tg:")); const double window = telegram ? 10.0 : 3.0; bool dropped = false; for (int i = rows.size() - 1; i >= 0; --i) { const MessageEntry row = rows.at(i); if (!row.isOwn || row.isFile || row.isSystem) continue; const bool provisional = isProvisionalId(row.msgId, row.ts); if (!telegram && !provisional) continue; for (int j = 0; j < rows.size(); ++j) { if (j == i) continue; const MessageEntry &other = rows.at(j); if (!other.isOwn || other.isFile || other.isSystem) continue; if (row.text.trimmed() != other.text.trimmed()) continue; if (qAbs(other.ts - row.ts) > window) continue; const bool otherProvisional = isProvisionalId(other.msgId, other.ts); bool keepOther = false; if (telegram) { // Keep the row with the larger numeric id: that is Telegram's // final id, while a negative one is only a placeholder. bool rowOk = false; bool otherOk = false; const qlonglong rowId = row.msgId.toLongLong(&rowOk); const qlonglong otherId = other.msgId.toLongLong(&otherOk); keepOther = otherOk && (!rowOk || otherId > rowId); if (rowOk && otherOk && rowId == otherId) keepOther = j > i; } else { // Of two temporary rows keep the earlier one; a final wins. keepOther = !otherProvisional || j < i; } if (!keepOther) continue; if (chatId.startsWith(QLatin1String("tg:")) && qEnvironmentVariableIsSet("KOUTNET_DEBUG_TG_DUP")) qWarning().nospace() << "TG-CLEAN drop id=" << row.msgId << " ts=" << row.ts << " text=" << row.text.left(30); rows.removeAt(i); dropped = true; break; } } return dropped; } } // namespace ChatModel::ChatModel(QObject *parent) : QAbstractListModel(parent) { } int ChatModel::rowCount(const QModelIndex &parent) const { if (parent.isValid()) return 0; return m_messages.size(); } QVariant ChatModel::data(const QModelIndex &index, int role) const { if (!index.isValid() || index.row() < 0 || index.row() >= m_messages.size()) return {}; const MessageEntry &m = m_messages.at(index.row()); switch (role) { case SenderRole: return m.sender; case SenderIdRole: return m.senderId; case SenderAvatarRole: return m.avatarUrl; case TextRole: return m.text; case FormattedTextRole: return m.formattedText; case IsOwnRole: return m.isOwn; case ColorRole: return m.color; case MsgTypeRole: return m.msgType; case IsSystemRole: return m.isSystem; case IsEditedRole: return m.isEdited; case ReplyToTextRole: return m.replyToText; case ReplyToSenderRole: return m.replyToSender; case ReplyToIdRole: return m.replyToId; case MsgIdRole: return m.msgId; case IsReadRole: return m.isRead; case IsPendingRole: return m.pending; case IsFileRole: return m.isFile; case FilePathRole: return m.filePath; case IsImageRole: return m.isImage; case MediaKindRole: return m.mediaKind; case MediaUrlRole: return m.mediaUrl; case MediaThumbnailUrlRole: return m.mediaThumbnailUrl; case MediaMimeRole: return m.mediaMime; case MediaSizeRole: return QVariant::fromValue(m.mediaSize); case MediaWidthRole: return m.mediaWidth; case MediaHeightRole: return m.mediaHeight; case MediaDurationRole: return m.mediaDurationMs; case ReactionsRole: return m_reactions ? m_reactions->summary(m.chatId.isEmpty() ? QStringLiteral("public") : m.chatId, m.ts) : QVariantList(); case TimeStringRole: return QDateTime::fromSecsSinceEpoch(static_cast(m.ts)).toString(QStringLiteral("HH:mm")); case StampSecsRole: return m.ts; case ShowAuthorRole: return startsRun(index.row()); case ShowDayRole: return startsDay(index.row()); case PollRole: return m.poll; default: return {}; } } bool ChatModel::startsRun(int row) const { const MessageEntry &m = m_messages.at(row); if (m.isSystem) return false; if (row == 0) return true; const MessageEntry &prev = m_messages.at(row - 1); if (prev.isSystem) return true; if (prev.isOwn != m.isOwn || prev.sender != m.sender) return true; if (m.ts - prev.ts > kRunGapSecs) return true; return startsDay(row); } bool ChatModel::startsDay(int row) const { if (row == 0) return true; const QDate today = QDateTime::fromSecsSinceEpoch(static_cast(m_messages.at(row).ts)).date(); const QDate before = QDateTime::fromSecsSinceEpoch(static_cast(m_messages.at(row - 1).ts)).date(); return today != before; } QHash ChatModel::roleNames() const { return { {SenderRole, "sender"}, {SenderIdRole, "senderId"}, {SenderAvatarRole, "senderAvatar"}, {TextRole, "text"}, {FormattedTextRole, "formattedText"}, {IsOwnRole, "isOwn"}, {ColorRole, "color"}, {MsgTypeRole, "msgType"}, {IsSystemRole, "isSystem"}, {IsEditedRole, "isEdited"}, {ReplyToTextRole, "replyToText"}, {ReplyToSenderRole, "replyToSender"}, {ReplyToIdRole, "replyToId"}, {MsgIdRole, "msgId"}, {IsReadRole, "isRead"}, {IsPendingRole, "isPending"}, {ReactionsRole, "reactions"}, {TimeStringRole, "timeString"}, {IsFileRole, "isFile"}, {FilePathRole, "filePath"}, {IsImageRole, "isImage"}, {MediaKindRole, "mediaKind"}, {MediaUrlRole, "mediaUrl"}, {MediaThumbnailUrlRole, "mediaThumbnailUrl"}, {MediaMimeRole, "mediaMime"}, {MediaSizeRole, "mediaSize"}, {MediaWidthRole, "mediaWidth"}, {MediaHeightRole, "mediaHeight"}, {MediaDurationRole, "mediaDuration"}, {StampSecsRole, "stampSecs"}, {ShowAuthorRole, "showAuthor"}, {ShowDayRole, "showDay"}, {PollRole, "poll"}, }; } void ChatModel::setChatId(const QString &id) { if (m_chatId == id) return; m_persistScheduled = false; m_chatId = id; Q_EMIT chatIdChanged(); reload(); Q_EMIT unreadCountChanged(); } QObject *ChatModel::historyManagerObj() const { return m_history; } void ChatModel::setHistoryManagerObj(QObject *obj) { auto *h = qobject_cast(obj); if (m_history == h) return; m_history = h; Q_EMIT historyManagerChanged(); reload(); } QObject *ChatModel::reactionStoreObj() const { return m_reactions; } void ChatModel::setReactionStoreObj(QObject *obj) { auto *r = qobject_cast(obj); if (m_reactions == r) return; if (m_reactions) disconnect(m_reactions, nullptr, this, nullptr); m_reactions = r; if (m_reactions) { connect(m_reactions, &ReactionStore::reactionsChanged, this, [this](const QString &chatId, double ts) { const QString cid = m_chatId.isEmpty() ? QStringLiteral("public") : m_chatId; if (chatId != cid) return; for (int i = 0; i < m_messages.size(); ++i) { if (m_messages.at(i).ts == ts) { refreshRow(i); break; } } }); } Q_EMIT reactionStoreChanged(); } QObject *ChatModel::unreadManagerObj() const { return m_unread; } void ChatModel::setUnreadManagerObj(QObject *obj) { auto *u = qobject_cast(obj); if (m_unread == u) return; if (m_unread) disconnect(m_unread, nullptr, this, nullptr); m_unread = u; if (m_unread) { connect(m_unread, &UnreadManager::unreadChanged, this, [this](const QString &chatId, int) { if (chatId == m_chatId) Q_EMIT unreadCountChanged(); }); } Q_EMIT unreadManagerChanged(); Q_EMIT unreadCountChanged(); } int ChatModel::unreadCount() const { if (!m_unread || m_chatId.isEmpty()) return 0; return m_unread->get(m_chatId); } int ChatModel::firstUnreadRow() const { int remaining = unreadCount(); if (remaining <= 0) return -1; // Own messages and system lines were never counted into the tally, so // they are skipped rather than consumed - the marker would land too late. int row = -1; for (int i = m_messages.size() - 1; i >= 0 && remaining > 0; --i) { const MessageEntry &m = m_messages.at(i); if (m.isOwn || m.isSystem) continue; row = i; --remaining; } return row; } void ChatModel::clearMessages() { m_persistScheduled = false; if (m_messages.isEmpty()) { if (m_history && !m_chatId.isEmpty()) m_history->replaceAll(m_chatId, QVariantList()); markAllRead(); return; } beginResetModel(); m_messages.clear(); endResetModel(); if (m_history && !m_chatId.isEmpty()) m_history->replaceAll(m_chatId, QVariantList()); markAllRead(); } void ChatModel::reload() { m_persistScheduled = false; bool cleaned = false; beginResetModel(); m_messages.clear(); if (m_history && !m_chatId.isEmpty()) { const QVariantList raw = m_history->load(m_chatId); m_messages.reserve(raw.size()); for (const QVariant &v : raw) m_messages.append(MessageEntry::fromJson(QJsonObject::fromVariantMap(v.toMap()))); const int rawCount = m_messages.size(); cleaned = dropStoredProvisionalDuplicates(m_messages, m_chatId); if (m_chatId.startsWith(QLatin1String("tg:")) && qEnvironmentVariableIsSet("KOUTNET_DEBUG_TG_DUP")) qWarning().nospace() << "TG-RELOAD chat=" << m_chatId << " raw=" << rawCount << " kept=" << m_messages.size() << " removed=" << (rawCount - m_messages.size()); // The log on disk was written by appends, and an append trusted // arrival order to be time order. An event that arrived out of order - // a sync replaying a timeline's tail, a room's state notice carrying // the day it happened on - wrote itself at the end of the log, so a // stored history can hold a week-old notice standing under this // morning's message. A stable sort by the times the rows themselves // carry is what straightens such a history; stable, so rows that // share a stamp keep the order they were read in. New rows are filed // where they belong on arrival - see appendEntry(). std::stable_sort(m_messages.begin(), m_messages.end(), [](const MessageEntry &a, const MessageEntry &b) { return a.ts < b.ts; }); } endResetModel(); // Write the cleaned log back so the next start does not repeat the work. if (cleaned) schedulePersist(); } void ChatModel::appendEntry(MessageEntry e, bool persist, bool countUnread) { e.chatId = m_chatId; e.ensureMsgId(); // Last line of defence for Telegram: whichever update wins the race, one // outgoing text is one row. The id checks above cover the usual two paths; // this also catches a replay that arrives with a timestamp that no longer // matches the narrow window, or a text field that differs only in spacing. if (m_chatId.startsWith(QLatin1String("tg:")) && e.isOwn && !e.isSystem && !e.isFile && e.ts > 0.0) { for (int i = m_messages.size() - 1; i >= 0; --i) { const MessageEntry &old = m_messages.at(i); if (old.ts + 10.0 < e.ts) break; if (!old.isOwn || old.isSystem || old.isFile || qAbs(old.ts - e.ts) > 10.0) continue; if (old.text.trimmed() != e.text.trimmed()) continue; // Keep the better id on the row that is already drawn. A real // server id outranks a negative placeholder; two placeholders keep // the first one so a later final update can still claim it. bool incomingOk = false; bool oldOk = false; const qlonglong incomingId = e.msgId.toLongLong(&incomingOk); const qlonglong oldId = old.msgId.toLongLong(&oldOk); const bool incomingFinal = !isProvisionalId(e.msgId, e.ts); const bool oldFinal = !isProvisionalId(old.msgId, old.ts) && !old.pending; if (incomingFinal && (!oldFinal || (incomingOk && oldOk && incomingId > oldId))) { m_messages[i].msgId = e.msgId; m_messages[i].pending = false; Q_EMIT dataChanged(index(i), index(i), {MsgIdRole, IsPendingRole}); } if (persist && m_history && !m_chatId.isEmpty()) schedulePersist(); return; } } // Where the row goes: after every entry whose time is not later than this // one's, so the log stays oldest first even when an event arrives out of // order. A sync replays the tail of a timeline on every reconnect, and a // room's state events come with the days they happened on; appending such // a row blindly would draw last week's notice below this morning's // message. The upper bound keeps rows that share a stamp in arrival order, // which is the order a reader watched them come in. A row with no time at // all keeps the old append, because there is nothing to file it against. int row = m_messages.size(); if (e.ts > 0.0) { int lo = 0; int hi = static_cast(m_messages.size()); while (lo < hi) { const int mid = lo + (hi - lo) / 2; if (m_messages.at(mid).ts <= e.ts) lo = mid + 1; else hi = mid; } row = lo; } beginInsertRows(QModelIndex(), row, row); m_messages.insert(row, e); endInsertRows(); if (persist && m_history && !m_chatId.isEmpty()) schedulePersist(); // Backlog the transport says was already read must still be drawn, but // must not count as new work for the user to do again. if (countUnread && !e.isOwn && !e.isSystem && m_unread && !m_chatId.isEmpty()) m_unread->increment(m_chatId); if (!e.isSystem && !m_chatId.isEmpty()) Q_EMIT messageAdded(m_chatId, e.text, e.isOwn, e.ts); } double ChatModel::sendMessage(const QString &text, const QString &replyToText, const QString &replyToSender, const QString &replyToId) { if (text.trimmed().isEmpty()) return 0.0; MessageEntry e; e.text = text; e.ts = QDateTime::currentMSecsSinceEpoch() / 1000.0; e.isOwn = true; e.pending = true; e.replyToText = replyToText; e.replyToSender = replyToSender; e.replyToId = replyToId; appendEntry(e, true); return e.ts; } int ChatModel::rowForMsgId(const QString &msgId) const { if (msgId.isEmpty()) return -1; for (int i = 0; i < m_messages.size(); ++i) { if (m_messages.at(i).msgId == msgId) return i; } return -1; } double ChatModel::sendFile(const QString &filePath, bool isImage) { MessageEntry e; e.text = filePath.section(QLatin1Char('/'), -1); e.ts = QDateTime::currentMSecsSinceEpoch() / 1000.0; e.isOwn = true; e.pending = true; e.isFile = true; e.filePath = filePath; e.isImage = isImage; // The kind is what decides the row shape, so a song sent over the LAN // gets the same music row one from a server gets, and a document keeps // the file row it always had. e.mediaKind = attachmentKindFor(filePath); appendEntry(e, true); return e.ts; } void ChatModel::markSent(double stamp) { const int row = rowForStamp(stamp); if (row < 0 || !m_messages.at(row).pending) return; m_messages[row].pending = false; const QModelIndex idx = index(row); Q_EMIT dataChanged(idx, idx, {IsPendingRole}); } void ChatModel::receiveMessage(const QString &text, const QString &sender) { MessageEntry e; e.text = text; e.sender = sender; e.ts = QDateTime::currentMSecsSinceEpoch() / 1000.0; e.isOwn = false; appendEntry(e, true); } void ChatModel::receiveFile(const QString &filePath, bool isImage, const QString &sender) { MessageEntry e; e.text = filePath.section(QLatin1Char('/'), -1); e.sender = sender; e.ts = QDateTime::currentMSecsSinceEpoch() / 1000.0; e.isOwn = false; e.isFile = true; e.filePath = filePath; e.isImage = isImage; e.mediaKind = attachmentKindFor(filePath); appendEntry(e, true); } void ChatModel::setPeerAvatar(const QString &avatarSource) { if (m_messages.isEmpty()) return; int first = -1; int last = -1; for (int i = 0; i < m_messages.size(); ++i) { if (m_messages[i].isOwn) continue; if (m_messages[i].avatarUrl == avatarSource) continue; m_messages[i].avatarUrl = avatarSource; if (first < 0) first = i; last = i; } if (first >= 0) Q_EMIT dataChanged(index(first), index(last), {SenderAvatarRole}); } void ChatModel::appendSystemMessage(const QString &text) { MessageEntry e; e.text = text; e.ts = QDateTime::currentMSecsSinceEpoch() / 1000.0; e.isSystem = true; appendEntry(e, false); } bool ChatModel::ingestRemoteMessage(const QString &remoteId, const QString &text, const QString &sender, bool isOwn, double ts, bool isSystem, const QString &senderAvatar, const QString &formattedText, const QString &senderId, bool alreadyRead) { // no id means no duplicate check, and without one this is receiveMessage(). if (isOwn && m_chatId.startsWith(QLatin1String("tg:")) && qEnvironmentVariableIsSet("KOUTNET_DEBUG_TG_DUP")) qWarning().nospace() << "TG-OWN ingest id=" << remoteId << " ts=" << ts << " text=" << text.left(30); if (remoteId.isEmpty() || rowForMsgId(remoteId) >= 0) return false; // An outgoing Telegram message can arrive in either order: the negative // placeholder from updateNewMessage first, or the final id carried by a // chat-list update first. Both orders are one message. Incoming mail is // never folded: two identical messages from somebody else are real. if (isOwn) { const bool incomingProvisional = isProvisionalId(remoteId, ts); for (int i = m_messages.size() - 1; i >= 0; --i) { const MessageEntry &old = m_messages.at(i); if (!old.isOwn || old.text != text) continue; if (qAbs(old.ts - ts) <= 3.0) { const bool oldProvisional = isProvisionalId(old.msgId, old.ts) || old.pending; // The final row was already on screen and this is its late // placeholder. There is nothing to update on that row. if (incomingProvisional && !oldProvisional) return false; // The placeholder came first: give it the real id in place. if (!incomingProvisional && oldProvisional) { m_messages[i].msgId = remoteId; m_messages[i].pending = false; Q_EMIT dataChanged(index(i), index(i), {MsgIdRole, IsPendingRole}); return false; } // Two placeholders for one send keep the row already drawn. if (incomingProvisional && oldProvisional) return false; } if (old.ts + 3.0 < ts) break; } } MessageEntry e; e.msgId = remoteId; e.text = text; e.formattedText = formattedText; e.sender = sender; e.senderId = senderId; e.avatarUrl = senderAvatar; e.ts = ts > 0.0 ? ts : QDateTime::currentMSecsSinceEpoch() / 1000.0; e.isOwn = isOwn; e.isSystem = isSystem; e.msgType = QStringLiteral("private"); // Opt-in trace for the one bug a test cannot see: the exact ids Telegram // sends while the user is watching a live conversation. if (isOwn && m_chatId.startsWith(QLatin1String("tg:")) && qEnvironmentVariableIsSet("KOUTNET_DEBUG_TG_DUP")) qWarning().nospace() << "TG-OWN text id=" << remoteId << " ts=" << ts << " text=" << text.left(30); // A row of ours the server echoed is at most on the server - it is not read. // The receipt is what turns the single tick into a double one; marking it // here would be the same lie the LAN path once told about a message nobody // had on screen. Incoming backlog the transport calls already read is the // opposite case: it is on screen elsewhere, so show it without a badge. e.isRead = alreadyRead && !isOwn; // Persisted like any other, which is what makes the duplicate check survive // a restart: reload() puts these ids back before the first sync arrives. const int before = rowCount(); appendEntry(e, true, !alreadyRead); const bool added = rowCount() > before; if (isOwn && m_chatId.startsWith(QLatin1String("tg:")) && qEnvironmentVariableIsSet("KOUTNET_DEBUG_TG_DUP")) qWarning().nospace() << "TG-OWN text result added=" << added << " rows=" << rowCount(); // appendEntry may have folded this into a row that was already drawn; // callers treat false as "no new row, so no notification". return added; } bool ChatModel::ingestRemoteAttachment(const QString &remoteId, const QVariantMap &media, const QString &sender, bool isOwn, double ts, const QString &senderAvatar, const QString &senderId, bool alreadyRead) { if (isOwn && m_chatId.startsWith(QLatin1String("tg:")) && qEnvironmentVariableIsSet("KOUTNET_DEBUG_TG_DUP")) qWarning().nospace() << "TG-OWN ingest media id=" << remoteId << " ts=" << ts << " name=" << media.value(QStringLiteral("name")).toString().left(30); if (remoteId.isEmpty() || rowForMsgId(remoteId) >= 0) return false; const QString remoteName = media.value(QStringLiteral("name")).toString(); const QString remoteKind = media.value(QStringLiteral("kind")).toString(); if (isOwn) { // Same two update orders as text: the placeholder can be the first row // or the last one. Documents match by file name, pictures by kind, // because a Telegram photo carries no name to compare. const bool incomingProvisional = isProvisionalId(remoteId, ts); for (int i = m_messages.size() - 1; i >= 0; --i) { const MessageEntry &old = m_messages.at(i); const bool sameName = !remoteName.isEmpty() && old.text == remoteName; const bool samePicture = remoteName.isEmpty() && (remoteKind == QStringLiteral("image") || remoteKind == QStringLiteral("sticker")) && old.isImage; if (!old.isOwn || !old.isFile || (!sameName && !samePicture)) continue; if (qAbs(old.ts - ts) > 10.0) continue; const bool oldProvisional = isProvisionalId(old.msgId, old.ts) || old.pending; if (incomingProvisional && !oldProvisional) return false; if (incomingProvisional && oldProvisional) return false; if (oldProvisional) { MessageEntry merged = old; merged.msgId = remoteId; merged.pending = false; merged.mediaKind = remoteKind; merged.isImage = merged.mediaKind == QStringLiteral("image") || merged.mediaKind == QStringLiteral("sticker") || old.isImage; merged.mediaUrl = media.value(QStringLiteral("url")).toString(); merged.mediaThumbnailUrl = media.value(QStringLiteral("thumbnailUrl")).toString(); merged.mediaMime = media.value(QStringLiteral("mime")).toString(); merged.mediaSize = media.value(QStringLiteral("size")).toLongLong(); merged.mediaWidth = media.value(QStringLiteral("width")).toInt(); merged.mediaHeight = media.value(QStringLiteral("height")).toInt(); merged.mediaDurationMs = media.value(QStringLiteral("duration")).toInt(); m_messages[i] = merged; Q_EMIT dataChanged(index(i), index(i), {MsgIdRole, IsPendingRole, MediaKindRole, MediaUrlRole, MediaThumbnailUrlRole, MediaMimeRole, MediaSizeRole, MediaWidthRole, MediaHeightRole, MediaDurationRole}); persistAll(); return false; } } } MessageEntry e; e.msgId = remoteId; e.sender = sender; e.senderId = senderId; e.avatarUrl = senderAvatar; e.ts = ts > 0.0 ? ts : QDateTime::currentMSecsSinceEpoch() / 1000.0; e.isOwn = isOwn; e.msgType = QStringLiteral("private"); if (isOwn && m_chatId.startsWith(QLatin1String("tg:")) && qEnvironmentVariableIsSet("KOUTNET_DEBUG_TG_DUP")) qWarning().nospace() << "TG-OWN media id=" << remoteId << " ts=" << ts << " name=" << remoteName; // the same honesty as a text row: echoed is not read, but transport // backlog that was read elsewhere should not ask to be read again. e.isRead = alreadyRead && !isOwn; // isFile as well as mediaKind: the timeline's own rules about attachments - // no editing, no emoji-only sizing, a name instead of a body - are written // against isFile, and a Matrix attachment obeys every one of them. e.isFile = true; e.mediaKind = media.value(QStringLiteral("kind")).toString(); e.isImage = e.mediaKind == QStringLiteral("image") || e.mediaKind == QStringLiteral("sticker"); e.mediaUrl = media.value(QStringLiteral("url")).toString(); e.mediaThumbnailUrl = media.value(QStringLiteral("thumbnailUrl")).toString(); e.mediaMime = media.value(QStringLiteral("mime")).toString(); e.mediaSize = media.value(QStringLiteral("size")).toLongLong(); e.mediaWidth = media.value(QStringLiteral("width")).toInt(); e.mediaHeight = media.value(QStringLiteral("height")).toInt(); e.mediaDurationMs = media.value(QStringLiteral("duration")).toInt(); // the label, in the same field a LAN attachment puts its file name in. e.text = media.value(QStringLiteral("name")).toString(); const int before = rowCount(); appendEntry(e, true, !alreadyRead); const bool added = rowCount() > before; if (isOwn && m_chatId.startsWith(QLatin1String("tg:")) && qEnvironmentVariableIsSet("KOUTNET_DEBUG_TG_DUP")) qWarning().nospace() << "TG-OWN media result added=" << added << " rows=" << rowCount(); // appendEntry may have folded this into a row that was already drawn; // callers treat false as "no new row, so no notification". return added; } bool ChatModel::ingestRemotePoll(const QString &remoteId, const QString &question, const QVariantList &answers, bool disclosed, const QString &sender, bool isOwn, double ts, const QString &senderAvatar, const QString &senderId) { if (remoteId.isEmpty() || rowForMsgId(remoteId) >= 0) return false; MessageEntry e; e.msgId = remoteId; e.sender = sender; e.senderId = senderId; e.avatarUrl = senderAvatar; e.ts = ts > 0.0 ? ts : QDateTime::currentMSecsSinceEpoch() / 1000.0; e.isOwn = isOwn; e.msgType = QStringLiteral("private"); e.isRead = false; e.text = question; // the question and options ride as structured data the window renders. Votes // are tallied live as m.poll.response events arrive, so the counts start bare. QVariantMap poll; poll.insert(QStringLiteral("question"), question); poll.insert(QStringLiteral("answers"), answers); poll.insert(QStringLiteral("disclosed"), disclosed); QVariantList counts; counts.reserve(answers.size()); for (int i = 0; i < answers.size(); ++i) counts.append(0); poll.insert(QStringLiteral("counts"), counts); poll.insert(QStringLiteral("totalVotes"), 0); poll.insert(QStringLiteral("myVotes"), QVariantList()); // voterId -> chosen answerId, so a voter counts once and can only move their // vote; without it repeated clicks would inflate the tally (and the server // aggregates by voter, not by event, so our local count must too). poll.insert(QStringLiteral("voters"), QVariantMap()); e.poll = poll; appendEntry(e, true); // Replay votes that arrived before this poll start event. const auto it = m_pendingPollVotes.find(remoteId); if (it != m_pendingPollVotes.end()) { for (const auto &vote : std::as_const(*it)) applyPollResponse(remoteId, vote.answerId, vote.voterId, vote.isOwn); m_pendingPollVotes.erase(it); } return true; } bool ChatModel::applyPollResponse(const QString &pollStartId, const QString &answerId, const QString &voterId, bool isOwn) { const int row = rowForMsgId(pollStartId); if (row < 0 || answerId.isEmpty()) { // Matrix may deliver a response before the start event (different timelines, // or the start was not yet in our timeline). Stash it so ingestRemotePoll can // replay it once the poll appears. if (row < 0 && !answerId.isEmpty()) m_pendingPollVotes[pollStartId].append({answerId, voterId, isOwn}); return false; } MessageEntry &m = m_messages[row]; if (!m.poll.contains(QStringLiteral("answers"))) return false; QVariantMap poll = m.poll; QVariantList answers = poll.value(QStringLiteral("answers")).toList(); QVariantList counts = poll.value(QStringLiteral("counts")).toList(); int total = poll.value(QStringLiteral("totalVotes"), 0).toInt(); QVariantList myVotes = poll.value(QStringLiteral("myVotes")).toList(); QVariantMap voters = poll.value(QStringLiteral("voters")).toMap(); // index of the newly chosen answer int answerIndex = -1; for (int i = 0; i < answers.size(); ++i) { if (answers.at(i).toMap().value(QStringLiteral("id")).toString() == answerId) { answerIndex = i; break; } } if (answerIndex < 0) return false; // A voter may change their vote but must count once. Track each voter's current // choice and move the tally instead of stacking clicks - a re-vote or a duplicate // server echo for the same option changes nothing, and switching options shifts // the count rather than adding to it. const QString prev = voters.value(voterId).toString(); if (!prev.isEmpty() && prev == answerId) return false; if (!prev.isEmpty()) { int prevIndex = -1; for (int i = 0; i < answers.size(); ++i) { if (answers.at(i).toMap().value(QStringLiteral("id")).toString() == prev) { prevIndex = i; break; } } if (prevIndex >= 0) { const int before = counts.value(prevIndex, 0).toInt(); counts[prevIndex] = qMax(0, before - 1); } total = qMax(0, total - 1); if (isOwn) { const int pos = myVotes.indexOf(prev); if (pos >= 0) myVotes.removeAt(pos); } } const int before = counts.value(answerIndex, 0).toInt(); counts[answerIndex] = before + 1; total += 1; voters.insert(voterId, answerId); poll.insert(QStringLiteral("counts"), counts); poll.insert(QStringLiteral("totalVotes"), total); poll.insert(QStringLiteral("voters"), voters); if (isOwn && !myVotes.contains(answerId)) myVotes.append(answerId); poll.insert(QStringLiteral("myVotes"), myVotes); m.poll = poll; const QModelIndex idx = index(row); Q_EMIT dataChanged(idx, idx, {PollRole}); return true; } bool ChatModel::applyRemoteEdit(const QString &remoteId, const QString &newText, bool markEdited, const QString &formattedText) { const int row = rowForMsgId(remoteId); if (row < 0 || (newText.isEmpty() && formattedText.isEmpty())) return false; MessageEntry &m = m_messages[row]; if (m.text == newText && m.formattedText == formattedText) return false; m.text = newText; m.formattedText = formattedText; if (markEdited) m.isEdited = true; // A revealed message stops being a system notice: it is an ordinary message // that could not be read until now, and leaving it styled as a notice would // keep it looking like something the room said rather than something a // person wrote. if (!markEdited) m.isSystem = false; const QModelIndex idx = index(row); Q_EMIT dataChanged(idx, idx, {TextRole, FormattedTextRole, IsEditedRole, IsSystemRole}); persistAll(); return true; } bool ChatModel::updateRemoteAttachment(const QString &remoteId, const QVariantMap &media) { const int row = rowForMsgId(remoteId); if (row < 0) return false; MessageEntry &m = m_messages[row]; const QString kind = media.value(QStringLiteral("kind")).toString(); if (!kind.isEmpty()) m.mediaKind = kind; if (media.contains(QStringLiteral("url"))) m.mediaUrl = media.value(QStringLiteral("url")).toString(); if (media.contains(QStringLiteral("thumbnail"))) m.mediaThumbnailUrl = media.value(QStringLiteral("thumbnail")).toString(); if (media.contains(QStringLiteral("name"))) m.filePath = media.value(QStringLiteral("name")).toString(); if (media.contains(QStringLiteral("mime"))) m.mediaMime = media.value(QStringLiteral("mime")).toString(); if (media.contains(QStringLiteral("size"))) m.mediaSize = media.value(QStringLiteral("size")).toLongLong(); if (media.contains(QStringLiteral("width"))) m.mediaWidth = media.value(QStringLiteral("width")).toInt(); if (media.contains(QStringLiteral("height"))) m.mediaHeight = media.value(QStringLiteral("height")).toInt(); if (media.contains(QStringLiteral("duration"))) m.mediaDurationMs = media.value(QStringLiteral("duration")).toInt(); if (media.contains(QStringLiteral("caption"))) { const QString caption = media.value(QStringLiteral("caption")).toString(); if (!caption.isEmpty()) m.text = caption; } m.isFile = !m.mediaKind.isEmpty() || !m.filePath.isEmpty(); m.isImage = (m.mediaKind == QLatin1String("image")); const QModelIndex idx = index(row); Q_EMIT dataChanged(idx, idx, {TextRole, IsFileRole, FilePathRole, IsImageRole, MediaKindRole, MediaUrlRole, MediaThumbnailUrlRole, MediaMimeRole, MediaSizeRole, MediaWidthRole, MediaHeightRole, MediaDurationRole}); persistAll(); return true; } void ChatModel::toggleReaction(int row, const QString &emoji, const QString &username) { if (row < 0 || row >= m_messages.size() || !m_reactions) return; const MessageEntry &m = m_messages.at(row); const bool added = m_reactions->toggle(m.chatId.isEmpty() ? QStringLiteral("public") : m.chatId, m.ts, emoji, username); // Pass the msgId (opaque identifier) rather than the stamp: a double is // lossy and two events can share a millisecond. Q_EMIT reactionToggledLocally(m.msgId, emoji, added); } void ChatModel::markOwnMessagesRead() { bool any = false; for (int i = 0; i < m_messages.size(); ++i) { if (m_messages[i].isOwn && !m_messages[i].isRead) { m_messages[i].isRead = true; m_messages[i].pending = false; any = true; const QModelIndex idx = index(i); Q_EMIT dataChanged(idx, idx, {IsReadRole, IsPendingRole}); } } if (!any) return; // Persist the read flags. This loop used to be a no-op because nothing could // rewrite a stored entry, so receipts were lost on the next reload. persistAll(); } double ChatModel::lastMessageStamp() const { return m_messages.isEmpty() ? 0.0 : m_messages.constLast().ts; } void ChatModel::markOwnMessagesReadUpTo(double upToTs) { if (upToTs <= 0.0) { markOwnMessagesRead(); return; } bool any = false; for (int i = 0; i < m_messages.size(); ++i) { if (!m_messages[i].isOwn || m_messages[i].isRead) continue; // The same tolerance rowForStamp() compares with: the stamp crossed the // wire as a JSON number, so equality is three decimal places, not bits. if (m_messages[i].ts > upToTs + 0.0005) continue; m_messages[i].isRead = true; m_messages[i].pending = false; any = true; const QModelIndex idx = index(i); Q_EMIT dataChanged(idx, idx, {IsReadRole, IsPendingRole}); } if (any) persistAll(); } void ChatModel::markOwnMessagesReadUpToById(double maxMessageId) { if (maxMessageId <= 0.0) return; const auto limit = static_cast(maxMessageId); bool any = false; for (int i = 0; i < m_messages.size(); ++i) { MessageEntry &m = m_messages[i]; if (!m.isOwn || m.msgId.isEmpty()) continue; bool ok = false; const qlonglong id = m.msgId.toLongLong(&ok); if (!ok) continue; const bool read = id <= limit; if (m.isRead == read) continue; m.isRead = read; m.pending = false; any = true; const QModelIndex idx = index(i); Q_EMIT dataChanged(idx, idx, {IsReadRole, IsPendingRole}); } if (any) persistAll(); } void ChatModel::persistAll() { m_persistScheduled = false; if (!m_history || m_chatId.isEmpty()) return; QVariantList persisted; persisted.reserve(m_messages.size()); for (int i = 0; i < m_messages.size(); ++i) { if (!m_messages.at(i).isSystem) persisted.append(m_messages.at(i).toVariantMap()); } m_history->replaceAll(m_chatId, persisted); } void ChatModel::schedulePersist() { if (m_persistScheduled || !m_history || m_chatId.isEmpty()) return; m_persistScheduled = true; QTimer::singleShot(0, this, [this]() { if (!m_persistScheduled) return; persistAll(); }); } double ChatModel::stampForRow(int row) const { if (row < 0 || row >= m_messages.size()) return 0.0; return m_messages.at(row).ts; } QString ChatModel::msgIdForRow(int row) const { if (row < 0 || row >= m_messages.size()) return {}; return m_messages.at(row).msgId; } QString ChatModel::oldestMessageId() const { qint64 best = 0; bool have = false; for (const MessageEntry &m : m_messages) { bool ok = false; const qint64 id = m.msgId.toLongLong(&ok); if (!ok || id <= 0) continue; if (!have || id < best) { best = id; have = true; } } return have ? QString::number(best) : QString(); } int ChatModel::rowForStamp(double ts) const { for (int i = 0; i < m_messages.size(); ++i) { // Tolerance, not equality: the stamp travels as a JSON number and // ensureMsgId() treats three decimal places as a message identity. if (qAbs(m_messages.at(i).ts - ts) < 0.0005) return i; } return -1; } bool ChatModel::editMessage(int row, const QString &newText) { if (row < 0 || row >= m_messages.size()) return false; MessageEntry &m = m_messages[row]; if (m.isSystem || m.isFile) return false; const QString trimmed = newText.trimmed(); if (trimmed.isEmpty() || trimmed == m.text) return false; m.text = trimmed; m.formattedText.clear(); m.isEdited = true; const QModelIndex idx = index(row); Q_EMIT dataChanged(idx, idx, {TextRole, FormattedTextRole, IsEditedRole}); persistAll(); return true; } bool ChatModel::deleteMessage(int row) { if (row < 0 || row >= m_messages.size()) return false; if (m_messages.at(row).isSystem) return false; beginRemoveRows(QModelIndex(), row, row); m_messages.remove(row); endRemoveRows(); // Run and day headers describe the row before, so the row that moved up may // need one. if (row < m_messages.size()) { const QModelIndex idx = index(row); Q_EMIT dataChanged(idx, idx, {ShowAuthorRole, ShowDayRole}); } persistAll(); return true; } void ChatModel::markAllRead() { if (m_unread && !m_chatId.isEmpty()) m_unread->markRead(m_chatId); } void ChatModel::refreshRow(int row) { const QModelIndex idx = index(row); Q_EMIT dataChanged(idx, idx, {ReactionsRole}); }