File: controller.cpp

package info (click to toggle)
spectral 0.0~git20210114.30028a2-3
  • links: PTS
  • area: main
  • in suites: bookworm
  • size: 2,740 kB
  • sloc: cpp: 9,889; xml: 54; makefile: 6
file content (393 lines) | stat: -rw-r--r-- 12,216 bytes parent folder | download | duplicates (2)
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
#include "controller.h"

#include <qt5keychain/keychain.h>

#include <QClipboard>
#include <QFile>
#include <QFileInfo>
#include <QSysInfo>
#include <QtCore/QDebug>
#include <QtCore/QDir>
#include <QtCore/QElapsedTimer>
#include <QtCore/QFileInfo>
#include <QtCore/QStandardPaths>
#include <QtCore/QStringBuilder>
#include <QtCore/QTimer>
#include <QtGui/QCloseEvent>
#include <QtGui/QDesktopServices>
#include <QtGui/QMovie>
#include <QtGui/QPixmap>
#include <QtNetwork/QAuthenticator>
#include <QtNetwork/QNetworkReply>

#include "csapi/account-data.h"
#include "csapi/content-repo.h"
#include "csapi/joining.h"
#include "csapi/logout.h"
#include "csapi/profile.h"
#include "events/eventcontent.h"
#include "events/roommessageevent.h"
#include "settings.h"
#include "spectralroom.h"
#include "spectraluser.h"
#include "utils.h"

Controller::Controller(QObject* parent) : QObject(parent) {
  QApplication::setQuitOnLastWindowClosed(false);

  Connection::setRoomType<SpectralRoom>();
  Connection::setUserType<SpectralUser>();

  connect(&m_ncm, &QNetworkConfigurationManager::onlineStateChanged, this,
          &Controller::isOnlineChanged);

  QTimer::singleShot(0, this, [=] { invokeLogin(); });
}

Controller::~Controller() {
  for (auto c : m_connections) {
    c->stopSync();
    c->saveState();
  }
}

inline QString accessTokenFileName(const AccountSettings& account) {
  QString fileName = account.userId();
  fileName.replace(':', '_');
  return QStandardPaths::writableLocation(
             QStandardPaths::AppLocalDataLocation) +
         '/' + fileName;
}

void Controller::loginWithCredentials(QString serverAddr,
                                      QString user,
                                      QString pass,
                                      QString deviceName) {
  if (user.isEmpty() || pass.isEmpty()) {
    return;
  }

  if (deviceName.isEmpty()) {
    deviceName = "Spectral " + QSysInfo::machineHostName() + " " +
                 QSysInfo::productType() + " " + QSysInfo::productVersion() +
                 " " + QSysInfo::currentCpuArchitecture();
  }

  QUrl serverUrl(serverAddr);

  auto conn = new Connection(this);
  if (serverUrl.isValid()) {
    conn->setHomeserver(serverUrl);
  }
  conn->connectToServer(user, pass, deviceName, "");

  connect(conn, &Connection::connected, [=] {
    AccountSettings account(conn->userId());
    account.setKeepLoggedIn(true);
    account.clearAccessToken();  // Drop the legacy - just in case
    account.setHomeserver(conn->homeserver());
    account.setDeviceId(conn->deviceId());
    account.setDeviceName(deviceName);
    if (!saveAccessTokenToKeyChain(account, conn->accessToken()))
      qWarning() << "Couldn't save access token";
    account.sync();
    addConnection(conn);
    setConnection(conn);
  });
  connect(conn, &Connection::networkError,
          [=](QString error, QString, int, int) {
            emit errorOccured("Network Error", error);
          });
  connect(conn, &Connection::loginError, [=](QString error, QString) {
    emit errorOccured("Login Failed", error);
  });
}

void Controller::loginWithAccessToken(QString serverAddr,
                                      QString user,
                                      QString token,
                                      QString deviceName) {
  if (user.isEmpty() || token.isEmpty()) {
    return;
  }

  QUrl serverUrl(serverAddr);

  auto conn = new Connection(this);
  if (serverUrl.isValid()) {
    conn->setHomeserver(serverUrl);
  }

  connect(conn, &Connection::connected, [=] {
    AccountSettings account(conn->userId());
    account.setKeepLoggedIn(true);
    account.clearAccessToken();  // Drop the legacy - just in case
    account.setHomeserver(conn->homeserver());
    account.setDeviceId(conn->deviceId());
    account.setDeviceName(deviceName);
    if (!saveAccessTokenToKeyChain(account, conn->accessToken()))
      qWarning() << "Couldn't save access token";
    account.sync();
    addConnection(conn);
    setConnection(conn);
  });
  connect(conn, &Connection::networkError,
          [=](QString error, QString, int, int) {
            emit errorOccured("Network Error", error);
          });
  conn->connectWithToken(user, token, deviceName);
}

void Controller::logout(Connection* conn) {
  if (!conn) {
    qCritical() << "Attempt to logout null connection";
    return;
  }

  SettingsGroup("Accounts").remove(conn->userId());
  QFile(accessTokenFileName(AccountSettings(conn->userId()))).remove();

  QKeychain::DeletePasswordJob job(qAppName());
  job.setAutoDelete(true);
  job.setKey(conn->userId());
  QEventLoop loop;
  QKeychain::DeletePasswordJob::connect(&job, &QKeychain::Job::finished, &loop,
                                        &QEventLoop::quit);
  job.start();
  loop.exec();

  auto logoutJob = conn->callApi<LogoutJob>();
  connect(logoutJob, &LogoutJob::finished, conn, [=] {
    conn->stopSync();
    emit conn->stateChanged();
    emit conn->loggedOut();
    if (!m_connections.isEmpty())
      setConnection(m_connections[0]);
  });
  connect(logoutJob, &LogoutJob::failure, this, [=] {
    emit errorOccured("Server-side Logout Failed", logoutJob->errorString());
  });
}

void Controller::addConnection(Connection* c) {
  Q_ASSERT_X(c, __FUNCTION__, "Attempt to add a null connection");

  m_connections += c;

  c->setLazyLoading(true);

  connect(c, &Connection::syncDone, this, [=] {
    setBusy(false);

    emit syncDone();

    c->sync(30000);
    c->saveState();
  });
  connect(c, &Connection::loggedOut, this, [=] { dropConnection(c); });
  connect(&m_ncm, &QNetworkConfigurationManager::onlineStateChanged,
          [=](bool status) {
            if (!status) {
              return;
            }

            c->stopSync();
            c->sync(30000);
          });

  using namespace Quotient;

  setBusy(true);

  c->sync();

  emit connectionAdded(c);
}

void Controller::dropConnection(Connection* c) {
  Q_ASSERT_X(c, __FUNCTION__, "Attempt to drop a null connection");
  m_connections.removeOne(c);

  emit connectionDropped(c);
  c->deleteLater();
}

void Controller::invokeLogin() {
  using namespace Quotient;
  const auto accounts = SettingsGroup("Accounts").childGroups();
  for (const auto& accountId : accounts) {
    AccountSettings account{accountId};
    if (!account.homeserver().isEmpty()) {
      auto accessToken = loadAccessTokenFromKeyChain(account);

      auto c = new Connection(account.homeserver(), this);
      auto deviceName = account.deviceName();
      connect(c, &Connection::connected, this, [=] {
        c->loadState();
        addConnection(c);
      });
      connect(c, &Connection::loginError, [=](QString error, QString) {
        emit errorOccured("Login Failed", error);
        logout(c);
      });
      connect(c, &Connection::networkError,
              [=](QString error, QString, int, int) {
                emit errorOccured("Network Error", error);
              });
      c->connectWithToken(account.userId(), accessToken, account.deviceId());
    }
  }

  if (!m_connections.isEmpty()) {
    setConnection(m_connections[0]);
  }

  emit initiated();
}

QByteArray Controller::loadAccessTokenFromFile(const AccountSettings& account) {
  QFile accountTokenFile{accessTokenFileName(account)};
  if (accountTokenFile.open(QFile::ReadOnly)) {
    if (accountTokenFile.size() < 1024)
      return accountTokenFile.readAll();

    qWarning() << "File" << accountTokenFile.fileName() << "is"
               << accountTokenFile.size()
               << "bytes long - too long for a token, ignoring it.";
  }
  qWarning() << "Could not open access token file"
             << accountTokenFile.fileName();

  return {};
}

QByteArray Controller::loadAccessTokenFromKeyChain(
    const AccountSettings& account) {
  qDebug() << "Read the access token from the keychain for "
           << account.userId();
  QKeychain::ReadPasswordJob job(qAppName());
  job.setAutoDelete(false);
  job.setKey(account.userId());
  QEventLoop loop;
  QKeychain::ReadPasswordJob::connect(&job, &QKeychain::Job::finished, &loop,
                                      &QEventLoop::quit);
  job.start();
  loop.exec();

  if (job.error() == QKeychain::Error::NoError) {
    return job.binaryData();
  }

  qWarning() << "Could not read the access token from the keychain: "
             << qPrintable(job.errorString());
  // no access token from the keychain, try token file
  auto accessToken = loadAccessTokenFromFile(account);
  if (job.error() == QKeychain::Error::EntryNotFound) {
    if (!accessToken.isEmpty()) {
      qDebug() << "Migrating the access token from file to the keychain for "
               << account.userId();
      bool removed = false;
      bool saved = saveAccessTokenToKeyChain(account, accessToken);
      if (saved) {
        QFile accountTokenFile{accessTokenFileName(account)};
        removed = accountTokenFile.remove();
      }
      if (!(saved && removed)) {
        qDebug() << "Migrating the access token from the file to the keychain "
                    "failed";
      }
    }
  }

  return accessToken;
}

bool Controller::saveAccessTokenToFile(const AccountSettings& account,
                                       const QByteArray& accessToken) {
  // (Re-)Make a dedicated file for access_token.
  QFile accountTokenFile{accessTokenFileName(account)};
  accountTokenFile.remove();  // Just in case

  auto fileDir = QFileInfo(accountTokenFile).dir();
  if (!((fileDir.exists() || fileDir.mkpath(".")) &&
        accountTokenFile.open(QFile::WriteOnly))) {
    emit errorOccured("I/O Denied", "Cannot save access token.");
  } else {
    accountTokenFile.write(accessToken);
    return true;
  }
  return false;
}

bool Controller::saveAccessTokenToKeyChain(const AccountSettings& account,
                                           const QByteArray& accessToken) {
  qDebug() << "Save the access token to the keychain for " << account.userId();
  QKeychain::WritePasswordJob job(qAppName());
  job.setAutoDelete(false);
  job.setKey(account.userId());
  job.setBinaryData(accessToken);
  QEventLoop loop;
  QKeychain::WritePasswordJob::connect(&job, &QKeychain::Job::finished, &loop,
                                       &QEventLoop::quit);
  job.start();
  loop.exec();

  if (job.error()) {
    qWarning() << "Could not save access token to the keychain: "
               << qPrintable(job.errorString());
    return saveAccessTokenToFile(account, accessToken);
  }

  return true;
}

void Controller::joinRoom(Connection* c, const QString& alias) {
  if (!alias.contains(":"))
    return;

  auto knownServer = alias.mid(alias.indexOf(":") + 1);
  auto joinRoomJob = c->joinRoom(alias, QStringList{knownServer});
  joinRoomJob->connect(joinRoomJob, &JoinRoomJob::failure, [=] {
    emit errorOccured("Join Room Failed", joinRoomJob->errorString());
  });
}

void Controller::createRoom(Connection* c,
                            const QString& name,
                            const QString& topic) {
  auto createRoomJob =
      c->createRoom(Connection::PublishRoom, "", name, topic, QStringList());
  createRoomJob->connect(createRoomJob, &CreateRoomJob::failure, [=] {
    emit errorOccured("Create Room Failed", createRoomJob->errorString());
  });
}

void Controller::createDirectChat(Connection* c, const QString& userID) {
  auto createRoomJob = c->createDirectChat(userID);
  createRoomJob->connect(createRoomJob, &CreateRoomJob::failure, [=] {
    emit errorOccured("Create Direct Chat Failed",
                      createRoomJob->errorString());
  });
}

void Controller::playAudio(QUrl localFile) {
  auto player = new QMediaPlayer;
  player->setMedia(localFile);
  player->play();
  connect(player, &QMediaPlayer::stateChanged, [=] { player->deleteLater(); });
}

void Controller::changeAvatar(Connection* conn, QUrl localFile) {
  auto job = conn->uploadFile(localFile.toLocalFile());
  if (isJobRunning(job)) {
    connect(job, &BaseJob::success, this, [conn, job] {
      conn->callApi<SetAvatarUrlJob>(conn->userId(), job->contentUri());
    });
  }
}

void Controller::markAllMessagesAsRead(Connection* conn) {
  for (auto room : conn->allRooms()) {
    room->markAllMessagesAsRead();
  }
}