dm3-org / dm3

The dm3 protocol | New standard of web3 messaging | Decentralized ENS-based registry | Secure end-to-end encryption | Easy dApp integration
https://dm3.network
BSD 2-Clause "Simplified" License
73 stars 15 forks source link

Duplication of messages on fetching old messages (pagination) #1070

Closed Bhupesh-mfsi closed 3 weeks ago

Bhupesh-mfsi commented 4 weeks ago

Currently when we fetch old messages of a contact then it returns already existing messages which becomes duplicate. There must be some issue in the logic of the below function in the useMessage hook of frontend

const loadMoreMessages = async (_contactName: string) => {
        const contactName = normalizeEnsName(_contactName);

        const messagesFromContact = messages[contactName] ?? [];
        //For the messageCount we only consider emssages from the MessageSource storage
        const messageCount = messagesFromContact.filter(
            (message) => message.source === MessageSource.Storage,
        ).length;

        //We calculate the offset based on the messageCount
        const offset = Math.floor(messageCount / DEFAULT_MESSAGE_PAGESIZE);

        const messagesFromStorage = await handleMessagesFromStorage(
            setContactsLoading,
            getMessagesFromStorage,
            contactName,
            DEFAULT_MESSAGE_PAGESIZE,
            offset,
        );
        await _addMessages(contactName, messagesFromStorage);
    };

    const _addMessages = async (
        _contactName: string,
        newMessages: MessageModel[],
    ) => {
        const contactName = normalizeEnsName(_contactName);

        newMessages
            //filter duplicates
            .filter((message, index, self) => {
                if (!message.envelop.metadata?.encryptedMessageHash) {
                    return true;
                }
                return (
                    index ===
                    self.findIndex(
                        (m) =>
                            m.envelop.metadata?.encryptedMessageHash ===
                            message.envelop.metadata?.encryptedMessageHash,
                    )
                );
            });

        const withResolvedAliasNames = await resolveAliasNames(newMessages);

        setMessages((prev) => {
            return {
                ...prev,
                [contactName]: [
                    ...(prev[contactName] ?? []),
                    ...withResolvedAliasNames,
                ],
            };
        });

        setContactsLoading((prev) => {
            return prev.filter((contact) => contact !== contactName);
        });
    };

Expected : Only new messages should be added in the message list.