aboutsummaryrefslogtreecommitdiff
path: root/lib/events/encryptedevent.cpp
blob: 3af3d6ff89f7a95d3b6d532b53d4036f67fc65d1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// SPDX-FileCopyrightText: 2019 Alexey Andreyev <aa13q@ya.ru>
// SPDX-License-Identifier: LGPL-2.1-or-later

#include "encryptedevent.h"
#include "roommessageevent.h"
#include "events/eventloader.h"

using namespace Quotient;

EncryptedEvent::EncryptedEvent(const QJsonObject& ciphertext,
                               const QString& senderKey)
    : RoomEvent(typeId(), matrixTypeId(),
                { { AlgorithmKeyL, OlmV1Curve25519AesSha2AlgoKey },
                  { CiphertextKeyL, ciphertext },
                  { SenderKeyKeyL, senderKey } })
{}

EncryptedEvent::EncryptedEvent(QByteArray ciphertext, const QString& senderKey,
                               const QString& deviceId, const QString& sessionId)
    : RoomEvent(typeId(), matrixTypeId(),
                {
                    { AlgorithmKeyL, MegolmV1AesSha2AlgoKey },
                    { CiphertextKeyL, QString(ciphertext) },
                    { DeviceIdKeyL, deviceId },
                    { SenderKeyKeyL, senderKey },
                    { SessionIdKeyL, sessionId },
                })
{}

EncryptedEvent::EncryptedEvent(const QJsonObject& obj)
    : RoomEvent(typeId(), obj)
{
    qCDebug(E2EE) << "Encrypted event from" << senderId();
}

QString EncryptedEvent::algorithm() const
{
    const auto algo = contentPart<QString>(AlgorithmKeyL);
    if (!isSupportedAlgorithm(algo))
        qWarning(MAIN) << "The EncryptedEvent's algorithm" << algo
                       << "is not supported";

    return algo;
}

RoomEventPtr EncryptedEvent::createDecrypted(const QString &decrypted) const
{
    auto eventObject = QJsonDocument::fromJson(decrypted.toUtf8()).object();
    eventObject["event_id"] = id();
    eventObject["sender"] = senderId();
    eventObject["origin_server_ts"] = originTimestamp().toMSecsSinceEpoch();
    if (const auto relatesToJson = contentPart("m.relates_to"_ls); !relatesToJson.isUndefined()) {
        auto content = eventObject["content"].toObject();
        content["m.relates_to"] = relatesToJson.toObject();
        eventObject["content"] = content;
    }
    if (const auto redactsJson = unsignedPart("redacts"_ls); !redactsJson.isUndefined()) {
        auto unsign = eventObject["unsigned"].toObject();
        unsign["redacts"] = redactsJson.toString();
        eventObject["unsigned"] = unsign;
    }
    return loadEvent<RoomEvent>(eventObject);
}

void EncryptedEvent::setRelation(const QJsonObject& relation)
{
    auto content = editJson()["content"_ls].toObject();
    content["m.relates_to"] = relation;
    editJson()["content"] = content;
}