aboutsummaryrefslogtreecommitdiff
path: root/connection.cpp
blob: fdf58e9e679d883d0dc54a7b9ac89b7e723555be (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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
/******************************************************************************
 * Copyright (C) 2015 Felix Rohrbach <kde@fxrh.de>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "connection.h"
#include "connectiondata.h"
#include "user.h"
#include "events/event.h"
#include "room.h"
#include "jobs/passwordlogin.h"
#include "jobs/logoutjob.h"
#include "jobs/sendeventjob.h"
#include "jobs/postreceiptjob.h"
#include "jobs/joinroomjob.h"
#include "jobs/leaveroomjob.h"
#include "jobs/roommessagesjob.h"
#include "jobs/syncjob.h"
#include "jobs/mediathumbnailjob.h"

#include <QtNetwork/QDnsLookup>

using namespace QMatrixClient;

class Connection::Private
{
    public:
        explicit Private(const QUrl& serverUrl)
            : q(nullptr)
            , data(new ConnectionData(serverUrl))
            , syncJob(nullptr)
        { }
        Q_DISABLE_COPY(Private)
        Private(Private&&) = delete;
        Private operator=(Private&&) = delete;
        ~Private() { delete data; }

        Connection* q;
        ConnectionData* data;
        // A complex key below is a pair of room name and whether its
        // state is Invited. The spec mandates to keep Invited room state
        // separately so we should, e.g., keep objects for Invite and
        // Leave state of the same room.
        QHash<QPair<QString, bool>, Room*> roomMap;
        QHash<QString, User*> userMap;
        QString username;
        QString password;
        QString userId;

        SyncJob* syncJob;
};

Connection::Connection(const QUrl& server, QObject* parent)
    : QObject(parent)
    , d(new Private(server))
{
    d->q = this; // All d initialization should occur before this line
}

Connection::Connection()
    : Connection(QUrl("https://matrix.org"))
{
}

Connection::~Connection()
{
    qCDebug(MAIN) << "deconstructing connection object for" << d->userId;
    stopSync();
    delete d;
}

void Connection::resolveServer(const QString& domain)
{
    // Find the Matrix server for the given domain.
    QScopedPointer<QDnsLookup, QScopedPointerDeleteLater> dns { new QDnsLookup() };
    dns->setType(QDnsLookup::SRV);
    dns->setName("_matrix._tcp." + domain);

    dns->lookup();
    connect(dns.data(), &QDnsLookup::finished, [&]() {
        // Check the lookup succeeded.
        if (dns->error() != QDnsLookup::NoError ||
                dns->serviceRecords().isEmpty()) {
            emit resolveError("DNS lookup failed");
            return;
        }

        // Handle the results.
        auto record = dns->serviceRecords().front();
        d->data->setHost(record.target());
        d->data->setPort(record.port());
        emit resolved();
    });
}

void Connection::connectToServer(const QString& user, const QString& password)
{
    auto loginJob = callApi<PasswordLogin>(user, password);
    connect( loginJob, &PasswordLogin::success, [=] () {
        connectWithToken(loginJob->id(), loginJob->token());
    });
    connect( loginJob, &PasswordLogin::failure, [=] () {
        emit loginError(loginJob->errorString());
    });
    d->username = user; // to be able to reconnect
    d->password = password;
}

void Connection::connectWithToken(const QString& userId, const QString& token)
{
    d->userId = userId;
    d->data->setToken(token);
    qCDebug(MAIN) << "Accessing" << d->data->baseUrl()
             << "by user" << userId
             << "with the following access token:";
    qCDebug(MAIN) << token;
    emit connected();
}

void Connection::reconnect()
{
    auto loginJob = callApi<PasswordLogin>(d->username, d->password);
    connect( loginJob, &PasswordLogin::success, [=] () {
        d->userId = loginJob->id();
        emit reconnected();
    });
    connect( loginJob, &PasswordLogin::failure, [=] () {
        emit loginError(loginJob->errorString());
    });
}

void Connection::logout()
{
    auto job = callApi<LogoutJob>();
    connect( job, &LogoutJob::success, [=] {
        stopSync();
        emit loggedOut();
    });
}

void Connection::sync(int timeout)
{
    if (d->syncJob)
        return;

    // Raw string: http://en.cppreference.com/w/cpp/language/string_literal
    const QString filter { R"({"room": { "timeline": { "limit": 100 } } })" };
    auto job = d->syncJob =
            callApi<SyncJob>(d->data->lastEvent(), filter, timeout);
    connect( job, &SyncJob::success, [=] () {
        d->data->setLastEvent(job->nextBatch());
        for( auto&& roomData: job->takeRoomData() )
        {
            if ( auto* r = provideRoom(roomData.roomId, roomData.joinState) )
                r->updateData(std::move(roomData));
        }
        d->syncJob = nullptr;
        emit syncDone();
    });
    connect( job, &SyncJob::retryScheduled, this, &Connection::networkError);
    connect( job, &SyncJob::failure, [=] () {
        d->syncJob = nullptr;
        if (job->error() == BaseJob::ContentAccessError)
            emit loginError(job->errorString());
        else
            emit syncError(job->errorString());
    });
}

void Connection::stopSync()
{
    if (d->syncJob)
    {
        d->syncJob->abandon();
        d->syncJob = nullptr;
    }
}

void Connection::postMessage(Room* room, const QString& type, const QString& message) const
{
    callApi<SendEventJob>(room->id(), type, message);
}

PostReceiptJob* Connection::postReceipt(Room* room, RoomEvent* event) const
{
    return callApi<PostReceiptJob>(room->id(), event->id());
}

JoinRoomJob* Connection::joinRoom(const QString& roomAlias)
{
    return callApi<JoinRoomJob>(roomAlias);
}

void Connection::leaveRoom(Room* room)
{
    callApi<LeaveRoomJob>(room->id());
}

RoomMessagesJob* Connection::getMessages(Room* room, const QString& from) const
{
    return callApi<RoomMessagesJob>(room->id(), from);
}

MediaThumbnailJob* Connection::getThumbnail(const QUrl& url, QSize requestedSize) const
{
    return callApi<MediaThumbnailJob>(url, requestedSize);
}

MediaThumbnailJob* Connection::getThumbnail(const QUrl& url, int requestedWidth,
                                            int requestedHeight) const
{
    return getThumbnail(url, QSize(requestedWidth, requestedHeight));
}

QUrl Connection::homeserver() const
{
    return d->data->baseUrl();
}

User* Connection::user(const QString& userId)
{
    if( d->userMap.contains(userId) )
        return d->userMap.value(userId);
    auto* user = createUser(this, userId);
    d->userMap.insert(userId, user);
    return user;
}

User *Connection::user()
{
    if( d->userId.isEmpty() )
        return nullptr;
    return user(d->userId);
}

QString Connection::userId() const
{
    return d->userId;
}

QString Connection::token() const
{
    return accessToken();
}

QString Connection::accessToken() const
{
    return d->data->accessToken();
}

SyncJob* Connection::syncJob() const
{
    return d->syncJob;
}

int Connection::millisToReconnect() const
{
    return d->syncJob ? d->syncJob->millisToRetry() : 0;
}

QHash< QPair<QString, bool>, Room* > Connection::roomMap() const
{
    // Copy-on-write-and-remove-elements is faster than copying elements one by one.
    QHash< QPair<QString, bool>, Room* > roomMap = d->roomMap;
    for (auto it = roomMap.begin(); it != roomMap.end(); )
    {
        if (it.value()->joinState() == JoinState::Leave)
            it = roomMap.erase(it);
        else
            ++it;
    }
    return roomMap;
}

const ConnectionData* Connection::connectionData() const
{
    return d->data;
}

Room* Connection::provideRoom(const QString& id, JoinState joinState)
{
    // TODO: This whole function is a strong case for a RoomManager class.
    if (id.isEmpty())
    {
        qCDebug(MAIN) << "Connection::provideRoom() with empty id, doing nothing";
        return nullptr;
    }

    // Room transitions from the Connection standpoint:
    // - none -> (new) Invite
    // - none -> (new) Join
    // - none -> (new) Leave
    // - Invite -> (new) Join replaces Invite (deleted)
    // - Invite -> (new) Leave (archived) replaces Invite (deleted)
    // - Join -> (moves to) Leave
    // - Leave -> (new) Invite, Leave
    // - Leave -> (moves to) Join
    // Room transitions from the user's standpoint (what's seen in signals):
    // - none -> Invite: newRoom(Invite)
    // - none -> Join: newRoom(Join) or Room::joinStateChanged(Join); joinedRoom
    // - Invite -> Invite replaced with Join:
    //      newRoom(Join); joinedRoom; aboutToDeleteRoom(Invite)
    // - Invite -> Invite replaced with Leave (none):
    //      newRoom(Leave); leftRoom; aboutToDeleteRoom(Invite)
    // - Join -> Leave (none): leftRoom
    const auto roomKey = qMakePair(id, joinState == JoinState::Invite);
    auto* room = d->roomMap.value(roomKey, nullptr);
    if (!room)
    {
        room = createRoom(this, id, joinState);
        if (!room)
        {
            qCCritical(MAIN) << "Failed to create a room" << id;
            return nullptr;
        }
        qCDebug(MAIN) << "Created Room" << id << ", invited:" << roomKey.second;

        d->roomMap.insert(roomKey, room);
        emit newRoom(room);
    }

    if (joinState != JoinState::Invite)
    {
        // Preempt the Invite room (if any) with a room in Join/Leave state.
        auto prevInvite = d->roomMap.take({id, true});
        if (joinState == JoinState::Join)
            joinedRoom(room, prevInvite);
        else if (joinState == JoinState::Leave)
            leftRoom(room, prevInvite);
        if (prevInvite)
        {
            qCDebug(MAIN) << "Deleting Invite state for room" << prevInvite->id();
            emit aboutToDeleteRoom(prevInvite);
            delete prevInvite;
        }
    }

    return room;
}

Connection::room_factory_t Connection::createRoom =
    [](Connection* c, const QString& id, JoinState joinState)
    { return new Room(c, id, joinState); };

Connection::user_factory_t Connection::createUser =
    [](Connection* c, const QString& id) { return new User(id, c); };
QByteArray Connection::generateTxnId()
{
    return d->data->generateTxnId();
}