-
Notifications
You must be signed in to change notification settings - Fork 682
/
Copy pathowncloudsetupwizard.cpp
485 lines (424 loc) · 19.7 KB
/
owncloudsetupwizard.cpp
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
/*
* Copyright (C) by Klaas Freitag <[email protected]>
* Copyright (C) by Krzesimir Nowak <[email protected]>
*
* 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 2 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.
*/
#include <QAbstractButton>
#include <QtCore>
#include <QProcess>
#include <QMessageBox>
#include <QDesktopServices>
#include <QApplication>
#include "wizard/owncloudwizardcommon.h"
#include "wizard/owncloudwizard.h"
#include "owncloudsetupwizard.h"
#include "configfile.h"
#include "folderman.h"
#include "accessmanager.h"
#include "account.h"
#include "networkjobs.h"
#include "sslerrordialog.h"
#include "accountmanager.h"
#include "clientproxy.h"
#include "filesystem.h"
#include "owncloudgui.h"
#include "settingsdialog.h"
#include "creds/dummycredentials.h"
#include <graphapi/drives.h>
using namespace std::chrono_literals;
namespace OCC {
OwncloudSetupWizard::OwncloudSetupWizard(QWidget *parent)
: QObject(parent)
, _ocWizard(new OwncloudWizard(parent))
{
connect(_ocWizard, &OwncloudWizard::determineAuthType,
this, &OwncloudSetupWizard::slotCheckServer);
connect(_ocWizard, &OwncloudWizard::connectToOCUrl,
this, &OwncloudSetupWizard::slotConnectToOCUrl);
connect(_ocWizard, &OwncloudWizard::createLocalAndRemoteFolders,
this, &OwncloudSetupWizard::slotCreateLocalAndRemoteFolders);
/* basicSetupFinished might be called from a reply from the network.
slotAssistantFinished might destroy the temporary QNetworkAccessManager.
Therefore Qt::QueuedConnection is required */
connect(_ocWizard, &OwncloudWizard::basicSetupFinished,
this, &OwncloudSetupWizard::slotAssistantFinished, Qt::QueuedConnection);
connect(_ocWizard, &OwncloudWizard::finished, this, &QObject::deleteLater);
}
OwncloudSetupWizard::~OwncloudSetupWizard()
{
_ocWizard->deleteLater();
}
void OwncloudSetupWizard::startWizard()
{
AccountPtr account = AccountManager::createAccount();
account->setCredentials(new DummyCredentials);
account->setUrl(Theme::instance()->overrideServerUrlV2());
_ocWizard->setAccount(account);
_ocWizard->setOCUrl(account->url().toString());
_ocWizard->setStartId(WizardCommon::Page_ServerSetup);
_ocWizard->restart();
_ocWizard->open();
ownCloudGui::raiseDialog(_ocWizard);
}
// also checks if an installation is valid and determines auth type in a second step
void OwncloudSetupWizard::slotCheckServer(const QString &urlString)
{
QString fixedUrl = urlString;
QUrl url = QUrl::fromUserInput(fixedUrl);
// fromUserInput defaults to http, not http if no scheme is specified
if (!fixedUrl.startsWith("http://") && !fixedUrl.startsWith("https://")) {
url.setScheme("https");
}
AccountPtr account = _ocWizard->account();
account->setUrl(url);
// Reset the proxy which might had been determined previously in ConnectionValidator::checkServerAndAuth()
// when there was a previous account.
account->networkAccessManager()->setProxy(QNetworkProxy(QNetworkProxy::NoProxy));
// And also reset the QSslConfiguration, for the same reason (#6832)
// Here the client certificate is added, if any. Later it'll be in HttpCredentials
account->setSslConfiguration(QSslConfiguration());
auto sslConfiguration = account->getOrCreateSslConfig(); // let Account set defaults
account->setSslConfiguration(sslConfiguration);
// Make sure TCP connections get re-established
account->networkAccessManager()->clearAccessCache();
// Lookup system proxy in a thread https://github.com/owncloud/client/issues/2993
if (ClientProxy::isUsingSystemDefault()) {
qCDebug(lcWizard) << "Trying to look up system proxy";
ClientProxy::lookupSystemProxyAsync(account->url(),
this, SLOT(slotSystemProxyLookupDone(QNetworkProxy)));
} else {
// We want to reset the QNAM proxy so that the global proxy settings are used (via ClientProxy settings)
account->networkAccessManager()->setProxy(QNetworkProxy(QNetworkProxy::DefaultProxy));
// use a queued invocation so we're as asynchronous as with the other code path
QMetaObject::invokeMethod(this, &OwncloudSetupWizard::slotFindServer, Qt::QueuedConnection);
}
}
void OwncloudSetupWizard::slotSystemProxyLookupDone(const QNetworkProxy &proxy)
{
if (proxy.type() != QNetworkProxy::NoProxy) {
qCInfo(lcWizard) << "Setting QNAM proxy to be system proxy" << printQNetworkProxy(proxy);
} else {
qCInfo(lcWizard) << "No system proxy set by OS";
}
AccountPtr account = _ocWizard->account();
account->networkAccessManager()->setProxy(proxy);
slotFindServer();
}
void OwncloudSetupWizard::slotFindServer()
{
AccountPtr account = _ocWizard->account();
// Set fake credentials before we check what credential it actually is.
account->setCredentials(new DummyCredentials);
// Determining the actual server URL can be a multi-stage process
// 1. Check url/status.php with CheckServerJob
// If that works we're done. In that case we don't check the
// url directly for redirects, see #5954.
// 2. Check the url for permanent redirects (like url shorteners)
// 3. Check redirected-url/status.php with CheckServerJob
// Step 1: Check url/status.php
CheckServerJob *job = new CheckServerJob(account, this);
connect(job, &CheckServerJob::instanceFound, this, &OwncloudSetupWizard::slotFoundServer);
connect(job, &CheckServerJob::timeout, this, &OwncloudSetupWizard::slotNoServerFoundTimeout);
connect(job, &CheckServerJob::instanceNotFound, this, &OwncloudSetupWizard::slotNoServerFound);
job->setTimeout((account->url().scheme() == "https") ? 30s : 10s);
job->start();
}
void OwncloudSetupWizard::slotFoundServer(const QUrl &url, const QJsonObject &info)
{
auto serverVersion = CheckServerJob::version(info);
qCDebug(lcWizard) << "Successfully connected to" << url.toString() << "version" << CheckServerJob::versionString(info) << "(" << serverVersion << ")";
// Note with newer servers we get the version actually only later in capabilities
// https://github.com/owncloud/core/pull/27473/files
_ocWizard->account()->setServerVersion(serverVersion);
const auto oldUrl = _ocWizard->account()->url();
if (oldUrl != url) {
qCInfo(lcWizard) << oldUrl << "was redirected to" << url;
if (url.scheme() == QLatin1String("https") && oldUrl.host() == url.host()) {
_ocWizard->account()->setUrl(url);
} else {
// the account state is only used for a quick moment to handle the URL change, and needs to be cleaned up immediately once finished
auto accountState = AccountState::fromNewAccount(_ocWizard->account()).take();
connect(accountState, &AccountState::urlUpdated, this, &OwncloudSetupWizard::slotDetermineAuthType);
auto dialog = accountState->updateUrlDialog(url);
Q_ASSERT(dialog != nullptr);
connect(dialog, &UpdateUrlDialog::finished, accountState, &AccountState::deleteLater);
return;
}
}
slotDetermineAuthType();
}
void OwncloudSetupWizard::slotNoServerFound(QNetworkReply *)
{
auto job = qobject_cast<CheckServerJob *>(sender());
// Do this early because reply might be deleted in message box event loop
QString msg;
if (!_ocWizard->account()->url().isValid()) {
msg = tr("Invalid URL");
} else {
msg = tr("Failed to connect to %1 at %2:<br/>%3")
.arg(Utility::escape(Theme::instance()->appNameGUI()),
Utility::escape(_ocWizard->account()->url().toString()),
Utility::escape(job->errorString()));
}
// Displays message inside wizard and possibly also another message box
_ocWizard->displayError(msg);
// Allow the credentials dialog to pop up again for the same URL.
// Maybe the user just clicked 'Cancel' by accident or changed his mind.
_ocWizard->account()->resetRejectedCertificates();
}
void OwncloudSetupWizard::slotNoServerFoundTimeout(const QUrl &url)
{
_ocWizard->displayError(
tr("Timeout while trying to connect to %1 at %2.")
.arg(Utility::escape(Theme::instance()->appNameGUI()), Utility::escape(url.toString())));
}
void OwncloudSetupWizard::slotDetermineAuthType()
{
DetermineAuthTypeJob *job = new DetermineAuthTypeJob(_ocWizard->account(), this);
connect(job, &DetermineAuthTypeJob::authType,
_ocWizard, &OwncloudWizard::setAuthType);
job->start();
}
void OwncloudSetupWizard::slotConnectToOCUrl(const QString &url)
{
qCInfo(lcWizard) << "Connect to url: " << url;
AbstractCredentials *creds = _ocWizard->getCredentials();
_ocWizard->account()->setCredentials(creds);
_ocWizard->setField(QLatin1String("OCUrl"), url);
qCDebug(lcWizard) << "Trying to connect to" << url;
testOwnCloudConnect();
}
void OwncloudSetupWizard::testOwnCloudConnect()
{
auto job = new ConnectionValidator(_ocWizard->account(), this);
connect(job, &ConnectionValidator::connectionResult, this, [this](ConnectionValidator::Status status, const QStringList &errors){
qDebug() << status;
if (status == ConnectionValidator::Connected) {
_ocWizard->successfulStep();
return;
}
_ocWizard->show();
if (_ocWizard->currentId() == WizardCommon::Page_OAuthCreds) {
_ocWizard->back();
}
_ocWizard->displayError(errors.join(QLatin1Char('\n')));
});
job->checkServerAndUpdate();
}
void OwncloudSetupWizard::slotCreateLocalAndRemoteFolders()
{
qCInfo(lcWizard) << "Setup local sync folder for new oC connection " << _ocWizard->localFolder();
const QDir fi(_ocWizard->localFolder());
bool nextStep = true;
if (fi.exists()) {
FileSystem::setFolderMinimumPermissions(_ocWizard->localFolder());
Utility::setupFavLink(_ocWizard->localFolder());
// there is an existing local folder. If its non empty, it can only be synced if the
// ownCloud is newly created.
qCDebug(lcWizard) << "Local sync folder" << _ocWizard->localFolder() << "already exists, setting it up for sync.";
} else {
bool ok = true;
if (fi.mkpath(_ocWizard->localFolder())) {
FileSystem::setFolderMinimumPermissions(_ocWizard->localFolder());
Utility::setupFavLink(_ocWizard->localFolder());
} else {
ok = false;
qCWarning(lcWizard) << "Failed to create " << fi.path();
_ocWizard->displayError(tr("Could not create local folder %1").arg(Utility::escape(_ocWizard->localFolder())));
nextStep = false;
}
qCDebug(lcWizard) << "Creating local sync folder" << _ocWizard->localFolder() << "success:" << ok;
}
if (nextStep) {
// TODO: legacy
EntityExistsJob *job = new EntityExistsJob(_ocWizard->account(), _ocWizard->account()->davUrl(), _ocWizard->remoteFolder(), this);
connect(job, &EntityExistsJob::exists, this, &OwncloudSetupWizard::slotRemoteFolderExists);
job->start();
} else {
finalizeSetup(false);
}
}
// ### TODO move into EntityExistsJob once we decide if/how to return gui strings from jobs
void OwncloudSetupWizard::slotRemoteFolderExists(QNetworkReply *reply)
{
auto job = qobject_cast<EntityExistsJob *>(sender());
bool ok = true;
QString error;
QNetworkReply::NetworkError errId = reply->error();
if (errId == QNetworkReply::NoError) {
qCInfo(lcWizard) << "Remote folder found, all cool!";
} else if (errId == QNetworkReply::ContentNotFoundError) {
createRemoteFolder();
} else {
error = tr("Error: %1").arg(job->errorString());
ok = false;
}
if (!ok) {
_ocWizard->displayError(Utility::escape(error));
}
finalizeSetup(ok);
}
void OwncloudSetupWizard::createRemoteFolder()
{
qCDebug(lcWizard) << "creating folder on ownCloud:" << _ocWizard->remoteFolder();
// TODO: legacy
MkColJob *job = new MkColJob(_ocWizard->account(), _ocWizard->account()->davUrl(), _ocWizard->remoteFolder(), {}, this);
connect(job, &MkColJob::finishedWithError, this, &OwncloudSetupWizard::slotCreateRemoteFolderFinished);
connect(job, &MkColJob::finishedWithoutError, this, [this] {
qCDebug(lcWizard) << "Remote folder" << _ocWizard->remoteFolder() << "created successfully.";
finalizeSetup(true);
});
job->start();
}
void OwncloudSetupWizard::slotCreateRemoteFolderFinished(QNetworkReply *reply)
{
auto error = reply->error();
qCDebug(lcWizard) << "** webdav mkdir request finished " << error;
bool success = true;
if (error == 202) {
qCDebug(lcWizard) << "The remote folder" << _ocWizard->remoteFolder() << "already exists. Connecting it for syncing.";
} else if (error > 202 && error < 300) {
_ocWizard->displayError(tr("The folder creation resulted in HTTP error code %1").arg((int)error));
qCDebug(lcWizard) << "The folder creation resulted in HTTP error code" << error;
} else if (error == QNetworkReply::OperationCanceledError) {
_ocWizard->displayError(tr("The remote folder creation failed because the provided credentials "
"are wrong!"
"<br/>Please go back and check your credentials.</p>"));
qCDebug(lcWizard) << "Remote folder creation failed probably because the provided credentials are wrong. Please go back and check your credentials.";
_ocWizard->resetRemoteFolder();
success = false;
} else {
qCDebug(lcWizard) << "Remote folder" << _ocWizard->remoteFolder() << "creation failed with error" << error;
_ocWizard->displayError(tr("Remote folder %1 creation failed with error <tt>%2</tt>.").arg(Utility::escape(_ocWizard->remoteFolder())).arg(error));
_ocWizard->resetRemoteFolder();
success = false;
}
finalizeSetup(success);
}
void OwncloudSetupWizard::finalizeSetup(bool success)
{
const QString localFolder = _ocWizard->localFolder();
if (success) {
qCDebug(lcWizard) << "A sync connection from" << localFolder << "to remote directory" << _ocWizard->remoteFolder() << "was set up.";
qCDebug(lcWizard) << "Successfully connected";
_ocWizard->successfulStep();
} else {
// ### this is not quite true, pass in the real problem as optional parameter
qCDebug(lcWizard) << "Connection could not be established. Please check again.";
}
}
bool OwncloudSetupWizard::ensureStartFromScratch(const QString &localFolder)
{
// first try to rename (backup) the current local dir.
bool renameOk = false;
while (!renameOk) {
renameOk = FolderMan::instance()->startFromScratch(localFolder);
if (!renameOk) {
QMessageBox::StandardButton but;
but = QMessageBox::question(nullptr, tr("Folder rename failed"),
tr("Can't remove and back up the folder because the folder or a file in it is open in another program."
" Please close the folder or file and hit retry or cancel the setup."),
QMessageBox::Retry | QMessageBox::Abort, QMessageBox::Retry);
if (but == QMessageBox::Abort) {
break;
}
}
}
return renameOk;
}
void OwncloudSetupWizard::addFolder(AccountStatePtr account, const QString &localFolder, const QString &remotePath, const QUrl &webDavUrl)
{
FolderMan *folderMan = FolderMan::instance();
qCInfo(lcWizard) << "Adding folder definition for" << localFolder << remotePath;
FolderDefinition folderDefinition(webDavUrl);
folderDefinition.setLocalPath(localFolder);
folderDefinition.setTargetPath(remotePath);
folderDefinition.ignoreHiddenFiles = folderMan->ignoreHiddenFiles();
if (_ocWizard->useVirtualFileSync()) {
folderDefinition.virtualFilesMode = bestAvailableVfsMode();
}
#ifdef Q_OS_WIN
if (folderMan->navigationPaneHelper().showInExplorerNavigationPane())
folderDefinition.navigationPaneClsid = QUuid::createUuid();
#endif
auto f = folderMan->addFolder(account, folderDefinition);
if (f) {
if (folderDefinition.virtualFilesMode != Vfs::Off && _ocWizard->useVirtualFileSync())
f->setRootPinState(PinState::OnlineOnly);
f->journalDb()->setSelectiveSyncList(SyncJournalDb::SelectiveSyncBlackList,
_ocWizard->selectiveSyncBlacklist());
if (!_ocWizard->isConfirmBigFolderChecked()) {
// The user already accepted the selective sync dialog. everything is in the white list
f->journalDb()->setSelectiveSyncList(SyncJournalDb::SelectiveSyncWhiteList,
QStringList() << QLatin1String("/"));
}
qCDebug(lcWizard) << "Local sync folder" << localFolder << "successfully created!";
} else {
qCWarning(lcWizard) << "Failed to create local sync folder!";
}
}
// Method executed when the user end has finished the basic setup.
void OwncloudSetupWizard::slotAssistantFinished(int result)
{
if (result == QDialog::Rejected) {
// Wizard was cancelled
} else if (_ocWizard->manualFolderConfig()) {
applyAccountChanges();
} else {
const QString localFolder = _ocWizard->localFolder();
bool startFromScratch = _ocWizard->field("OCSyncFromScratch").toBool();
if (!startFromScratch || ensureStartFromScratch(localFolder)) {
auto account = applyAccountChanges();
if (account->account()->capabilities().spacesSupport().enabled) {
auto *drive = new OCC::GraphApi::Drives(account->account());
connect(drive, &OCC::GraphApi::Drives::finishedSignal, [account, localFolder, result, drive, this] {
if (drive->parseError().error == QJsonParseError::NoError) {
const auto &drives = drive->drives();
if (!drives.isEmpty()) {
const QDir localDir(localFolder);
localDir.mkdir(".");
for (const auto &d : drives) {
const QDir driveLocalFolder = localDir.filePath(d.getName());
driveLocalFolder.mkdir(".");
addFolder(account, driveLocalFolder.absolutePath(), {}, QUrl::fromEncoded(d.getRoot().getWebDavUrl().toUtf8()));
}
}
}
// notify others.
emit ownCloudWizardDone(result);
});
drive->start();
return;
} else {
addFolder(account, localFolder, _ocWizard->remoteFolder(), account->account()->davUrl());
}
} else {
qCWarning(lcWizard) << "Failed to create local sync folder!";
}
}
// notify others.
emit ownCloudWizardDone(result);
}
AccountStatePtr OwncloudSetupWizard::applyAccountChanges()
{
AccountPtr newAccount = _ocWizard->account();
// Detach the account that is going to be saved from the
// wizard to ensure it doesn't accidentally get modified
// later (such as from running cleanup such as
// AbstractCredentialsWizardPage::cleanupPage())
_ocWizard->setAccount(AccountManager::createAccount());
auto manager = AccountManager::instance();
auto newState = manager->addAccount(newAccount);
manager->save();
return newState;
}
} // namespace OCC