summaryrefslogtreecommitdiffstats
path: root/src/Cache.cc
blob: c96ec37d63b743de549a183e2a9d3b6840c58bca (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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
/*
 * nheko Copyright (C) 2017  Konstantinos Sideris <siderisk@auth.gr>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <stdexcept>

#include <QDebug>
#include <QDir>
#include <QFile>
#include <QStandardPaths>

#include "Cache.h"
#include "MemberEventContent.h"

namespace events = matrix::events;

static const lmdb::val NEXT_BATCH_KEY("next_batch");
static const lmdb::val transactionID("transaction_id");

Cache::Cache(const QString &userId)
  : env_{ nullptr }
  , stateDb_{ 0 }
  , roomDb_{ 0 }
  , isMounted_{ false }
  , userId_{ userId }
{
}

void
Cache::setup()
{
        qDebug() << "Setting up cache";

        auto statePath = QString("%1/%2/state")
                           .arg(QStandardPaths::writableLocation(QStandardPaths::CacheLocation))
                           .arg(QString::fromUtf8(userId_.toUtf8().toHex()));

        cacheDirectory_ = QString("%1/%2")
                            .arg(QStandardPaths::writableLocation(QStandardPaths::CacheLocation))
                            .arg(QString::fromUtf8(userId_.toUtf8().toHex()));

        bool isInitial = !QFile::exists(statePath);

        env_ = lmdb::env::create();
        env_.set_mapsize(128UL * 1024UL * 1024UL); /* 128 MB */
        env_.set_max_dbs(1024UL);

        if (isInitial) {
                qDebug() << "First time initializing LMDB";

                if (!QDir().mkpath(statePath)) {
                        throw std::runtime_error(
                          ("Unable to create state directory:" + statePath).toStdString().c_str());
                }
        }

        try {
                env_.open(statePath.toStdString().c_str());
        } catch (const lmdb::error &e) {
                if (e.code() != MDB_VERSION_MISMATCH && e.code() != MDB_INVALID) {
                        throw std::runtime_error("LMDB initialization failed" +
                                                 std::string(e.what()));
                }

                qWarning() << "Resetting cache due to LMDB version mismatch:" << e.what();

                QDir stateDir(statePath);

                for (const auto &file : stateDir.entryList(QDir::NoDotAndDotDot)) {
                        if (!stateDir.remove(file))
                                throw std::runtime_error(
                                  ("Unable to delete file " + file).toStdString().c_str());
                }

                env_.open(statePath.toStdString().c_str());
        }

        auto txn = lmdb::txn::begin(env_);
        stateDb_ = lmdb::dbi::open(txn, "state", MDB_CREATE);
        roomDb_  = lmdb::dbi::open(txn, "rooms", MDB_CREATE);

        txn.commit();

        isMounted_ = true;
}

void
Cache::setState(const QString &nextBatchToken, const QMap<QString, RoomState> &states)
{
        if (!isMounted_)
                return;

        auto txn = lmdb::txn::begin(env_);

        setNextBatchToken(txn, nextBatchToken);

        for (auto it = states.constBegin(); it != states.constEnd(); it++)
                insertRoomState(txn, it.key(), it.value());

        txn.commit();
}

void
Cache::insertRoomState(lmdb::txn &txn, const QString &roomid, const RoomState &state)
{
        auto stateEvents = QJsonDocument(state.serialize()).toBinaryData();
        auto id          = roomid.toUtf8();

        lmdb::dbi_put(txn,
                      roomDb_,
                      lmdb::val(id.data(), id.size()),
                      lmdb::val(stateEvents.data(), stateEvents.size()));

        for (const auto &membership : state.memberships) {
                lmdb::dbi membersDb =
                  lmdb::dbi::open(txn, roomid.toStdString().c_str(), MDB_CREATE);

                // The user_id this membership event relates to, is used
                // as the index on the membership database.
                auto key         = membership.stateKey().toUtf8();
                auto memberEvent = QJsonDocument(membership.serialize()).toBinaryData();

                switch (membership.content().membershipState()) {
                // We add or update (e.g invite -> join) a new user to the membership
                // list.
                case events::Membership::Invite:
                case events::Membership::Join: {
                        lmdb::dbi_put(txn,
                                      membersDb,
                                      lmdb::val(key.data(), key.size()),
                                      lmdb::val(memberEvent.data(), memberEvent.size()));
                        break;
                }
                // We remove the user from the membership list.
                case events::Membership::Leave:
                case events::Membership::Ban: {
                        lmdb::dbi_del(txn,
                                      membersDb,
                                      lmdb::val(key.data(), key.size()),
                                      lmdb::val(memberEvent.data(), memberEvent.size()));
                        break;
                }
                case events::Membership::Knock: {
                        qWarning() << "Skipping knock membership" << roomid << key;
                        break;
                }
                }
        }
}

void
Cache::removeRoom(const QString &roomid)
{
        if (!isMounted_)
                return;

        auto txn = lmdb::txn::begin(env_, nullptr, 0);

        lmdb::dbi_del(txn, roomDb_, lmdb::val(roomid.toUtf8(), roomid.toUtf8().size()), nullptr);

        txn.commit();
}

QMap<QString, RoomState>
Cache::states()
{
        QMap<QString, RoomState> states;

        auto txn    = lmdb::txn::begin(env_, nullptr, MDB_RDONLY);
        auto cursor = lmdb::cursor::open(txn, roomDb_);

        std::string room;
        std::string stateData;

        // Retrieve all the room names.
        while (cursor.get(room, stateData, MDB_NEXT)) {
                auto roomid = QString::fromUtf8(room.data(), room.size());
                auto json =
                  QJsonDocument::fromBinaryData(QByteArray(stateData.data(), stateData.size()));

                RoomState state;
                state.parse(json.object());

                auto memberDb = lmdb::dbi::open(txn, roomid.toStdString().c_str(), MDB_CREATE);
                QMap<QString, events::StateEvent<events::MemberEventContent>> members;

                auto memberCursor = lmdb::cursor::open(txn, memberDb);

                std::string memberId;
                std::string memberContent;

                while (memberCursor.get(memberId, memberContent, MDB_NEXT)) {
                        auto userid = QString::fromUtf8(memberId.data(), memberId.size());
                        auto data   = QJsonDocument::fromBinaryData(
                          QByteArray(memberContent.data(), memberContent.size()));

                        try {
                                events::StateEvent<events::MemberEventContent> member;
                                member.deserialize(data.object());
                                members.insert(userid, member);
                        } catch (const DeserializationException &e) {
                                qWarning() << e.what();
                                qWarning() << "Fault while parsing member event" << data.object();
                                continue;
                        }
                }

                qDebug() << members.size() << "members for" << roomid;

                state.memberships = members;
                states.insert(roomid, state);
        }

        qDebug() << "Retrieved" << states.size() << "rooms";

        cursor.close();

        txn.commit();

        return states;
}

void
Cache::setNextBatchToken(lmdb::txn &txn, const QString &token)
{
        auto value = token.toUtf8();

        lmdb::dbi_put(