aboutsummaryrefslogtreecommitdiff
path: root/lib/connection.cpp
blob: 8007cea1adba0d1dae8d2e91b1f74c3e15fc8980 (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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
/******************************************************************************
 * 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/directchatevent.h"
#include "events/eventloader.h"
#include "room.h"
#include "settings.h"
#include "csapi/login.h"
#include "csapi/logout.h"
#include "csapi/receipts.h"
#include "csapi/leaving.h"
#include "csapi/account-data.h"
#include "csapi/joining.h"
#include "csapi/to_device.h"
#include "jobs/sendeventjob.h"
#include "jobs/syncjob.h"
#include "jobs/mediathumbnailjob.h"
#include "jobs/downloadfilejob.h"

#include <QtNetwork/QDnsLookup>
#include <QtCore/QFile>
#include <QtCore/QDir>
#include <QtCore/QFileInfo>
#include <QtCore/QStandardPaths>
#include <QtCore/QStringBuilder>
#include <QtCore/QElapsedTimer>
#include <QtCore/QRegularExpression>
#include <QtCore/QCoreApplication>

using namespace QMatrixClient;

// This is very much Qt-specific; STL iterators don't have key() and value()
template <typename HashT, typename Pred>
HashT erase_if(HashT& hashMap, Pred pred)
{
    HashT removals;
    for (auto it = hashMap.begin(); it != hashMap.end();)
    {
        if (pred(it))
        {
            removals.insert(it.key(), it.value());
            it = hashMap.erase(it);
        } else
            ++it;
    }
    return removals;
}

#ifndef TRIM_RAW_DATA
#define TRIM_RAW_DATA 65535
#endif

class Connection::Private
{
    public:
        explicit Private(std::unique_ptr<ConnectionData>&& connection)
            : data(move(connection))
        { }
        Q_DISABLE_COPY(Private)
        Private(Private&&) = delete;
        Private operator=(Private&&) = delete;

        Connection* q = nullptr;
        std::unique_ptr<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;
        QVector<QString> roomIdsToForget;
        QVector<Room*> firstTimeRooms;
        QMap<QString, User*> userMap;
        DirectChatsMap directChats;
        std::unordered_map<QString, EventPtr> accountData;
        QString userId;

        SyncJob* syncJob = nullptr;

        bool cacheState = true;
        bool cacheToBinary = SettingsGroup("libqmatrixclient")
                             .value("cache_type").toString() != "json";

        void connectWithToken(const QString& user, const QString& accessToken,
                              const QString& deviceId);
        void broadcastDirectChatUpdates(const DirectChatsMap& additions,
                                        const DirectChatsMap& removals);

        template <typename EventT>
        EventT* unpackAccountData() const
        {
            const auto& eventIt = accountData.find(EventT::matrixTypeId());
            return eventIt == accountData.end()
                    ? nullptr : weakPtrCast<EventT>(eventIt->second);
        }

        void packAndSendAccountData(EventPtr&& event)
        {
            const auto eventType = event->matrixType();
            q->callApi<SetAccountDataJob>(userId, eventType,
                                          event->contentJson());
            accountData[eventType] = std::move(event);
            emit q->accountDataChanged(eventType);
        }

        template <typename EventT, typename ContentT>
        void packAndSendAccountData(ContentT&& content)
        {
            packAndSendAccountData(
                        makeEvent<EventT>(std::forward<ContentT>(content)));
        }
};

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

Connection::Connection(QObject* parent)
    : Connection({}, parent)
{ }

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

void Connection::resolveServer(const QString& mxidOrDomain)
{
    // At this point we may have something as complex as
    // @username:[IPv6:address]:port, or as simple as a plain domain name.

    // Try to parse as an FQID; if there's no @ part, assume it's a domain name.
    QRegularExpression parser(
        "^(@.+?:)?" // Optional username (allow everything for compatibility)
        "(\\[[^]]+\\]|[^:@]+)" // Either IPv6 address or hostname/IPv4 address
        "(:\\d{1,5})?$", // Optional port
        QRegularExpression::UseUnicodePropertiesOption); // Because asian digits
    auto match = parser.match(mxidOrDomain);

    QUrl maybeBaseUrl = QUrl::fromUserInput(match.captured(2));
    maybeBaseUrl.setScheme("https"); // Instead of the Qt-default "http"
    if (!match.hasMatch() || !maybeBaseUrl.isValid())
    {
        emit resolveError(
            tr("%1 is not a valid homeserver address")
                    .arg(maybeBaseUrl.toString()));
        return;
    }

    setHomeserver(maybeBaseUrl);
    emit resolved();
    return;

    // FIXME, #178: The below code is incorrect and is no more executed. The
    // correct server resolution should be done from .well-known/matrix/client
    auto domain = maybeBaseUrl.host();
    qCDebug(MAIN) << "Finding the server" << domain;
    // Check if the Matrix server has a dedicated service record.
    auto* dns = new QDnsLookup();
    dns->setType(QDnsLookup::SRV);
    dns->setName("_matrix._tcp." + domain);

    connect(dns, &QDnsLookup::finished, [this,dns,maybeBaseUrl]() {
        QUrl baseUrl { maybeBaseUrl };
        if (dns->error() == QDnsLookup::NoError &&
                dns->serviceRecords().isEmpty())
        {
            auto record = dns->serviceRecords().front();
            baseUrl.setHost(record.target());
            baseUrl.setPort(record.port());
            qCDebug(MAIN) << "SRV record for" << maybeBaseUrl.host()
                          << "is" << baseUrl.authority();
        } else {
            qCDebug(MAIN) << baseUrl.host() << "doesn't have SRV record"
                          << dns->name() << "- using the hostname as is";
        }
        setHomeserver(baseUrl);
        emit resolved();
        dns->deleteLater();
    });
    dns->lookup();
}

void Connection::connectToServer(const QString& user, const QString& password,
                                 const QString& initialDeviceName,
                                 const QString& deviceId)
{
    checkAndConnect(user,
        [=] {
            doConnectToServer(user, password, initialDeviceName, deviceId);
        });
}
void Connection::doConnectToServer(const QString& user, const QString& password,
                                   const QString& initialDeviceName,
                                   const QString& deviceId)
{
    auto loginJob = callApi<LoginJob>(QStringLiteral("m.login.password"),
            user, /*medium*/ "", /*address*/ "", password, /*token*/ "",
            deviceId, initialDeviceName);
    connect(loginJob, &BaseJob::success, this,
        [this, loginJob] {
            d->connectWithToken(loginJob->userId(), loginJob->accessToken(),
                                loginJob->deviceId());
        });
    connect(loginJob, &BaseJob::failure, this,
        [this, loginJob] {
            emit loginError(loginJob->errorString(),
                            loginJob->rawData(TRIM_RAW_DATA));
        });
}

void Connection::connectWithToken(const QString& userId,
                                  const QString& accessToken,
                                  const QString& deviceId)
{
    checkAndConnect(userId,
        [=] { d->connectWithToken(userId, accessToken, deviceId); });
}

void Connection::Private::connectWithToken(const QString& user,
                                           const QString& accessToken,
                                           const QString& deviceId)
{
    userId = user;
    q->user(); // Creates a User object for the local user
    data->setToken(accessToken.toLatin1());
    data->setDeviceId(deviceId);
    qCDebug(MAIN) << "Using server" << data->baseUrl().toDisplayString()
                  << "by user" << userId << "from device" << deviceId;
    emit q->stateChanged();
    emit q->connected();

}

void Connection::checkAndConnect(const QString& userId,
                                 std::function<void()> connectFn)
{
    if (d->data->baseUrl().isValid())
    {
        connectFn();
        return;
    }
    // Not good to go, try to fix the homeserver URL.
    if (userId.startsWith('@') && userId.indexOf(':') != -1)
    {
        connectSingleShot(this, &Connection::homeserverChanged, this, connectFn);
        // NB: doResolveServer can emit resolveError, so this is a part of
        // checkAndConnect function contract.
        resolveServer(userId);
    } else
        emit resolveError(
            tr("%1 is an invalid homeserver URL")
                .arg(d->data->baseUrl().toString()));
}

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

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

    // Raw string: http://en.cppreference.com/w/cpp/language/string_literal
    const auto filter =
        QStringLiteral(R"({"room": { "timeline": { "limit": 100 } } })");
    auto job = d->syncJob = callApi<SyncJob>(BackgroundRequest,
                                         d->data->lastEvent(), filter, timeout);
    connect( job, &SyncJob::success, this, [this, job] {
        onSyncSuccess(job->takeData());
        d->syncJob = nullptr;
        emit syncDone();
    });
    connect( job, &SyncJob::retryScheduled, this,
        [this,job] (int retriesTaken, int nextInMilliseconds)
        {
            emit networkError(job->errorString(), job->rawData(TRIM_RAW_DATA),
                              retriesTaken, nextInMilliseconds);
        });
    connect( job, &SyncJob::failure, this, [this, job] {
        d->syncJob = nullptr;
        if (job->error() == BaseJob::ContentAccessError)
        {
            qCWarning(SYNCJOB)
                << "Sync job failed with ContentAccessError - login expired?";
            emit loginError(job->errorString(), job->rawData(TRIM_RAW_DATA));
        }
        else
            emit syncError(job->errorString(), job->rawData(TRIM_RAW_DATA));
    });
}

void Connection::onSyncSuccess(SyncData &&data) {
    d->data->setLastEvent(data.nextBatch());
    for (auto&& roomData: data.takeRoomData())
    {
        const auto forgetIdx = d->roomIdsToForget.indexOf(roomData.roomId);
        if (forgetIdx != -1)
        {
            d->roomIdsToForget.removeAt(forgetIdx);
            if (roomData.joinState == JoinState::Leave)
            {
                qDebug(MAIN) << "Room" << roomData.roomId
                    << "has been forgotten, ignoring /sync response for it";
                continue;
            }
            qWarning(MAIN) << "Room" << roomData.roomId
                 << "has just been forgotten but /sync returned it in"
                 << toCString(roomData.joinState)
                 << "state - suspiciously fast turnaround";
        }
        if ( auto* r = provideRoom(roomData.roomId, roomData.joinState) )
        {
            r->updateData(std::move(roomData));
            if (d->firstTimeRooms.removeOne(r))
                emit loadedRoomState(r);
        }
        QCoreApplication::processEvents();
    }
    for (auto&& accountEvent: data.takeAccountData())
    {
        if (is<DirectChatEvent>(*accountEvent))
        {
            const auto usersToDCs = ptrCast<DirectChatEvent>(move(accountEvent))
                                        ->usersToDirectChats();
            DirectChatsMap removals =
                erase_if(d->directChats, [&usersToDCs] (auto it) {
                    return !usersToDCs.contains(it.key()->id(), it.value());
                });
            if (MAIN().isDebugEnabled())
                for (auto it = removals.begin(); it != removals.end(); ++it)
                    qCDebug(MAIN) << it.value()
                        << "is no more a direct chat with" << it.key()->id();

            DirectChatsMap additions;
            for (auto it = usersToDCs.begin(); it != usersToDCs.end(); ++it)
            {
                const auto* u = user(it.key());
                if (!d->directChats.contains(u, it.value()))
                {
                    additions.insert(u, it.value());
                    d->directChats.insert(u, it.value());
                    qCDebug(MAIN) << "Marked room" << it.value()
                                  << "as a direct chat with" << u->id();
                }
            }
            if (!additions.isEmpty() || !removals.isEmpty())
                emit directChatsListChanged(additions, removals);

            continue;
        }
        if (is<IgnoredUsersEvent>(*accountEvent))
            qCDebug(MAIN) << "Users ignored by" << d->userId << "updated:"
                << QStringList::fromSet(ignoredUsers()).join(',');

        auto& currentData = d->accountData[accountEvent->matrixType()];
        // A polymorphic event-specific comparison might be a bit more
        // efficient; maaybe do it another day
        if (!currentData ||
                currentData->contentJson() != accountEvent->contentJson())
        {
            currentData = std::move(accountEvent);
            qCDebug(MAIN) << "Updated account data of type"
                          << currentData->matrixType();
            emit accountDataChanged(currentData->matrixType());
        }
    }
}

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(), "m.read", event->id());
}

JoinRoomJob* Connection::joinRoom(const QString& roomAlias)
{
    auto job = callApi<JoinRoomJob>(roomAlias);
    connect(job, &JoinRoomJob::success,
            this, [this, job] { provideRoom(job->roomId(), JoinState::Join); });
    return job;
}

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

inline auto splitMediaId(const QString& mediaId)
{
    auto idParts = mediaId.split('/');
    Q_ASSERT_X(idParts.size() == 2, __FUNCTION__,
               ("'" + mediaId +
                "' doesn't look like 'serverName/localMediaId'").toLatin1());
    return idParts;
}

MediaThumbnailJob* Connection::getThumbnail(const QString& mediaId,
    QSize requestedSize, RunningPolicy policy) const
{
    auto idParts = splitMediaId(mediaId);
    return callApi<MediaThumbnailJob>(policy,
        idParts.front(), idParts.back(), requestedSize);
}

MediaThumbnailJob* Connection::getThumbnail(const QUrl& url,
    QSize requestedSize, RunningPolicy policy) const
{
    return getThumbnail(url.authority() + url.path(), requestedSize, policy);
}

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

UploadContentJob* Connection::uploadContent(QIODevice* contentSource,
        const QString& filename, const QString& contentType) const
{
    return callApi<UploadContentJob>(contentSource, filename, contentType);
}

UploadContentJob* Connection::uploadFile(const QString& fileName,
                                         const QString& contentType)
{
    auto sourceFile = new QFile(fileName);
    if (!sourceFile->open(QIODevice::ReadOnly))
    {
        qCWarning(MAIN) << "Couldn't open" << sourceFile->fileName()
                        << "for reading";
        return nullptr;
    }
    return uploadContent(sourceFile, QFileInfo(*sourceFile).fileName(),
                         contentType);
}

GetContentJob* Connection::getContent(const QString& mediaId) const
{
    auto idParts = splitMediaId(mediaId);
    return callApi<GetContentJob>(idParts.front(), idParts.back());
}

GetContentJob* Connection::getContent(const QUrl& url) const
{
    return getContent(url.authority() + url.path());
}

DownloadFileJob* Connection::downloadFile(const QUrl& url,
                                          const QString& localFilename) const
{
    auto mediaId = url.authority() + url.path();
    auto idParts = splitMediaId(mediaId);
    auto* job = callApi<DownloadFileJob>(idParts.front(), idParts.back(),
                                         localFilename);
    return job;
}

CreateRoomJob* Connection::createRoom(RoomVisibility visibility,
    const QString& alias, const QString& name, const QString& topic,
    const QStringList& invites, const QString& presetName,
    bool isDirect, bool guestsCanJoin,
    const QVector<CreateRoomJob::StateEvent>& initialState,
    const QVector<CreateRoomJob::Invite3pid>& invite3pids,
    const QJsonObject& creationContent)
{
    // FIXME: switch to using QStringList instead of const QStringList& in 0.4
    auto filteredInvites = invites;
    filteredInvites.removeOne(d->userId); // The creator is by definition in the room
    auto job = callApi<CreateRoomJob>(
            visibility == PublishRoom ? "public" : "private", alias, name,
            topic, filteredInvites, invite3pids, creationContent, initialState,
            presetName, isDirect, guestsCanJoin);
    connect(job, &BaseJob::success, this, [this,job] {
        emit createdRoom(provideRoom(job->roomId(), JoinState::Join));
    });
    return job;
}

void Connection::requestDirectChat(const QString& userId)
{
    doInDirectChat(userId, [this] (Room* r) { emit directChatAvailable(r); });
}

void Connection::doInDirectChat(const QString& userId,
                                std::function<void (Room*)> operation)
{
    // There can be more than one DC; find the first valid, and delete invalid
    // (left/forgotten) ones along the way.
    const auto* u = user(userId);
    DirectChatsMap removals;
    for (auto it = d->directChats.find(u);
         it != d->directChats.end() && it.key() == u; ++it)
    {
        const auto& roomId = *it;
        if (auto r = room(roomId, JoinState::Join))
        {
            Q_ASSERT(r->id() == roomId);
            // A direct chat with yourself should only involve yourself :)
            if (userId == d->userId && r->memberCount() > 1)
                continue;
            qCDebug(MAIN) << "Requested direct chat with" << userId
                          << "is already available as" << r->id();
            operation(r);
            return;
        }
        if (auto ir = invitation(roomId))
        {
            Q_ASSERT(ir->id() == roomId);
            auto j = joinRoom(ir->id());
            connect(j, &BaseJob::success, this, [this,roomId,userId,operation] {
                qCDebug(MAIN) << "Joined the already invited direct chat with"
                              << userId << "as" << roomId;
                operation(room(roomId, JoinState::Join));
            });
        }
        qCWarning(MAIN) << "Direct chat with" << userId << "known as room"
                        << roomId << "is not valid and will be discarded";
        // Postpone actual deletion until we finish iterating d->directChats.
        removals.insert(it.key(), it.value());
    }
    if (!removals.isEmpty())
    {
        for (auto it = removals.cbegin(); it != removals.cend(); ++it)
            d->directChats.remove(it.key(), it.value());
        d->broadcastDirectChatUpdates({}, removals);
    }

    auto j = createDirectChat(userId);
    connect(j, &BaseJob::success, this, [this,j,userId,operation] {
        qCDebug(MAIN) << "Direct chat with" << userId
                      << "has been created as" << j->roomId();
        operation(room(j->roomId(), JoinState::Join));
    });
}

CreateRoomJob* Connection::createDirectChat(const QString& userId,
    const QString& topic, const QString& name)
{
    return createRoom(UnpublishRoom, "", name, topic, {userId},
                      "trusted_private_chat", true);
}

ForgetRoomJob* Connection::forgetRoom(const QString& id)
{
    // To forget is hard :) First we should ensure the local user is not
    // in the room (by leaving it, if necessary); once it's done, the /forget
    // endpoint can be called; and once this is through, the local Room object
    // (if any existed) is deleted. At the same time, we still have to
    // (basically immediately) return a pointer to ForgetRoomJob. Therefore
    // a ForgetRoomJob is created in advance and can be returned in a probably
    // not-yet-started state (it will start once /leave completes).
    auto forgetJob = new ForgetRoomJob(id);
    auto room = d->roomMap.value({id, false});
    if (!room)
        room = d->roomMap.value({id, true});
    if (room && room->joinState() != JoinState::Leave)
    {
        auto leaveJob = room->leaveRoom();
        connect(leaveJob, &BaseJob::success, this, [this, forgetJob, room] {
            forgetJob->start(connectionData());
            // If the matching /sync response hasn't arrived yet, mark the room
            // for explicit deletion
            if (room->joinState() != JoinState::Leave)
                d->roomIdsToForget.push_back(room->id());
        });
        connect(leaveJob, &BaseJob::failure, forgetJob, &BaseJob::abandon);
    }
    else
        forgetJob->start(connectionData());
    connect(forgetJob, &BaseJob::success, this, [this, id]
    {
        // If the room is in the map (possibly in both forms), delete all forms.
        for (auto f: {false, true})
            if (auto r = d->roomMap.take({ id, f }))
            {
                emit aboutToDeleteRoom(r);
                qCDebug(MAIN) << "Room" << id
                              << "in join state" << toCString(r->joinState())
                              << "will be deleted";
                r->deleteLater();
            }
    });
    return forgetJob;
}

SendToDeviceJob* Connection::sendToDevices(const QString& eventType,
        const UsersToDevicesToEvents& eventsMap) const
{
    QHash<QString, QHash<QString, QJsonObject>> json;
    json.reserve(int(eventsMap.size()));
    std::for_each(eventsMap.begin(), eventsMap.end(),
        [&json] (const auto& userTodevicesToEvents) {
            auto& jsonUser = json[userTodevicesToEvents.first];
            const auto& devicesToEvents = userTodevicesToEvents.second;
            std::for_each(devicesToEvents.begin(), devicesToEvents.end(),
                [&jsonUser] (const auto& deviceToEvents) {
                    jsonUser.insert(deviceToEvents.first,
                                    deviceToEvents.second.contentJson());
                });
        });
    return callApi<SendToDeviceJob>(BackgroundRequest,
                eventType, generateTxnId(), json);
}

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

Room* Connection::room(const QString& roomId, JoinStates states) const
{
    Room* room = d->roomMap.value({roomId, false}, nullptr);
    if (states.testFlag(JoinState::Join) &&
            room && room->joinState() == JoinState::Join)
        return room;

    if (states.testFlag(JoinState::Invite))
        if (Room* invRoom = invitation(roomId))
            return invRoom;

    if (states.testFlag(JoinState::Leave) &&
            room && room->joinState() == JoinState::Leave)
        return room;

    return nullptr;
}

Room* Connection::invitation(const QString& roomId) const
{
    return d->roomMap.value({roomId, true}, nullptr);
}

User* Connection::user(const QString& userId)
{
    Q_ASSERT(userId.startsWith('@') && userId.contains(':'));
    if( d->userMap.contains(userId) )
        return d->userMap.value(userId);
    auto* user = userFactory(this, userId);
    d->userMap.insert(userId, user);
    emit newUser(user);
    return user;
}

const User* Connection::user() const
{
    return d->userId.isEmpty() ? nullptr : d->userMap.value(d->userId, nullptr);
}

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

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

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

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

QByteArray 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;
}

bool Connection::hasAccountData(const QString& type) const
{
    return d->accountData.find(type) != d->accountData.cend();
}

const EventPtr& Connection::accountData(const QString& type) const
{
    static EventPtr NoEventPtr {};
    auto it = d->accountData.find(type);
    return it == d->accountData.end() ? NoEventPtr : it->second;
}

QJsonObject Connection::accountDataJson(const QString& type) const
{
    const auto& eventPtr = accountData(type);
    return eventPtr ? eventPtr->contentJson() : QJsonObject();
}

void Connection::setAccountData(EventPtr&& event)
{
    d->packAndSendAccountData(std::move(event));
}

void Connection::setAccountData(const QString& type, const QJsonObject& content)
{
    d->packAndSendAccountData(loadEvent<Event>(type, content));
}

QHash<QString, QVector<Room*>> Connection::tagsToRooms() const
{
    QHash<QString, QVector<Room*>> result;
    for (auto* r: qAsConst(d->roomMap))
    {
        for (const auto& tagName: r->tagNames())
            result[tagName].push_back(r);
    }
    for (auto it = result.begin(); it != result.end(); ++it)
        std::sort(it->begin(), it->end(),
            [t=it.key()] (Room* r1, Room* r2) {
                return r1->tags().value(t).order < r2->tags().value(t).order;
            });
    return result;
}

QStringList Connection::tagNames() const
{
    QStringList tags ({FavouriteTag});
    for (auto* r: qAsConst(d->roomMap))
        for (const auto& tag: r->tagNames())
            if (tag != LowPriorityTag && !tags.contains(tag))
                tags.push_back(tag);
    tags.push_back(LowPriorityTag);
    return tags;
}

QVector<Room*> Connection::roomsWithTag(const QString& tagName) const
{
    QVector<Room*> rooms;
    std::copy_if(d->roomMap.begin(), d->roomMap.end(), std::back_inserter(rooms),
                 [&tagName] (Room* r) { return r->tags().contains(tagName); });
    return rooms;
}

Connection::DirectChatsMap Connection::directChats() const
{
    return d->directChats;
}

QJsonObject toJson(const Connection::DirectChatsMap& directChats)
{
    QJsonObject json;
    for (auto it = directChats.begin(); it != directChats.end();)
    {
        QJsonArray roomIds;
        const auto* user = it.key();
        for (; it != directChats.end() && it.key() == user; ++it)
            roomIds.append(*it);
        json.insert(user->id(), roomIds);
    }
    return json;
}

void Connection::Private::broadcastDirectChatUpdates(const DirectChatsMap& additions,
                                                     const DirectChatsMap& removals)
{
    q->callApi<SetAccountDataJob>(userId, QStringLiteral("m.direct"),
                                  toJson(directChats));
    emit q->directChatsListChanged(additions, removals);
}

void Connection::addToDirectChats(const Room* room, const User* user)
{
    Q_ASSERT(room != nullptr && user != nullptr);
    if (d->directChats.contains(user, room->id()))
        return;
    d->directChats.insert(user, room->id());
    DirectChatsMap additions { { user, room->id() } };
    d->broadcastDirectChatUpdates(additions, {});
}

void Connection::removeFromDirectChats(const QString& roomId, const User* user)
{
    Q_ASSERT(!roomId.isEmpty());
    if ((user != nullptr && !d->directChats.contains(user, roomId)) ||
            d->directChats.key(roomId) == nullptr)
        return;

    DirectChatsMap removals;
    if (user != nullptr)
    {
        removals.insert(user, roomId);
        d->directChats.remove(user, roomId);
    }
    else
        removals = erase_if(d->directChats,
                            [&roomId] (auto it) { return it.value() == roomId; });
    d->broadcastDirectChatUpdates({}, removals);
}

bool Connection::isDirectChat(const QString& roomId) const
{
    return d->directChats.key(roomId) != nullptr;
}

QList<const User*> Connection::directChatUsers(const Room* room) const
{
    Q_ASSERT(room != nullptr);
    return d->directChats.keys(room->id());
}

bool Connection::isIgnored(const User* user) const
{
    return ignoredUsers().contains(user->id());
}

Connection::IgnoredUsersList Connection::ignoredUsers() const
{
    const auto* event = d->unpackAccountData<IgnoredUsersEvent>();
    return event ? event->ignored_users() : IgnoredUsersList();
}

void Connection::addToIgnoredUsers(const User* user)
{
    Q_ASSERT(user != nullptr);

    auto ignoreList = ignoredUsers();
    if (!ignoreList.contains(user->id()))
    {
        ignoreList.insert(user->id());
        d->packAndSendAccountData<IgnoredUsersEvent>(ignoreList);
        emit ignoredUsersListChanged({{ user->id() }}, {});
    }
}

void Connection::removeFromIgnoredUsers(const User* user)
{
    Q_ASSERT(user != nullptr);

    auto ignoreList = ignoredUsers();
    if (ignoreList.remove(user->id()) != 0)
    {
        d->packAndSendAccountData<IgnoredUsersEvent>(ignoreList);
        emit ignoredUsersListChanged({}, {{ user->id() }});
    }
}

QMap<QString, User*> Connection::users() const
{
    return d->userMap;
}

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

Room* Connection::provideRoom(const QString& id, JoinState joinState)
{
    // TODO: This whole function is a strong case for a RoomManager class.
    Q_ASSERT_X(!id.isEmpty(), __FUNCTION__, "Empty room id");

    const auto roomKey = qMakePair(id, joinState == JoinState::Invite);
    auto* room = d->roomMap.value(roomKey, nullptr);
    if (room)
    {
        // Leave is a special case because in transition (5a) (see the .h file)
        // joinState == room->joinState but we still have to preempt the Invite
        // and emit a signal. For Invite and Join, there's no such problem.
        if (room->joinState() == joinState && joinState != JoinState::Leave)
            return room;
    }
    else
    {
        room = roomFactory(this, id, joinState);
        if (!room)
        {
            qCCritical(MAIN) << "Failed to create a room" << id;
            return nullptr;
        }
        d->roomMap.insert(roomKey, room);
        d->firstTimeRooms.push_back(room);
        emit newRoom(room);
    }
    if (joinState == JoinState::Invite)
    {
        // prev is either Leave or nullptr
        auto* prev = d->roomMap.value({id, false}, nullptr);
        emit invitedRoom(room, prev);
    }
    else
    {
        room->setJoinState(joinState);
        // Preempt the Invite room (if any) with a room in Join/Leave state.
        auto* prevInvite = d->roomMap.take({id, true});
        if (joinState == JoinState::Join)
            emit joinedRoom(room, prevInvite);
        else if (joinState == JoinState::Leave)
            emit leftRoom(room, prevInvite);
        if (prevInvite)
        {
            qCDebug(MAIN) << "Deleting Invite state for room" << prevInvite->id();
            emit aboutToDeleteRoom(prevInvite);
            prevInvite->deleteLater();
        }
    }

    return room;
}

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

Connection::user_factory_t Connection::userFactory =
    [](Connection* c, const QString& id) { return new User(id, c); };

QByteArray Connection::generateTxnId() const
{
    return d->data->generateTxnId();
}

void Connection::setHomeserver(const QUrl& url)
{
    if (homeserver() == url)
        return;

    d->data->setBaseUrl(url);
    emit homeserverChanged(homeserver());
}

static constexpr int CACHE_VERSION_MAJOR = 8;
static constexpr int CACHE_VERSION_MINOR = 0;

void Connection::saveState(const QUrl &toFile) const
{
    if (!d->cacheState)
        return;

    QElapsedTimer et; et.start();

    QFileInfo stateFile {
        toFile.isEmpty() ? stateCachePath() : toFile.toLocalFile()
    };
    if (!stateFile.dir().exists())
        stateFile.dir().mkpath(".");

    QFile outfile { stateFile.absoluteFilePath() };
    if (!outfile.open(QFile::WriteOnly))
    {
        qCWarning(MAIN) << "Error opening" << stateFile.absoluteFilePath()
                        << ":" << outfile.errorString();
        qCWarning(MAIN) << "Caching the rooms state disabled";
        d->cacheState = false;
        return;
    }

    QJsonObject rootObj;
    {
        QJsonObject rooms;
        QJsonObject inviteRooms;
        for (const auto* i : roomMap()) // Pass on rooms in Leave state
        {
            if (i->joinState() == JoinState::Invite)
                inviteRooms.insert(i->id(), i->toJson());
            else
                rooms.insert(i->id(), i->toJson());
            QElapsedTimer et1; et1.start();
            QCoreApplication::processEvents();
            if (et1.elapsed() > 1)
                qCDebug(PROFILER) << "processEvents() borrowed" << et1;
        }

        QJsonObject roomObj;
        if (!rooms.isEmpty())
            roomObj.insert("join", rooms);
        if (!inviteRooms.isEmpty())
            roomObj.insert("invite", inviteRooms);

        rootObj.insert("next_batch", d->data->lastEvent());
        rootObj.insert("rooms", roomObj);
    }
    {
        QJsonArray accountDataEvents {
            basicEventJson(QStringLiteral("m.direct"), toJson(d->directChats))
        };
        for (const auto &e : d->accountData)
            accountDataEvents.append(
                basicEventJson(e.first, e.second->contentJson()));

        rootObj.insert("account_data",
            QJsonObject {{ QStringLiteral("events"), accountDataEvents }});
    }

    QJsonObject versionObj;
    versionObj.insert("major", CACHE_VERSION_MAJOR);
    versionObj.insert("minor", CACHE_VERSION_MINOR);
    rootObj.insert("cache_version", versionObj);

    QJsonDocument json { rootObj };
    auto data = d->cacheToBinary ? json.toBinaryData() :
                                   json.toJson(QJsonDocument::Compact);
    qCDebug(PROFILER) << "Cache for" << userId() << "generated in" << et;

    outfile.write(data.data(), data.size());
    qCDebug(MAIN) << "State cache saved to" << outfile.fileName();
}

void Connection::loadState(const QUrl &fromFile)
{
    if (!d->cacheState)
        return;

    QElapsedTimer et; et.start();
    QFile file {
        fromFile.isEmpty() ? stateCachePath() : fromFile.toLocalFile()
    };
    if (!file.exists())
    {
        qCDebug(MAIN) << "No state cache file found";
        return;
    }
    if(!file.open(QFile::ReadOnly))
    {
        qCWarning(MAIN) << "file " << file.fileName() << "failed to open for read";
        return;
    }
    QByteArray data = file.readAll();

    auto jsonDoc = d->cacheToBinary ? QJsonDocument::fromBinaryData(data) :
                                      QJsonDocument::fromJson(data);
    if (jsonDoc.isNull())
    {
        qCWarning(MAIN) << "Cache file broken, discarding";
        return;
    }
    auto actualCacheVersionMajor =
            jsonDoc.object()
            .value("cache_version").toObject()
            .value("major").toInt();
    if (actualCacheVersionMajor < CACHE_VERSION_MAJOR)
    {
        qCWarning(MAIN)
            << "Major version of the cache file is" << actualCacheVersionMajor
            << "but" << CACHE_VERSION_MAJOR << "required; discarding the cache";
        return;
    }

    SyncData sync;
    sync.parseJson(jsonDoc);
    onSyncSuccess(std::move(sync));
    qCDebug(PROFILER) << "*** Cached state for" << userId() << "loaded in" << et;
}

QString Connection::stateCachePath() const
{
    auto safeUserId = userId();
    safeUserId.replace(':', '_');
    return QStandardPaths::writableLocation(QStandardPaths::CacheLocation)
            % '/' % safeUserId % "_state.json";
}

bool Connection::cacheState() const
{
    return d->cacheState;
}

void Connection::setCacheState(bool newValue)
{
    if (d->cacheState != newValue)
    {
        d->cacheState = newValue;
        emit cacheStateChanged();
    }
}