# For details see the accompanying COPYING* file.
if (CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang")
- set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -pedantic -Wno-long-long")
+ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -pedantic -Wno-long-long -Wno-gnu-zero-variadic-macro-arguments")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x")
if (CMAKE_CXX_COMPILER_ID MATCHES "GNU")
namespace OCC {
+Q_LOGGING_CATEGORY(lcAccountManager, "gui.account.manager", QtInfoMsg)
+
AccountManager *AccountManager::instance()
{
static AccountManager instance;
{
auto settings = Utility::settingsWithGroup(QLatin1String(accountsC));
if (settings->status() != QSettings::NoError) {
- qDebug() << "Could not read settings from" << settings->fileName()
+ qCDebug(lcAccountManager) << "Could not read settings from" << settings->fileName()
<< settings->status();
return false;
}
bool AccountManager::restoreFromLegacySettings()
{
- qDebug() << "Migrate: restoreFromLegacySettings, checking settings group"
+ qCDebug(lcAccountManager) << "Migrate: restoreFromLegacySettings, checking settings group"
<< Theme::instance()->appName();
// try to open the correctly themed settings
oCCfgFile = oCCfgFile.left( oCCfgFile.lastIndexOf('/'));
oCCfgFile += QLatin1String("/ownCloud/owncloud.cfg");
- qDebug() << "Migrate: checking old config " << oCCfgFile;
+ qCDebug(lcAccountManager) << "Migrate: checking old config " << oCCfgFile;
QFileInfo fi( oCCfgFile );
if( fi.isReadable() ) {
// in case the urls are equal reset the settings object to read from
// the ownCloud settings object
- qDebug() << "Migrate oC config if " << oCUrl << " == " << overrideUrl << ":"
+ qCDebug(lcAccountManager) << "Migrate oC config if " << oCUrl << " == " << overrideUrl << ":"
<< (oCUrl == overrideUrl ? "Yes" : "No");
if( oCUrl == overrideUrl ) {
settings = std::move(oCSettings);
}
settings->sync();
- qDebug() << "Saved all account settings, status:" << settings->status();
+ qCDebug(lcAccountManager) << "Saved all account settings, status:" << settings->status();
}
void AccountManager::saveAccount(Account* a)
{
- qDebug() << "Saving account" << a->url().toString();
+ qCDebug(lcAccountManager) << "Saving account" << a->url().toString();
auto settings = Utility::settingsWithGroup(QLatin1String(accountsC));
settings->beginGroup(a->id());
saveAccountHelper(a, *settings, false); // don't save credentials they might not have been loaded yet
settings->endGroup();
settings->sync();
- qDebug() << "Saved account settings, status:" << settings->status();
+ qCDebug(lcAccountManager) << "Saved account settings, status:" << settings->status();
}
void AccountManager::saveAccountState(AccountState* a)
{
- qDebug() << "Saving account state" << a->account()->url().toString();
+ qCDebug(lcAccountManager) << "Saving account state" << a->account()->url().toString();
auto settings = Utility::settingsWithGroup(QLatin1String(accountsC));
settings->beginGroup(a->account()->id());
a->writeToSettings(*settings);
settings->endGroup();
settings->sync();
- qDebug() << "Saved account state settings, status:" << settings->status();
+ qCDebug(lcAccountManager) << "Saved account state settings, status:" << settings->status();
}
void AccountManager::saveAccountHelper(Account* acc, QSettings& settings, bool saveCredentials)
// Save accepted certificates.
settings.beginGroup(QLatin1String("General"));
- qDebug() << "Saving " << acc->approvedCerts().count() << " unknown certs.";
+ qCDebug(lcAccountManager) << "Saving " << acc->approvedCerts().count() << " unknown certs.";
QByteArray certs;
Q_FOREACH( const QSslCertificate& cert, acc->approvedCerts() ) {
certs += cert.toPem() + '\n';
if (acc->_am) {
CookieJar* jar = qobject_cast<CookieJar*>(acc->_am->cookieJar());
if (jar) {
- qDebug() << "Saving cookies." << acc->cookieJarPath();
+ qCDebug(lcAccountManager) << "Saving cookies." << acc->cookieJarPath();
jar->save(acc->cookieJarPath());
}
}
auto urlConfig = settings.value(QLatin1String(urlC));
if (!urlConfig.isValid()) {
// No URL probably means a corrupted entry in the account settings
- qDebug() << "No URL for account " << settings.group();
+ qCDebug(lcAccountManager) << "No URL for account " << settings.group();
return AccountPtr();
}
acc->setUrl(urlConfig.toUrl());
}
- qDebug() << "Account for" << acc->url() << "using auth type" << authType;
+ qCDebug(lcAccountManager) << "Account for" << acc->url() << "using auth type" << authType;
acc->_serverVersion = settings.value(QLatin1String(serverVersionC)).toString();
#include <math.h>
-#include <QDebug>
#include <QDesktopServices>
#include <QDir>
#include <QListWidgetItem>
namespace OCC {
+Q_LOGGING_CATEGORY(lcAccountSettings, "gui.account.settings", QtInfoMsg)
+
static const char progressBarStyleC[] =
"QProgressBar {"
"border: 1px solid grey;"
topLevelWidget()->close();
}
#ifdef Q_OS_MAC
- qDebug() << parent() << topLevelWidget();
+ qCDebug(lcAccountSettings) << parent() << topLevelWidget();
SettingsDialogMac *sd = qobject_cast<SettingsDialogMac*>(topLevelWidget());
if (sd) {
FolderWizard *folderWizard = qobject_cast<FolderWizard*>(sender());
FolderMan *folderMan = FolderMan::instance();
- qDebug() << "* Folder wizard completed";
+ qCDebug(lcAccountSettings) << "* Folder wizard completed";
FolderDefinition definition;
definition.localPath = FolderDefinition::prepareLocalPath(
{
QDir dir(definition.localPath);
if (!dir.exists()) {
- qDebug() << "Creating folder" << definition.localPath;
+ qCDebug(lcAccountSettings) << "Creating folder" << definition.localPath;
if (!dir.mkpath(".")) {
QMessageBox::warning(this, tr("Folder creation failed"),
tr("<p>Could not create local folder <i>%1</i>.")
void AccountSettings::slotFolderWizardRejected()
{
- qDebug() << "* Folder wizard cancelled";
+ qCDebug(lcAccountSettings) << "* Folder wizard cancelled";
FolderMan *folderMan = FolderMan::instance();
folderMan->setSyncEnabled(true);
}
if( selected.isValid() && folder ) {
int row = selected.row();
- qDebug() << "Remove Folder alias " << folder->alias();
+ qCDebug(lcAccountSettings) << "Remove Folder alias " << folder->alias();
QString shortGuiLocalPath = folder->shortGuiLocalPath();
QMessageBox messageBox(QMessageBox::Question,
} else {
errors.prepend(message);
const QString msg = errors.join(QLatin1String("\n"));
- qDebug() << msg;
+ qCDebug(lcAccountSettings) << msg;
ui->connectLabel->setText( msg );
ui->connectLabel->setToolTip(QString());
ui->connectLabel->setStyleSheet(errStyle);
if( !alias.isEmpty() ) {
FolderMan *folderMan = FolderMan::instance();
- qDebug() << "Application: enable folder with alias " << alias;
+ qCDebug(lcAccountSettings) << "Application: enable folder with alias " << alias;
bool terminate = false;
bool currentlyPaused = false;
ui->_folderList->setCurrentIndex(indx);
ui->_folderList->scrollTo(indx);
} else {
- qDebug() << "Unable to find a valid index for " << myFolder;
+ qCDebug(lcAccountSettings) << "Unable to find a valid index for " << myFolder;
}
}
}
#include "logger.h"
#include "configfile.h"
-#include <QDebug>
#include <QSettings>
#include <qfontmetrics.h>
namespace OCC {
+Q_LOGGING_CATEGORY(lcAccountState, "gui.account.state", QtInfoMsg)
+
AccountState::AccountState(AccountPtr account)
: QObject()
, _account(account)
void AccountState::setState(State state)
{
if (_state != state) {
- qDebug() << "AccountState state change: "
+ qCDebug(lcAccountState) << "AccountState state change: "
<< stateString(_state) << "->" << stateString(state);
State oldState = _state;
_state = state;
}
if (_connectionValidator) {
- qDebug() << "ConnectionValidator already running, ignoring" << account()->displayName();
+ qCDebug(lcAccountState) << "ConnectionValidator already running, ignoring" << account()->displayName();
return;
}
if (isConnected() && _timeSinceLastETagCheck.isValid()
&& _timeSinceLastETagCheck.elapsed() < polltime) {
- //qDebug() << account()->displayName() << "The last ETag check succeeded within the last " << polltime/1000 << " secs. No connection check needed!";
+ //qCDebug(lcAccountState) << account()->displayName() << "The last ETag check succeeded within the last " << polltime/1000 << " secs. No connection check needed!";
return;
}
void AccountState::slotConnectionValidatorResult(ConnectionValidator::Status status, const QStringList& errors)
{
if (isSignedOut()) {
- qDebug() << "Signed out, ignoring" << connectionStatusString(status) << _account->url().toString();
+ qCDebug(lcAccountState) << "Signed out, ignoring" << connectionStatusString(status) << _account->url().toString();
return;
}
if (_connectionStatus != status) {
- qDebug() << "AccountState connection status change: "
+ qCDebug(lcAccountState) << "AccountState connection status change: "
<< connectionStatusString(_connectionStatus) << "->"
<< connectionStatusString(status);
_connectionStatus = status;
namespace OCC {
+Q_LOGGING_CATEGORY(lcActivity, "gui.activity", QtInfoMsg)
+
ActivityListModel::ActivityListModel(QWidget *parent)
:QAbstractListModel(parent)
{
job->addQueryParams(params);
_currentlyFetching.insert(s);
- qDebug() << Q_FUNC_INFO << "Start fetching activities for " << s->account()->displayName();
+ qCDebug(lcActivity) << "Start fetching activities for " << s->account()->displayName();
job->start();
}
namespace OCC {
+Q_DECLARE_LOGGING_CATEGORY(lcActivity)
+
class AccountState;
/**
namespace OCC {
-/* ==================================================================== */
-
ActivityWidget::ActivityWidget(QWidget *parent) :
QWidget(parent),
_ui(new Ui::ActivityWidget),
snh->slotFetchNotifications(ptr);
} else {
- qDebug() << Q_FUNC_INFO << "========> notification request counter not zero.";
+ qCDebug(lcActivity) << "========> notification request counter not zero.";
}
}
void ActivityWidget::slotOpenFile(QModelIndex indx)
{
- qDebug() << Q_FUNC_INFO << indx.isValid() << indx.data(ActivityItemDelegate::PathRole).toString() << QFile::exists(indx.data(ActivityItemDelegate::PathRole).toString());
+ qCDebug(lcActivity) << indx.isValid() << indx.data(ActivityItemDelegate::PathRole).toString() << QFile::exists(indx.data(ActivityItemDelegate::PathRole).toString());
if( indx.isValid() ) {
QString fullPath = indx.data(ActivityItemDelegate::PathRole).toString();
foreach( auto activity, list ) {
if( _blacklistedNotifications.contains(activity)) {
- qDebug() << Q_FUNC_INFO << "Activity in blacklist, skip";
+ qCDebug(lcActivity) << "Activity in blacklist, skip";
continue;
}
void ActivityWidget::slotSendNotificationRequest(const QString& accountName, const QString& link, const QByteArray& verb)
{
- qDebug() << Q_FUNC_INFO << "Server Notification Request " << verb << link << "on account" << accountName;
+ qCDebug(lcActivity) << "Server Notification Request " << verb << link << "on account" << accountName;
NotificationWidget *theSender = qobject_cast<NotificationWidget*>(sender());
const QStringList validVerbs = QStringList() << "GET" << "PUT" << "POST" << "DELETE";
_notificationRequestsRunning++;
}
} else {
- qDebug() << Q_FUNC_INFO << "Notification Links: Invalid verb:" << verb;
+ qCDebug(lcActivity) << "Notification Links: Invalid verb:" << verb;
}
}
int resultCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
endNotificationRequest(job->widget(), resultCode);
- qDebug() << Q_FUNC_INFO << "Server notify job failed with code " << resultCode;
+ qCDebug(lcActivity) << "Server notify job failed with code " << resultCode;
}
endNotificationRequest(job->widget(), replyCode);
// FIXME: remove the widget after a couple of seconds
- qDebug() << Q_FUNC_INFO << "Server Notification reply code"<< replyCode << reply;
+ qCDebug(lcActivity) << "Server Notification reply code"<< replyCode << reply;
// if the notification was successful start a timer that triggers
// removal of the done widgets in a few seconds
void ActivitySettings::setNotificationRefreshInterval( quint64 interval )
{
- qDebug() << "Starting Notification refresh timer with " << interval/1000 << " sec interval";
+ qCDebug(lcActivity) << "Starting Notification refresh timer with " << interval/1000 << " sec interval";
_notificationCheckTimer.start(interval);
}
// Fetch Activities only if visible and if last check is longer than 15 secs ago
if( timer.isValid() && timer.elapsed() < NOTIFICATION_REQUEST_FREE_PERIOD ) {
- qDebug() << Q_FUNC_INFO << "do not check as last check is only secs ago: " << timer.elapsed() / 1000;
+ qCDebug(lcActivity) << "do not check as last check is only secs ago: " << timer.elapsed() / 1000;
return;
}
if( ptr && ptr->isConnected() ) {
namespace OCC {
+Q_LOGGING_CATEGORY(lcApplication, "gui.application", QtInfoMsg)
+
namespace {
static const char optionsC[] =
QString devTrPath = qApp->applicationDirPath() + QString::fromLatin1("/../src/gui/");
if (QDir(devTrPath).exists()) {
// might miss Qt, QtKeyChain, etc.
- qDebug() << "Running from build location! Translations may be incomplete!";
+ qCDebug(lcApplication) << "Running from build location! Translations may be incomplete!";
return devTrPath;
}
#if defined(Q_OS_WIN)
setupTranslations();
// Setup global excludes
- qDebug() << "Loading global exclude list";
+ qCDebug(lcApplication) << "Loading global exclude list";
ConfigFile cfg;
ExcludedFiles& excludes = ExcludedFiles::instance();
excludes.addExcludeFilePath( cfg.excludeFile(ConfigFile::SystemScope) );
// (non-existence is not an error)
Utility::sleep(5);
if (!AccountManager::instance()->restore()) {
- qDebug() << "Could not read the account settings, quitting";
+ qCDebug(lcApplication) << "Could not read the account settings, quitting";
QMessageBox::critical(
0,
tr("Error accessing the configuration file"),
void Application::slotSystemOnlineConfigurationChanged(QNetworkConfiguration cnf)
{
if (cnf.state() & QNetworkConfiguration::Active) {
- //qDebug() << "Trying fast reconnect";
QMetaObject::invokeMethod(this, "slotCheckConnection", Qt::QueuedConnection);
}
}
Logger::instance()->enterNextLogFile();
- qDebug() << QString::fromLatin1( "################## %1 %2 (%3) %4 on %5").arg(_theme->appName())
+ qCDebug(lcApplication) << QString::fromLatin1( "################## %1 %2 (%3) %4 on %5").arg(_theme->appName())
.arg( QLocale::system().name() )
.arg(property("ui_lang").toString())
.arg(_theme->version())
parseOptions(options);
setupLogging();
} else if (msg.startsWith(QLatin1String("MSG_SHOWSETTINGS"))) {
- qDebug() << "Running for" << _startedAt.elapsed()/1000.0 << "sec";
+ qCDebug(lcApplication) << "Running for" << _startedAt.elapsed()/1000.0 << "sec";
if (_startedAt.elapsed() < 10*1000) {
// This call is mirrored with the one in int main()
- qWarning() << "Ignoring MSG_SHOWSETTINGS, possibly double-invocation of client via session restore and auto start";
+ qCWarning(lcApplication) << "Ignoring MSG_SHOWSETTINGS, possibly double-invocation of client via session restore and auto start";
return;
}
showSettingsDialog();
// for us to accept the language. Otherwise, we try with the next.
// "en" is an exception as it is the default language and may not
// have a translation file provided.
- qDebug() << Q_FUNC_INFO << "Using" << lang << "translation";
+ qCDebug(lcApplication) << "Using" << lang << "translation";
setProperty("ui_lang", lang);
const QString qtTrPath = QLibraryInfo::location(QLibraryInfo::TranslationsPath);
const QString qtTrFile = QLatin1String("qt_") + lang;
}
namespace OCC {
+
+Q_DECLARE_LOGGING_CATEGORY(lcApplication)
+
class Theme;
class Folder;
class SslErrorDialog;
#include <QString>
-#include <QDebug>
#import <Cocoa/Cocoa.h>
namespace OCC {
// https://github.com/owncloud/client/issues/3300
void copyToPasteboard(const QString &string)
{
- qDebug() << Q_FUNC_INFO << string;
[[NSPasteboard generalPasteboard] clearContents];
[[NSPasteboard generalPasteboard] setString:[NSString stringWithUTF8String:string.toUtf8().data()]
forType:NSStringPboardType];
* for more details.
*/
+#include <QLoggingCategory>
#include <QString>
#include "creds/credentialsfactory.h"
namespace OCC
{
+Q_LOGGING_CATEGORY(lcGuiCredentials, "gui.credentials", QtInfoMsg)
+
namespace CredentialsFactory
{
return new ShibbolethCredentials;
#endif
} else {
- qWarning("Unknown credentials type: %s", qPrintable(type));
+ qCWarning(lcGuiCredentials, "Unknown credentials type: %s", qPrintable(type));
return new DummyCredentials;
}
}
#include <QJsonDocument>
#include <QJsonObject>
+#include <QLoggingCategory>
namespace OCC {
+Q_DECLARE_LOGGING_CATEGORY(lcShibboleth)
+
ShibbolethUserJob::ShibbolethUserJob(AccountPtr account, QObject* parent)
: JsonApiJob(account, QLatin1String("ocs/v1.php/cloud/user"), parent)
{
void ShibbolethUserJob::slotJsonReceived(const QJsonDocument &json, int statusCode)
{
if( statusCode != 100 ) {
- qWarning() << "JSON Api call resulted in status code != 100";
+ qCWarning(lcShibboleth) << "JSON Api call resulted in status code != 100";
}
QString user = json.object().value("ocs").toObject().value("data").toObject().value("id").toString();
- //qDebug() << "cloud/user: " << json << "->" << user;
emit userFetched(user);
}
*/
#include <QApplication>
-#include <QDebug>
#include <QNetworkCookie>
#include <QNetworkCookieJar>
#include <QWebFrame>
}
if (!success) {
- qDebug() << Q_FUNC_INFO << "Could not load Shibboleth login page to log you in.";
+ qCDebug(lcShibboleth) << "Could not load Shibboleth login page to log you in.";
}
}
#include <QNetworkReply>
#include <QMessageBox>
#include <QAuthenticator>
-#include <QDebug>
#include "creds/shibbolethcredentials.h"
#include "creds/shibboleth/shibbolethwebview.h"
namespace OCC
{
+Q_LOGGING_CATEGORY(lcShibboleth, "gui.credentials.shibboleth", QtInfoMsg)
+
namespace
{
QVariant target = r->attribute(QNetworkRequest::RedirectionTargetAttribute);
if (target.isValid()) {
_stillValid = false;
- qWarning() << Q_FUNC_INFO << "detected redirect, will open Login Window"; // will be done in NetworkJob's finished signal
+ qCWarning(lcShibboleth) << "detected redirect, will open Login Window"; // will be done in NetworkJob's finished signal
} else {
//_stillValid = true; // gets set when reading from keychain or getting it from browser
}
{
if (_user.isEmpty()) {
if (user.isEmpty()) {
- qDebug() << "Failed to fetch the shibboleth user";
+ qCDebug(lcShibboleth) << "Failed to fetch the shibboleth user";
}
_user = user;
} else if (user != _user) {
- qDebug() << "Wrong user: " << user << "!=" << _user;
+ qCDebug(lcShibboleth) << "Wrong user: " << user << "!=" << _user;
QMessageBox::warning(_browser, tr("Login Error"), tr("You must sign in as user %1").arg(_user));
invalidateToken();
showLoginWindow();
#define MIRALL_CREDS_SHIBBOLETH_CREDENTIALS_H
#include <QList>
+#include <QLoggingCategory>
#include <QMap>
#include <QNetworkCookie>
#include <QUrl>
namespace OCC
{
+Q_DECLARE_LOGGING_CATEGORY(lcShibboleth)
+
class ShibbolethWebView;
/**
#include "creds/abstractcredentials.h"
-#include <QDebug>
#include <QTimer>
#include <QUrl>
#include <QDir>
namespace OCC {
+Q_LOGGING_CATEGORY(lcFolder, "gui.folder", QtInfoMsg)
+
Folder::Folder(const FolderDefinition& definition,
AccountState* accountState,
QObject* parent)
_engine->setIgnoreHiddenFiles(_definition.ignoreHiddenFiles);
if (!setIgnoredFiles())
- qWarning("Could not read system exclude file");
+ qCWarning(lcFolder, "Could not read system exclude file");
connect(_accountState.data(), SIGNAL(isConnectedChanged()), this, SIGNAL(canSyncChanged()));
connect(_engine.data(), SIGNAL(rootEtag(QString)), this, SLOT(etagRetreivedFromSyncEngine(QString)));
const QFileInfo fi(_definition.localPath);
_canonicalLocalPath = fi.canonicalFilePath();
if (_canonicalLocalPath.isEmpty()) {
- qDebug() << "Broken symlink:" << _definition.localPath;
+ qCDebug(lcFolder) << "Broken symlink:" << _definition.localPath;
_canonicalLocalPath = _definition.localPath;
} else if( !_canonicalLocalPath.endsWith('/') ) {
_canonicalLocalPath.append('/');
}
if( fi.isDir() && fi.isReadable() ) {
- qDebug() << "Checked local path ok";
+ qCDebug(lcFolder) << "Checked local path ok";
} else {
// Check directory again
if( !FileSystem::fileExists(_definition.localPath, fi) ) {
void Folder::slotRunEtagJob()
{
- qDebug() << "* Trying to check" << remoteUrl().toString() << "for changes via ETag check. (time since last sync:" << (_timeSinceLastSyncDone.elapsed() / 1000) << "s)";
+ qCDebug(lcFolder) << "Trying to check" << remoteUrl().toString() << "for changes via ETag check. (time since last sync:" << (_timeSinceLastSyncDone.elapsed() / 1000) << "s)";
AccountPtr account = _accountState->account();
if (_requestEtagJob) {
- qDebug() << Q_FUNC_INFO << remoteUrl().toString() << "has ETag job queued, not trying to sync";
+ qCDebug(lcFolder) << remoteUrl().toString() << "has ETag job queued, not trying to sync";
return;
}
if (!canSync()) {
- qDebug() << "Not syncing. :" << remoteUrl().toString() << _definition.paused << AccountState::stateString(_accountState->state());
+ qCDebug(lcFolder) << "Not syncing. :" << remoteUrl().toString() << _definition.paused << AccountState::stateString(_accountState->state());
return;
}
void Folder::etagRetreived(const QString& etag)
{
- //qDebug() << "* Compare etag with previous etag: last:" << _lastEtag << ", received:" << etag;
-
// re-enable sync if it was disabled because network was down
FolderMan::instance()->setSyncEnabled(true);
if (_lastEtag != etag) {
- qDebug() << "* Compare etag with previous etag: last:" << _lastEtag << ", received:" << etag << "-> CHANGED";
+ qCDebug(lcFolder) << "Compare etag with previous etag: last:" << _lastEtag << ", received:" << etag << "-> CHANGED";
_lastEtag = etag;
slotScheduleThisFolder();
}
void Folder::etagRetreivedFromSyncEngine(const QString& etag)
{
- qDebug() << "Root etag from during sync:" << etag;
+ qCDebug(lcFolder) << "Root etag from during sync:" << etag;
accountState()->tagLastSuccessfullETagRequest();
_lastEtag = etag;
}
createGuiLog( _syncResult.firstItemError()->_file, LogStatusError, errorCount );
}
- qDebug() << "OO folder slotSyncFinished: result: " << int(_syncResult.status());
+ qCDebug(lcFolder) << "Folder slotSyncFinished: result: " << int(_syncResult.status());
}
void Folder::createGuiLog( const QString& filename, LogStatus status, int count,
_journal.getAndDeleteStaleDownloadInfos(keep_nothing);
foreach (const SyncJournalDb::DownloadInfo & deleted_info, deleted_infos) {
const QString tmppath = folderpath.filePath(deleted_info._tmpfile);
- qDebug() << "Deleting temporary file: " << tmppath;
+ qCDebug(lcFolder) << "Deleting temporary file: " << tmppath;
FileSystem::remove(tmppath);
}
return deleted_infos.size();
auto record = _journal.getFileRecord(relativePath);
if (record.isValid() && !FileSystem::fileChanged(path, record._fileSize,
Utility::qDateTimeToTime_t(record._modtime))) {
- qDebug() << "Ignoring spurious notification for file" << relativePath;
+ qCDebug(lcFolder) << "Ignoring spurious notification for file" << relativePath;
return; // probably a spurious notification
}
}
FolderDefinition::save(*settings, _definition);
settings->sync();
- qDebug() << "Saved folder" << _definition.alias << "to settings, status" << settings->status();
+ qCDebug(lcFolder) << "Saved folder" << _definition.alias << "to settings, status" << settings->status();
}
void Folder::removeFromSettings() const
void Folder::slotTerminateSync()
{
- qDebug() << "folder " << alias() << " Terminating!";
+ qCDebug(lcFolder) << "folder " << alias() << " Terminating!";
if( _engine->isSyncRunning() ) {
_engine->abort();
QFile file(stateDbFile);
if( file.exists() ) {
if( !file.remove()) {
- qDebug() << "WRN: Failed to remove existing csync StateDB " << stateDbFile;
+ qCDebug(lcFolder) << "WRN: Failed to remove existing csync StateDB " << stateDbFile;
} else {
- qDebug() << "wipe: Removed csync StateDB " << stateDbFile;
+ qCDebug(lcFolder) << "wipe: Removed csync StateDB " << stateDbFile;
}
} else {
- qDebug() << "WRN: statedb is empty, can not remove.";
+ qCDebug(lcFolder) << "WRN: statedb is empty, can not remove.";
}
// Also remove other db related files
// a QSet of files to load.
ConfigFile cfg;
QString systemList = cfg.excludeFile(ConfigFile::SystemScope);
- qDebug() << "==== adding system ignore list to csync:" << systemList;
+ qCDebug(lcFolder) << "Adding system ignore list to csync:" << systemList;
_engine->excludedFiles().addExcludeFilePath(systemList);
QString userList = cfg.excludeFile(ConfigFile::UserScope);
if( QFile::exists(userList) ) {
- qDebug() << "==== adding user defined ignore list to csync:" << userList;
+ qCDebug(lcFolder) << "Adding user defined ignore list to csync:" << userList;
_engine->excludedFiles().addExcludeFilePath(userList);
}
}
if (isBusy()) {
- qCritical() << "* ERROR csync is still running and new sync requested.";
+ qCCritical(lcFolder) << "ERROR csync is still running and new sync requested.";
return;
}
_csyncUnavail = false;
_syncResult.setStatus( SyncResult::SyncPrepare );
emit syncStateChange();
- qDebug() << "*** Start syncing " << remoteUrl().toString() << " - client version"
+ qCDebug(lcFolder) << "*** Start syncing " << remoteUrl().toString() << " - client version"
<< qPrintable(Theme::instance()->version());
_fileLog->start(path());
void Folder::slotSyncStarted()
{
- qDebug() << "#### Propagation start #################################################### >>";
+ qCDebug(lcFolder) << "#### Propagation start #################################################### >>";
_syncResult.setStatus(SyncResult::SyncRunning);
emit syncStateChange();
}
void Folder::slotSyncFinished(bool success)
{
- qDebug() << " - client version" << qPrintable(Theme::instance()->version())
+ qCDebug(lcFolder) << "Client version" << qPrintable(Theme::instance()->version())
<< " Qt" << qVersion()
#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
<< " SSL " << QSslSocket::sslLibraryVersionString().toUtf8().data()
bool syncError = !_syncResult.errorStrings().isEmpty();
if( syncError ) {
- qDebug() << "-> SyncEngine finished with ERROR";
+ qCDebug(lcFolder) << "SyncEngine finished with ERROR";
} else {
- qDebug() << "-> SyncEngine finished without problem.";
+ qCDebug(lcFolder) << "SyncEngine finished without problem.";
}
_fileLog->finish();
showSyncResultPopup();
if (syncError) {
_syncResult.setStatus(SyncResult::Error);
- qDebug() << " * owncloud csync thread finished with error";
+ qCDebug(lcFolder) << "ownCloud csync thread finished with error";
} else if (_csyncUnavail) {
_syncResult.setStatus(SyncResult::Error);
- qDebug() << " ** csync not available.";
+ qCDebug(lcFolder) << "csync not available.";
} else if( _syncResult.foundFilesNotSynced() ) {
_syncResult.setStatus(SyncResult::Problem);
} else if( _definition.paused ) {
else
{
_consecutiveFailingSyncs++;
- qDebug() << "the last" << _consecutiveFailingSyncs << "syncs failed";
+ qCDebug(lcFolder) << "the last" << _consecutiveFailingSyncs << "syncs failed";
}
if (_syncResult.status() == SyncResult::Success && success) {
// Increment the follow-up sync counter if necessary.
if (anotherSyncNeeded == ImmediateFollowUp) {
_consecutiveFollowUpSyncs++;
- qDebug() << "another sync was requested by the finished sync, this has"
+ qCDebug(lcFolder) << "another sync was requested by the finished sync, this has"
<< "happened" << _consecutiveFollowUpSyncs << "times";
} else {
_consecutiveFollowUpSyncs = 0;
namespace OCC {
+Q_LOGGING_CATEGORY(lcFolderMan, "gui.folder.manager", QtInfoMsg)
+
FolderMan* FolderMan::_instance = 0;
FolderMan::FolderMan(QObject *parent) :
ConfigFile cfg;
int polltime = cfg.remotePollInterval();
- qDebug() << "setting remote poll timer interval to" << polltime << "msec";
+ qCDebug(lcFolderMan) << "setting remote poll timer interval to" << polltime << "msec";
_etagPollTimer.setInterval( polltime );
QObject::connect(&_etagPollTimer, SIGNAL(timeout()), this, SLOT(slotEtagPollTimerTimeout()));
_etagPollTimer.start();
return r;
}
- qDebug() << "* Setup folders from settings file";
+ qCDebug(lcFolderMan) << "* Setup folders from settings file";
foreach (const auto& account, AccountManager::instance()->accounts()) {
const auto id = account->account()->id();
QDir storageDir(cfg.configPath());
_folderConfigPath = cfg.configPath() + QLatin1String("folders");
- qDebug() << "* Setup folders from " << _folderConfigPath << "(migration)";
+ qCDebug(lcFolderMan) << "* Setup folders from " << _folderConfigPath << "(migration)";
QDir dir( _folderConfigPath );
//We need to include hidden files just in case the alias starts with '.'
{
// remove the old journal file
while (QFile::exists(journalDbFile) && !QFile::remove(journalDbFile)) {
- qDebug() << "Could not remove old db file at" << journalDbFile;
+ qCDebug(lcFolderMan) << "Could not remove old db file at" << journalDbFile;
int ret = QMessageBox::warning(0, tr("Could not reset folder state"),
tr("An old sync journal '%1' was found, "
"but could not be removed. Please make sure "
{
Folder *folder = 0;
- qDebug() << " ` -> setting up:" << file;
+ qCDebug(lcFolderMan) << " ` -> setting up:" << file;
QString escapedAlias(file);
// check the unescaped variant (for the case when the filename comes out
// of the directory listing). If the file does not exist, escape the
cfgFile.setFile( _folderConfigPath, escapedAlias );
}
if( !cfgFile.isReadable() ) {
- qDebug() << "Cannot read folder definition for alias " << cfgFile.filePath();
+ qCDebug(lcFolderMan) << "Cannot read folder definition for alias " << cfgFile.filePath();
return folder;
}
QSettings settings( _folderConfigPath + QLatin1Char('/') + escapedAlias, QSettings::IniFormat);
- qDebug() << " -> file path: " << settings.fileName();
+ qCDebug(lcFolderMan) << " -> file path: " << settings.fileName();
// Check if the filename is equal to the group setting. If not, use the group
// name as an alias.
QString alias = unescapeAlias( escapedAlias );
if (backend.isEmpty() || backend != QLatin1String("owncloud")) {
- qWarning() << "obsolete configuration of type" << backend;
+ qCWarning(lcFolderMan) << "obsolete configuration of type" << backend;
return 0;
}
}
if (!accountState) {
- qWarning() << "can't create folder without an account";
+ qCWarning(lcFolderMan) << "can't create folder without an account";
return 0;
}
folder->saveToSettings();
}
- qDebug() << "Migrated!" << folder;
+ qCDebug(lcFolderMan) << "Migrated!" << folder;
settings.sync();
return folder;
}
void FolderMan::slotFolderSyncPaused( Folder *f, bool paused )
{
if( !f ) {
- qWarning() << "!! slotFolderSyncPaused called with empty folder";
+ qCWarning(lcFolderMan) << "!! slotFolderSyncPaused called with empty folder";
return;
}
void FolderMan::slotScheduleAppRestart()
{
_appRestartRequired = true;
- qDebug() << "## Application restart requested!";
+ qCDebug(lcFolderMan) << "## Application restart requested!";
}
void FolderMan::slotSyncOnceFileUnlocks(const QString& path)
void FolderMan::scheduleFolder( Folder *f )
{
if( !f ) {
- qWarning() << "slotScheduleSync called with null folder";
+ qCWarning(lcFolderMan) << "slotScheduleSync called with null folder";
return;
}
auto alias = f->alias();
- qDebug() << "Schedule folder " << alias << " to sync!";
+ qCDebug(lcFolderMan) << "Schedule folder " << alias << " to sync!";
if( ! _scheduledFolders.contains(f) ) {
if( !f->canSync() ) {
- qDebug() << "Folder is not ready to sync, not scheduled!";
+ qCDebug(lcFolderMan) << "Folder is not ready to sync, not scheduled!";
_socketApi->slotUpdateFolderView(f);
return;
}
_scheduledFolders.enqueue(f);
emit scheduleQueueChanged();
} else {
- qDebug() << " II> Sync for folder " << alias << " already scheduled, do not enqueue!";
+ qCDebug(lcFolderMan) << " II> Sync for folder " << alias << " already scheduled, do not enqueue!";
}
startScheduledSyncSoon();
void FolderMan::scheduleFolderNext(Folder* f)
{
auto alias = f->alias();
- qDebug() << "Schedule folder " << alias << " to sync! Front-of-queue.";
+ qCDebug(lcFolderMan) << "Schedule folder " << alias << " to sync! Front-of-queue.";
if( !f->canSync() ) {
- qDebug() << "Folder is not ready to sync, not scheduled!";
+ qCDebug(lcFolderMan) << "Folder is not ready to sync, not scheduled!";
return;
}
}
}
if (_currentEtagJob.isNull()) {
- //qDebug() << "No more remote ETag check jobs to schedule.";
+ //qCDebug(lcFolderMan) << "No more remote ETag check jobs to schedule.";
/* now it might be a good time to check for restarting... */
if( _currentSyncFolder == NULL && _appRestartRequired ) {
restartApplication();
}
} else {
- qDebug() << "Scheduling" << folder->remoteUrl().toString() << "to check remote ETag";
+ qCDebug(lcFolderMan) << "Scheduling" << folder->remoteUrl().toString() << "to check remote ETag";
_currentEtagJob->start(); // on destroy/end it will continue the queue via slotEtagJobDestroyed
}
}
QString accountName = accountState->account()->displayName();
if (accountState->isConnected()) {
- qDebug() << "Account" << accountName << "connected, scheduling its folders";
+ qCDebug(lcFolderMan) << "Account" << accountName << "connected, scheduling its folders";
foreach (Folder *f, _folderMap.values()) {
if (f
}
}
} else {
- qDebug() << "Account" << accountName << "disconnected or paused, "
+ qCDebug(lcFolderMan) << "Account" << accountName << "disconnected or paused, "
"terminating or descheduling sync folders";
if (_currentSyncFolder
// Time since the last sync run counts against the delay
msDelay = qMax(1ll, msDelay - msSinceLastSync);
- qDebug() << "Starting the next scheduled sync in" << (msDelay/1000) << "seconds";
+ qCDebug(lcFolderMan) << "Starting the next scheduled sync in" << (msDelay/1000) << "seconds";
_startScheduledSyncTimer.start(msDelay);
}
void FolderMan::slotStartScheduledFolderSync()
{
if( _currentSyncFolder ) {
- qDebug() << "Currently folder " << _currentSyncFolder->remoteUrl().toString() << " is running, wait for finish!";
+ qCDebug(lcFolderMan) << "Currently folder " << _currentSyncFolder->remoteUrl().toString() << " is running, wait for finish!";
return;
}
if( ! _syncEnabled ) {
- qDebug() << "FolderMan: Syncing is disabled, no scheduling.";
+ qCDebug(lcFolderMan) << "FolderMan: Syncing is disabled, no scheduling.";
return;
}
- qDebug() << "XX slotScheduleFolderSync: folderQueue size: " << _scheduledFolders.count();
+ qCDebug(lcFolderMan) << "XX slotScheduleFolderSync: folderQueue size: " << _scheduledFolders.count();
if( _scheduledFolders.isEmpty() ) {
return;
}
void FolderMan::slotEtagPollTimerTimeout()
{
- //qDebug() << Q_FUNC_INFO << "Checking if we need to make any folders check the remote ETag";
ConfigFile cfg;
int polltime = cfg.remotePollInterval();
{
// Pause folders if the server version is unsupported
if (account->serverVersionUnsupported()) {
- qDebug() << "The server version is unsupported:" << account->serverVersion()
+ qCDebug(lcFolderMan) << "The server version is unsupported:" << account->serverVersion()
<< "pausing all folders on the account";
foreach (auto& f, _folderMap) {
bool forceSyncIntervalExpired =
quint64(msecsSinceSync) > ConfigFile().forceSyncInterval();
if (forceSyncIntervalExpired) {
- qDebug() << "** scheduling folder" << f->alias()
+ qCDebug(lcFolderMan) << "** scheduling folder" << f->alias()
<< "because it has been" << msecsSinceSync << "ms "
<< "since the last sync";
syncAgainDelay = 60 * 1000; // 60s for each further attempt
if (syncAgain
&& msecsSinceSync > syncAgainDelay) {
- qDebug() << "** scheduling folder" << f->alias()
+ qCDebug(lcFolderMan) << "** scheduling folder" << f->alias()
<< ", the last" << f->consecutiveFailingSyncs() << "syncs failed"
<< ", anotherSyncNeeded" << f->syncEngine().isAnotherSyncNeeded()
<< ", last status:" << f->syncResult().statusString()
void FolderMan::slotFolderSyncStarted( )
{
- qDebug() << ">===================================== sync started for " << _currentSyncFolder->remoteUrl().toString();
+ qCDebug(lcFolderMan) << ">===================================== sync started for " << _currentSyncFolder->remoteUrl().toString();
}
/*
*/
void FolderMan::slotFolderSyncFinished( const SyncResult& )
{
- qDebug() << "<===================================== sync finished for " << _currentSyncFolder->remoteUrl().toString();
+ qCDebug(lcFolderMan) << "<===================================== sync finished for " << _currentSyncFolder->remoteUrl().toString();
_lastSyncFolder = _currentSyncFolder;
_currentSyncFolder = 0;
auto folder = new Folder(folderDefinition, accountState, this );
- qDebug() << "Adding folder to Folder Map " << folder << folder->alias();
+ qCDebug(lcFolderMan) << "Adding folder to Folder Map " << folder << folder->alias();
_folderMap[folder->alias()] = folder;
if (folder->syncPaused()) {
_disabledFolders.insert(folder);
if(absolutePath.startsWith(folderPath, (Utility::isWindows() || Utility::isMac())?
Qt::CaseInsensitive : Qt::CaseSensitive)) {
- //qDebug() << "found folder: " << folder->path() << " for " << absolutePath;
return folder;
}
}
void FolderMan::removeFolder( Folder *f )
{
if( !f ) {
- qWarning() << "!! Can not remove null folder";
+ qCWarning(lcFolderMan) << "!! Can not remove null folder";
return;
}
- qDebug() << "Removing " << f->alias();
+ qCDebug(lcFolderMan) << "Removing " << f->alias();
const bool currentlyRunning = (_currentSyncFolder == f);
if( currentlyRunning ) {
if( fi.exists() ) {
// It exists, but is empty -> just reuse it.
if( fi.isDir() && fi.dir().count() == 0 ) {
- qDebug() << "startFromScratch: Directory is empty!";
+ qCDebug(lcFolderMan) << "startFromScratch: Directory is empty!";
return true;
}
// Disconnect the socket api from the database to avoid that locking of the
QString newName = getBackupName( parentDir.absoluteFilePath( folderName ) );
QString renameError;
if( !FileSystem::rename( fi.absoluteFilePath(), newName, &renameError ) ) {
- qDebug() << "startFromScratch: Could not rename" << fi.absoluteFilePath()
+ qCDebug(lcFolderMan) << "startFromScratch: Could not rename" << fi.absoluteFilePath()
<< "to" << newName << "error:" << renameError;
return false;
}
}
if( !parentDir.mkdir( fi.absoluteFilePath() ) ) {
- qDebug() << "startFromScratch: Could not mkdir" << fi.absoluteFilePath();
+ qCDebug(lcFolderMan) << "startFromScratch: Could not mkdir" << fi.absoluteFilePath();
return false;
}
{
if( Utility::isLinux() ) {
// restart:
- qDebug() << "### Restarting application NOW, PID" << qApp->applicationPid() << "is ending.";
+ qCDebug(lcFolderMan) << "### Restarting application NOW, PID" << qApp->applicationPid() << "is ending.";
qApp->quit();
QStringList args = qApp->arguments();
QString prg = args.takeFirst();
QProcess::startDetached(prg, args);
} else {
- qDebug() << "On this platform we do not restart.";
+ qCDebug(lcFolderMan) << "On this platform we do not restart.";
}
}
namespace OCC {
+Q_LOGGING_CATEGORY(lcFolderStatus, "gui.folder.model", QtInfoMsg)
+
static const char propertyParentIndexC[] = "oc_parentIndex";
static const char propertyPermissionMap[] = "oc_permissionMap";
auto selectiveSyncUndecidedList = parentInfo->_folder->journalDb()->getSelectiveSyncList(SyncJournalDb::SelectiveSyncUndecidedList, &ok2);
if( !(ok1 && ok2) ) {
- qDebug() << Q_FUNC_INFO << "Could not retrieve selective sync info from journal";
+ qCDebug(lcFolderStatus) << "Could not retrieve selective sync info from journal";
return;
}
}
auto parentInfo = infoForIndex(idx);
if (parentInfo) {
- qDebug() << r->errorString();
+ qCDebug(lcFolderStatus) << r->errorString();
parentInfo->_lastErrorString = r->errorString();
parentInfo->resetSubs(this, idx);
bool ok;
auto oldBlackList = folder->journalDb()->getSelectiveSyncList(SyncJournalDb::SelectiveSyncBlackList, &ok);
if( !ok ) {
- qDebug() << Q_FUNC_INFO << "Could not read selective sync list from db.";
+ qCDebug(lcFolderStatus) << "Could not read selective sync list from db.";
return;
}
QStringList blackList = createBlackList(&_folders[i], oldBlackList);
}
if (citm._item._direction != SyncFileItem::Up){
estimatedDownBw += progress.fileProgress(citm._item).estimatedBandwidth;
- //qDebug() << "DOWN" << citm._item._file << progress.fileProgress(citm._item).estimatedBandwidth;
} else {
estimatedUpBw += progress.fileProgress(citm._item).estimatedBandwidth;
- //qDebug() << "UP" << citm._item._file << progress.fileProgress(citm._item).estimatedBandwidth;
}
auto fileName = QFileInfo(citm._item._file).fileName();
if (allFilenames.length() > 0) {
allFilenames.append(tr("'%1'").arg(fileName));
}
}
- //qDebug() << "Syncing bandwidth" << estimatedDownBw << estimatedUpBw;
if (curItemProgress == -1) {
curItemProgress = curItem._size;
}
bool ok;
auto undecidedList = folder->journalDb()->getSelectiveSyncList(SyncJournalDb::SelectiveSyncUndecidedList, &ok);
if( !ok ) {
- qDebug() << Q_FUNC_INFO << "Could not read selective sync list from db.";
+ qCDebug(lcFolderStatus) << "Could not read selective sync list from db.";
return;
}
// Remove all undecided folders from the blacklist
auto blackList = folder->journalDb()->getSelectiveSyncList(SyncJournalDb::SelectiveSyncBlackList, &ok);
if( !ok ) {
- qDebug() << Q_FUNC_INFO << "Could not read selective sync list from db.";
+ qCDebug(lcFolderStatus) << "Could not read selective sync list from db.";
return;
}
foreach (const auto& undecidedFolder, undecidedList) {
// Add all undecided folders to the white list
auto whiteList = folder->journalDb()->getSelectiveSyncList(SyncJournalDb::SelectiveSyncWhiteList, &ok);
if( !ok ) {
- qDebug() << Q_FUNC_INFO << "Could not read selective sync list from db.";
+ qCDebug(lcFolderStatus) << "Could not read selective sync list from db.";
return;
}
whiteList += undecidedList;
#include <accountfwd.h>
#include <QAbstractItemModel>
+#include <QLoggingCategory>
#include <QVector>
#include <QElapsedTimer>
class QNetworkReply;
namespace OCC {
+Q_DECLARE_LOGGING_CATEGORY(lcFolderStatus)
+
class Folder;
class ProgressInfo;
#include <QFileInfo>
#include <QFlags>
-#include <QDebug>
#include <QDir>
#include <QMutexLocker>
#include <QStringList>
namespace OCC {
+Q_LOGGING_CATEGORY(lcFolderWatcher, "gui.folderwatcher", QtInfoMsg)
+
FolderWatcher::FolderWatcher(const QString &root, Folder* folder)
: QObject(folder),
_folder(folder)
#ifndef OWNCLOUD_TEST
if (_folder->isFileExcludedAbsolute(path)) {
- qDebug() << "* Ignoring file" << path;
+ qCDebug(lcFolderWatcher) << "* Ignoring file" << path;
return true;
}
#endif
void FolderWatcher::changeDetected( const QStringList& paths )
{
- // qDebug() << Q_FUNC_INFO << paths;
-
// TODO: this shortcut doesn't look very reliable:
// - why is the timeout only 1 second?
// - what if there is more than one file being updated frequently?
return;
}
- qDebug() << "detected changes in paths:" << changedPaths;
+ qCDebug(lcFolderWatcher) << "detected changes in paths:" << changedPaths;
foreach (const QString &path, changedPaths) {
emit pathChanged(path);
}
#include "config.h"
#include <QList>
+#include <QLoggingCategory>
#include <QObject>
#include <QString>
#include <QStringList>
namespace OCC {
+Q_DECLARE_LOGGING_CATEGORY(lcFolderWatcher)
+
class FolderWatcherPrivate;
class Folder;
#include "folderwatcher_linux.h"
#include <cerrno>
-#include <QDebug>
#include <QStringList>
#include <QObject>
#include <QVarLengthArray>
_socket.reset( new QSocketNotifier(_fd, QSocketNotifier::Read) );
connect(_socket.data(), SIGNAL(activated(int)), SLOT(slotReceivedNotification(int)));
} else {
- qDebug() << Q_FUNC_INFO << "notify_init() failed: " << strerror(errno);
+ qCDebug(lcFolderWatcher) << "notify_init() failed: " << strerror(errno);
}
QMetaObject::invokeMethod(this, "slotAddFolderRecursive", Q_ARG(QString, path));
{
bool ok = true;
if( !(dir.exists() && dir.isReadable()) ) {
- qDebug() << "Non existing path coming in: " << dir.absolutePath();
+ qCDebug(lcFolderWatcher) << "Non existing path coming in: " << dir.absolutePath();
ok = false;
} else {
QStringList nameFilter;
void FolderWatcherPrivate::slotAddFolderRecursive(const QString &path)
{
int subdirs = 0;
- qDebug() << "(+) Watcher:" << path;
+ qCDebug(lcFolderWatcher) << "(+) Watcher:" << path;
QDir inPath(path);
inotifyRegisterPath(inPath.absolutePath());
QStringList allSubfolders;
if( !findFoldersBelow(QDir(path), allSubfolders)) {
- qDebug() << "Could not traverse all sub folders";
+ qCDebug(lcFolderWatcher) << "Could not traverse all sub folders";
}
- // qDebug() << "currently watching " << watchedFolders;
QStringListIterator subfoldersIt(allSubfolders);
while (subfoldersIt.hasNext()) {
QString subfolder = subfoldersIt.next();
- // qDebug() << " (**) subfolder: " << subfolder;
QDir folder (subfolder);
if (folder.exists() && !watchedFolders.contains(folder.absolutePath())) {
subdirs++;
if( _parent->pathIsIgnored(subfolder) ) {
- qDebug() << "* Not adding" << folder.path();
+ qCDebug(lcFolderWatcher) << "* Not adding" << folder.path();
continue;
}
inotifyRegisterPath(folder.absolutePath());
} else {
- qDebug() << " `-> discarded:" << folder.path();
+ qCDebug(lcFolderWatcher) << " `-> discarded:" << folder.path();
}
}
if (subdirs >0) {
- qDebug() << " `-> and" << subdirs << "subdirectories";
+ qCDebug(lcFolderWatcher) << " `-> and" << subdirs << "subdirectories";
}
}
// cast an inotify_event
event = (struct inotify_event*)&buffer[i];
if (event == NULL) {
- qDebug() << "NULL event";
+ qCDebug(lcFolderWatcher) << "NULL event";
i += sizeof(struct inotify_event);
continue;
}
// Fire event for the path that was changed.
if (event->len > 0 && event->wd > -1) {
QByteArray fileName(event->name);
- // qDebug() << Q_FUNC_INFO << event->name;
if (fileName.startsWith("._sync_") ||
fileName.startsWith(".csync_journal.db") ||
fileName.startsWith(".owncloudsync.log")) {
- // qDebug() << "ignore journal";
} else {
const QString p = _watches[event->wd] + '/' + fileName;
- //qDebug() << "found a change in " << p;
_parent->changeDetected(p);
}
}
#include <cerrno>
-#include <QDebug>
#include <QStringList>
| kFSEventStreamEventFlagItemModified; // for content change
//We ignore other flags, e.g. for owner change, xattr change, Finder label change etc
- qDebug() << "FolderWatcherPrivate::callback by OS X";
+ qCDebug(lcFolderWatcher) << "FolderWatcherPrivate::callback by OS X";
QStringList paths;
CFArrayRef eventPaths = (CFArrayRef)eventPathsVoid;
QString fn = qstring.normalized(QString::NormalizationForm_C);
if (!(eventFlags[i] & c_interestingFlags)) {
- qDebug() << "Ignoring non-content changes for" << fn;
+ qCDebug(lcFolderWatcher) << "Ignoring non-content changes for" << fn;
continue;
}
void FolderWatcherPrivate::startWatching()
{
- qDebug() << "FolderWatcherPrivate::startWatching()" << _folder;
+ qCDebug(lcFolderWatcher) << "FolderWatcherPrivate::startWatching()" << _folder;
CFStringRef folderCF = CFStringCreateWithCharacters(0, reinterpret_cast<const UniChar *>(_folder.unicode()),
_folder.length());
CFArrayRef pathsToWatch = CFStringCreateArrayBySeparatingStrings (NULL, folderCF, CFSTR(":"));
*/
#include <QThread>
-#include <QDebug>
#include <QDir>
#include "filesystem.h"
if (_directory == INVALID_HANDLE_VALUE)
{
DWORD errorCode = GetLastError();
- qDebug() << Q_FUNC_INFO << "Failed to create handle for" << _path << ", error:" << errorCode;
+ qCDebug(lcFolderWatcher) << "Failed to create handle for" << _path << ", error:" << errorCode;
_directory = 0;
return;
}
{
DWORD errorCode = GetLastError();
if (errorCode == ERROR_NOTIFY_ENUM_DIR) {
- qDebug() << Q_FUNC_INFO << "The buffer for changes overflowed! Triggering a generic change and resizing";
+ qCDebug(lcFolderWatcher) << "The buffer for changes overflowed! Triggering a generic change and resizing";
emit changed(_path);
*increaseBufferSize = true;
} else {
- qDebug() << Q_FUNC_INFO << "ReadDirectoryChangesW error" << errorCode;
+ qCDebug(lcFolderWatcher) << "ReadDirectoryChangesW error" << errorCode;
}
break;
}
false, // awake once one of them arrives
INFINITE);
if (result == 1) {
- qDebug() << "Received stop event, aborting folder watcher thread";
+ qCDebug(lcFolderWatcher) << "Received stop event, aborting folder watcher thread";
break;
}
if (result != 0) {
- qDebug() << "WaitForMultipleObjects failed" << result << GetLastError();
+ qCDebug(lcFolderWatcher) << "WaitForMultipleObjects failed" << result << GetLastError();
break;
}
if (! ok) {
DWORD errorCode = GetLastError();
if (errorCode == ERROR_NOTIFY_ENUM_DIR) {
- qDebug() << Q_FUNC_INFO << "The buffer for changes overflowed! Triggering a generic change and resizing";
+ qCDebug(lcFolderWatcher) << "The buffer for changes overflowed! Triggering a generic change and resizing";
emit changed(_path);
*increaseBufferSize = true;
} else {
- qDebug() << Q_FUNC_INFO << "GetOverlappedResult error" << errorCode;
+ qCDebug(lcFolderWatcher) << "GetOverlappedResult error" << errorCode;
}
break;
}
if (longNameSize > 0) {
longfile = QString::fromUtf16(reinterpret_cast<const ushort *>(fileNameBuffer), longNameSize);
} else {
- qDebug() << Q_FUNC_INFO << "Error converting file name to full length, keeping original name.";
+ qCDebug(lcFolderWatcher) << "Error converting file name to full length, keeping original name.";
}
}
longfile = QDir::cleanPath(longfile);
&& QFileInfo(longfile).isDir();
if (!skip) {
- //qDebug() << Q_FUNC_INFO << "Found change in" << longfile
- // << "action:" << curEntry->Action;
emit changed(longfile);
}
#include "selectivesyncdialog.h"
#include "accountstate.h"
#include "creds/abstractcredentials.h"
+#include "wizard/owncloudwizard.h"
-#include <QDebug>
#include <QDesktopServices>
#include <QDir>
#include <QFileDialog>
void FolderWizardRemotePath::slotCreateRemoteFolderFinished(QNetworkReply::NetworkError error)
{
if (error == QNetworkReply::NoError) {
- qDebug() << "** webdav mkdir request finished";
+ qCDebug(lcWizard) << "webdav mkdir request finished";
showWarn(tr("Folder was successfully created on %1.").arg(Theme::instance()->appNameGUI()));
slotRefreshFolders();
_ui.folderEntry->setText(static_cast<MkColJob *>(sender())->path());
void FolderWizardRemotePath::slotHandleMkdirNetworkError(QNetworkReply *reply)
{
- qDebug() << "** webdav mkdir request failed:" << reply->error();
+ qCDebug(lcWizard) << "webdav mkdir request failed:" << reply->error();
if( !_account->credentials()->stillValid(reply) ) {
showWarn(tr("Authentication failed accessing %1").arg(Theme::instance()->appNameGUI()));
} else {
#include "lockwatcher.h"
#include "filesystem.h"
+#include <QLoggingCategory>
#include <QTimer>
-#include <QDebug>
using namespace OCC;
+Q_LOGGING_CATEGORY(lcLockWatcher, "gui.lockwatcher", QtInfoMsg)
+
static const int check_frequency = 20 * 1000; // ms
LockWatcher::LockWatcher(QObject* parent)
void LockWatcher::addFile(const QString& path)
{
- qDebug() << "Watching for lock of" << path << "being released";
+ qCDebug(lcLockWatcher) << "Watching for lock of" << path << "being released";
_watchedPaths.insert(path);
}
foreach (const QString& path, _watchedPaths) {
if (!FileSystem::isFileLocked(path)) {
- qDebug() << "Lock of" << path << "was released";
+ qCDebug(lcLockWatcher) << "Lock of" << path << "was released";
emit fileUnlocked(path);
unlocked.insert(path);
}
#include <QTextStream>
#include <QMessageBox>
#include <QCoreApplication>
-#include <QDebug>
#include <QSettings>
#include <QAction>
ConfigFile cfg;
cfg.restoreGeometry(this);
int lines = cfg.maxLogLines();
- // qDebug() << "# ## Have " << lines << " Loglines!";
_logWidget->document()->setMaximumBlockCount( lines );
}
if (setrlimit(RLIMIT_CORE, &core_limit) < 0) {
fprintf(stderr, "Unable to set core dump limit\n");
} else {
- qDebug() << "Core dumps enabled";
+ qCDebug(lcApplication) << "Core dumps enabled";
}
}
#endif
// if the application is already running, notify it.
if(app.isRunning()) {
- qDebug() << Q_FUNC_INFO << "Already running, exiting...";
+ qCDebug(lcApplication) << "Already running, exiting...";
if (app.isSessionRestored()) {
// This call is mirrored with the one in Application::slotParseMessage
- qDebug() << "Session was restored, don't notify app!";
+ qCDebug(lcApplication) << "Session was restored, don't notify app!";
return -1;
}
namespace OCC {
+Q_DECLARE_LOGGING_CATEGORY(lcNotifications)
+
NotificationConfirmJob::NotificationConfirmJob(AccountPtr account)
: AbstractNetworkJob(account, ""),
_widget(0)
void NotificationConfirmJob::start()
{
if( !_link.isValid() ) {
- qDebug() << "Attempt to trigger invalid URL: " << _link.toString();
+ qCDebug(lcNotifications) << "Attempt to trigger invalid URL: " << _link.toString();
return;
}
QNetworkRequest req;
namespace OCC {
+Q_LOGGING_CATEGORY(lcNotifications, "gui.notifications", QtInfoMsg)
+
NotificationWidget::NotificationWidget(QWidget *parent) : QWidget(parent)
{
_ui.setupUi(this);
_actionLabel = triggeredLink._label;
if( ! triggeredLink._link.isEmpty() ) {
- qDebug() << Q_FUNC_INFO << "Notification Link: "<< triggeredLink._verb << triggeredLink._link;
+ qCDebug(lcNotifications) << "Notification Link: "<< triggeredLink._verb << triggeredLink._link;
_progressIndi->startAnimation();
emit sendNotificationRequest( _accountName, triggeredLink._link, triggeredLink._verb );
}
// the ocs API returns stat code 100 if it succeeded.
if( statusCode != OCS_SUCCESS_STATUS_CODE ) {
- qDebug() << Q_FUNC_INFO << "Notification Request to Server failed, leave button visible.";
+ qCDebug(lcNotifications) << "Notification Request to Server failed, leave button visible.";
for( i = 0; i < _buttons.count(); i++ ) {
_buttons.at(i)->setEnabled(true);
}
namespace OCC {
+Q_LOGGING_CATEGORY(lcOcs, "gui.sharing.ocs", QtInfoMsg)
+
OcsJob::OcsJob(AccountPtr account)
: AbstractNetworkJob(account, "")
{
QJsonParseError error;
auto json = QJsonDocument::fromJson(replyData, &error);
if (error.error != QJsonParseError::NoError) {
- qDebug() << "Could not parse reply to"
+ qCDebug(lcOcs) << "Could not parse reply to"
<< _verb
<< Utility::concatUrlPath(account()->url(), path())
<< _params
QString message;
const int statusCode = getJsonReturnCode(json, message);
if (!_passStatusCodes.contains(statusCode)) {
- qDebug() << "Reply to"
+ qCDebug(lcOcs) << "Reply to"
<< _verb
<< Utility::concatUrlPath(account()->url(), path())
<< _params
#include <QDir>
#include <QUrl>
#include <QDesktopServices>
-#include <QDebug>
#include <QApplication>
namespace OCC {
nativeArgs += QDir::toNativeSeparators(fi.canonicalFilePath());
nativeArgs += QLatin1Char('"');
- qDebug() << "OO Open explorer commandline:" << explorer << nativeArgs;
QProcess p;
#ifdef Q_OS_WIN
// QProcess on Windows tries to wrap the whole argument/program string
p.waitForFinished(5000);
QByteArray result = p.readAll();
QString resultAsString(result); // if appropriate
- qDebug() << "Load Finder Overlay-Plugin: " << resultAsString << ": " << p.exitCode()
+ qCDebug(lcApplication) << "Load Finder Overlay-Plugin: " << resultAsString << ": " << p.exitCode()
<< (p.exitCode() != 0 ? p.errorString() : QString::null);
} else {
- qDebug() << finderExtension << "does not exist! Finder Overlay Plugin loading failed";
+ qCDebug(lcApplication) << finderExtension << "does not exist! Finder Overlay Plugin loading failed";
}
}
#endif
_settingsDialog->close();
}
} else {
- qDebug() << "No configured folders yet, starting setup wizard";
+ qCDebug(lcApplication) << "No configured folders yet, starting setup wizard";
slotNewAccountWizard();
}
}
auto result = folder->syncResult();
- qDebug() << "Sync state changed for folder " << folder->remoteUrl().toString() << ": " << result.statusString();
+ qCDebug(lcApplication) << "Sync state changed for folder " << folder->remoteUrl().toString() << ": " << result.statusString();
if (result.status() == SyncResult::Success || result.status() == SyncResult::Error) {
Logger::instance()->enterNextLogFile();
#else
QStringList allStatusStrings;
foreach(Folder* folder, map.values()) {
- //qDebug() << "Folder in overallStatus Message: " << folder << " with name " << folder->alias();
QString folderMessage = folderMan->statusToString(folder->syncResult().status(), folder->syncPaused());
allStatusStrings += tr("Folder %1: %2").arg(folder->shortGuiLocalPath(), folderMessage);
}
void ownCloudGui::slotContextMenuAboutToShow()
{
// For some reason on OS X _contextMenu->isVisible returns always false
- qDebug() << "";
_contextMenuVisibleOsx = true;
// Update icon in sys tray, as it might change depending on the context menu state
void ownCloudGui::slotContextMenuAboutToHide()
{
// For some reason on OS X _contextMenu->isVisible returns always false
- qDebug() << "";
_contextMenuVisibleOsx = false;
// Update icon in sys tray, as it might change depending on the context menu state
if (platformMenu
&& platformMenu->metaObject()->className() == QLatin1String("QDBusPlatformMenu")) {
_qdbusmenuWorkaround = true;
- qDebug() << "Enabled QDBusPlatformMenu workaround";
+ qCDebug(lcApplication) << "Enabled QDBusPlatformMenu workaround";
}
}
#endif
if( _tray )
_tray->showMessage(title, msg);
else
- qDebug() << "Tray not ready: " << msg;
+ qCDebug(lcApplication) << "Tray not ready: " << msg;
}
void ownCloudGui::slotShowOptionalTrayMessage(const QString &title, const QString &msg)
{
Folder *f = FolderMan::instance()->folder(alias);
if( f ) {
- qDebug() << "opening local url " << f->path();
+ qCDebug(lcApplication) << "opening local url " << f->path();
QUrl url = QUrl::fromLocalFile(f->path());
#ifdef Q_OS_WIN
void ownCloudGui::slotShowSettings()
{
- qDebug() << Q_FUNC_INFO;
if (_settingsDialog.isNull()) {
_settingsDialog =
#if defined(Q_OS_MAC)
{
const auto folder = FolderMan::instance()->folderForPath(localPath);
if (!folder) {
- qDebug() << "Could not open share dialog for" << localPath << "no responsible folder found";
+ qCDebug(lcApplication) << "Could not open share dialog for" << localPath << "no responsible folder found";
return;
}
ShareDialog *w = 0;
if (_shareDialogs.contains(localPath) && _shareDialogs[localPath]) {
- qDebug() << Q_FUNC_INFO << "Raising share dialog" << sharePath << localPath;
+ qCDebug(lcApplication) << "Raising share dialog" << sharePath << localPath;
w = _shareDialogs[localPath];
} else {
- qDebug() << Q_FUNC_INFO << "Opening share dialog" << sharePath << localPath << maxSharingPermissions;
+ qCDebug(lcApplication) << "Opening share dialog" << sharePath << localPath << maxSharingPermissions;
w = new ShareDialog(accountState, sharePath, localPath, maxSharingPermissions);
w->setAttribute( Qt::WA_DeleteOnClose, true );
it.next();
if (! it.value() || it.value() == sender()) {
it.remove();
- qDebug() << "REMOVED";
}
}
}
// Lookup system proxy in a thread https://github.com/owncloud/client/issues/2993
if (ClientProxy::isUsingSystemDefault()) {
- qDebug() << "Trying to look up system proxy";
+ qCDebug(lcWizard) << "Trying to look up system proxy";
ClientProxy::lookupSystemProxyAsync(account->url(),
this, SLOT(slotSystemProxyLookupDone(QNetworkProxy)));
} else {
void OwncloudSetupWizard::slotSystemProxyLookupDone(const QNetworkProxy &proxy)
{
if (proxy.type() != QNetworkProxy::NoProxy) {
- qDebug() << "Setting QNAM proxy to be system proxy" << printQNetworkProxy(proxy);
+ qCDebug(lcWizard) << "Setting QNAM proxy to be system proxy" << printQNetworkProxy(proxy);
} else {
- qDebug() << "No system proxy set by OS";
+ qCDebug(lcWizard) << "No system proxy set by OS";
}
AccountPtr account = _ocWizard->account();
account->networkAccessManager()->setProxy(proxy);
QUrl redirectedUrl = url;
redirectedUrl.setPath(url.path().left(url.path().length() - 11));
_ocWizard->account()->setUrl(redirectedUrl);
- qDebug() << Q_FUNC_INFO << " was redirected to" << redirectedUrl.toString();
+ qCDebug(lcWizard) << " was redirected to" << redirectedUrl.toString();
}
DetermineAuthTypeJob *job = new DetermineAuthTypeJob(_ocWizard->account(), this);
// FIXME: Synchronous dialogs are not so nice because of event loop recursion
// (we already create a dialog further below)
QString serverError = reply->peek(1024*20);
- qDebug() << serverError;
+ qCDebug(lcWizard) << serverError;
QMessageBox messageBox(_ocWizard);
messageBox.setText(serverError);
messageBox.addButton(QMessageBox::Ok);
void OwncloudSetupWizard::slotConnectToOCUrl( const QString& url )
{
- qDebug() << "Connect to url: " << url;
+ qCDebug(lcWizard) << "Connect to url: " << url;
AbstractCredentials *creds = _ocWizard->getCredentials();
_ocWizard->account()->setCredentials(creds);
_ocWizard->setField(QLatin1String("OCUrl"), url );
PropfindJob* job = qobject_cast<PropfindJob*>(sender());
if (!job) {
- qWarning() << "Can't check for authed redirects. This slot should be invoked from PropfindJob!";
+ qCWarning(lcWizard) << "Can't check for authed redirects. This slot should be invoked from PropfindJob!";
return;
}
QNetworkReply* reply = job->reply();
// the updated server URL, similar to redirects on status.php.
QUrl redirectUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
if (!redirectUrl.isEmpty()) {
- qDebug() << "authed request was redirected to" << redirectUrl.toString();
+ qCDebug(lcWizard) << "authed request was redirected to" << redirectUrl.toString();
// strip the expected path
QString path = redirectUrl.path();
path.chop(expectedPath.size());
redirectUrl.setPath(path);
- qDebug() << "setting account url to" << redirectUrl.toString();
+ qCDebug(lcWizard) << "setting account url to" << redirectUrl.toString();
_ocWizard->account()->setUrl(redirectUrl);
testOwnCloudConnect();
return;
void OwncloudSetupWizard::slotCreateLocalAndRemoteFolders(const QString& localFolder, const QString& remoteFolder)
{
- qDebug() << "Setup local sync folder for new oC connection " << localFolder;
+ qCDebug(lcWizard) << "Setup local sync folder for new oC connection " << localFolder;
const QDir fi( localFolder );
bool nextStep = true;
res += tr("ok");
} else {
res += tr("failed.");
- qDebug() << "Failed to create " << fi.path();
+ qCDebug(lcWizard) << "Failed to create " << fi.path();
_ocWizard->displayError(tr("Could not create local folder %1").arg(Utility::escape(localFolder)), false);
nextStep = false;
}
QNetworkReply::NetworkError errId = reply->error();
if( errId == QNetworkReply::NoError ) {
- qDebug() << "******** Remote folder found, all cool!";
+ qCDebug(lcWizard) << "******** Remote folder found, all cool!";
} else if( errId == QNetworkReply::ContentNotFoundError ) {
if( _remoteFolder.isEmpty() ) {
error = tr("No remote folder specified!");
void OwncloudSetupWizard::slotCreateRemoteFolderFinished( QNetworkReply::NetworkError error )
{
- qDebug() << "** webdav mkdir request finished " << error;
+ qCDebug(lcWizard) << "** webdav mkdir request finished " << error;
// disconnect(ownCloudInfo::instance(), SIGNAL(webdavColCreated(QNetworkReply::NetworkError)),
// this, SLOT(slotCreateRemoteFolderFinished(QNetworkReply::NetworkError)));
FolderMan *folderMan = FolderMan::instance();
if( result == QDialog::Rejected ) {
- qDebug() << "Rejected the new config, use the old!";
+ qCDebug(lcWizard) << "Rejected the new config, use the old!";
} else if( result == QDialog::Accepted ) {
// This may or may not wipe all folder definitions, depending
bool startFromScratch = _ocWizard->field("OCSyncFromScratch").toBool();
if (!startFromScratch || ensureStartFromScratch(localFolder)) {
- qDebug() << "Adding folder definition for" << localFolder << _remoteFolder;
+ qCDebug(lcWizard) << "Adding folder definition for" << localFolder << _remoteFolder;
FolderDefinition folderDefinition;
folderDefinition.localPath = localFolder;
folderDefinition.targetPath = FolderDefinition::prepareTargetPath(_remoteFolder);
bool DetermineAuthTypeJob::finished()
{
QUrl redirection = reply()->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
- qDebug() << Q_FUNC_INFO << redirection.toString();
+ qCDebug(lcWizard) << redirection.toString();
if (_redirects >= maxRedirects()) {
redirection.clear();
}
using namespace OCC;
+Q_LOGGING_CATEGORY(lcProxy, "gui.credentials.proxy", QtInfoMsg)
+
ProxyAuthHandler* ProxyAuthHandler::instance()
{
static ProxyAuthHandler inst;
sending_qnam = qnam_alive.data();
}
if (!sending_qnam) {
- qDebug() << "Could not get the sending QNAM for" << sender();
+ qCDebug(lcProxy) << "Could not get the sending QNAM for" << sender();
}
- qDebug() << Q_FUNC_INFO << key << proxy.type();
+ qCDebug(lcProxy) << "Proxy auth required for" << key << proxy.type();
// If we already had a username but auth still failed,
// invalidate the old credentials! Unfortunately, authenticator->user()
if (!_waitingForDialog && !_waitingForKeychain &&
(!authenticator->user().isEmpty()
|| (sending_qnam && _gaveCredentialsTo.contains(sending_qnam)))) {
- qDebug() << "invalidating old creds" << key;
+ qCDebug(lcProxy) << "invalidating old creds" << key;
_username.clear();
_password.clear();
invalidated = true;
}
}
- qDebug() << "got creds for" << _proxy;
+ qCDebug(lcProxy) << "got creds for" << _proxy;
authenticator->setUser(_username);
authenticator->setPassword(_password);
sending_qnam = qnam_alive.data();
--_waitingForDialog;
if (_dialog && _dialog->result() == QDialog::Accepted) {
- qDebug() << "got creds for" << _proxy << "from dialog";
+ qCDebug(lcProxy) << "got creds for" << _proxy << "from dialog";
_username = _dialog->username();
_password = _dialog->password();
return true;
return false;
}
- qDebug() << "trying to load" << _proxy;
+ qCDebug(lcProxy) << "trying to load" << _proxy;
if (!_waitingForKeychain) {
_username = _settings->value(keychainUsernameKey()).toString();
--_waitingForKeychain;
if (_readPasswordJob->error() == NoError) {
- qDebug() << "got creds for" << _proxy << "from keychain";
+ qCDebug(lcProxy) << "got creds for" << _proxy << "from keychain";
_password = _readPasswordJob->textData();
return true;
}
_username.clear();
if (_readPasswordJob->error() != EntryNotFound) {
- qDebug() << "ReadPasswordJob failed with" << _readPasswordJob->errorString();
+ qCDebug(lcProxy) << "ReadPasswordJob failed with" << _readPasswordJob->errorString();
}
return false;
}
return;
}
- qDebug() << "storing" << _proxy;
+ qCDebug(lcProxy) << "storing" << _proxy;
_settings->setValue(keychainUsernameKey(), _username);
job->deleteLater();
if (job->error() != NoError) {
- qDebug() << "WritePasswordJob failed with" << job->errorString();
+ qCDebug(lcProxy) << "WritePasswordJob failed with" << job->errorString();
}
}
#include <theme.h>
#include <QTimer>
-#include <QDebug>
namespace OCC {
#include <qpushbutton.h>
#include <QFileIconProvider>
#include <QHeaderView>
-#include <QDebug>
#include <QSettings>
#include <QScopedValueRollback>
#include <QTreeWidgetItem>
namespace OCC
{
+Q_LOGGING_CATEGORY(lcServerNotification, "gui.servernotification", QtInfoMsg)
+
ServerNotificationHandler::ServerNotificationHandler(QObject *parent)
: QObject(parent)
{
// not yet valid, its assumed that notifications are available.
if( ptr->account()->capabilities().isValid() ) {
if( ! ptr->account()->capabilities().notificationsAvailable() ) {
- qDebug() << Q_FUNC_INFO << "Account" << ptr->account()->displayName() << "does not have notifications enabled.";
+ qCDebug(lcServerNotification) << "Account" << ptr->account()->displayName() << "does not have notifications enabled.";
deleteLater();
return;
}
void ServerNotificationHandler::slotNotificationsReceived(const QJsonDocument& json, int statusCode)
{
if( statusCode != 200 ) {
- qDebug() << Q_FUNC_INFO << "Notifications failed with status code " << statusCode;
+ qCDebug(lcServerNotification) << "Notifications failed with status code " << statusCode;
deleteLater();
return;
}
#include <QStandardItemModel>
#include <QStackedWidget>
#include <QPushButton>
-#include <QDebug>
#include <QSettings>
#include <QToolBar>
#include <QToolButton>
#include <QLabel>
#include <QStandardItemModel>
#include <QPushButton>
-#include <QDebug>
#include <QSettings>
#include <QPainter>
#include <QPainterPath>
*/
#include "sharedialog.h"
+#include "sharee.h"
#include "sharelinkwidget.h"
#include "shareusergroupwidget.h"
#include "ui_sharedialog.h"
#include <QFileInfo>
#include <QFileIconProvider>
-#include <QDebug>
#include <QPointer>
#include <QPushButton>
#include <QFrame>
const QVariant receivedPermissions = result["share-permissions"];
if (!receivedPermissions.toString().isEmpty()) {
_maxSharingPermissions = static_cast<SharePermissions>(receivedPermissions.toInt());
- qDebug() << "Received sharing permissions for" << _sharePath << _maxSharingPermissions;
+ qCDebug(lcSharing) << "Received sharing permissions for" << _sharePath << _maxSharingPermissions;
}
showSharingUi();
void ShareDialog::slotThumbnailFetched(const int &statusCode, const QByteArray &reply)
{
if (statusCode != 200) {
- qDebug() << Q_FUNC_INFO << "Status code: " << statusCode;
+ qCDebug(lcSharing) << "Thumbnail status code: " << statusCode;
return;
}
void ShareDialog::slotAccountStateChanged(int state) {
bool enabled = (state == AccountState::State::Connected);
- qDebug() << Q_FUNC_INFO << enabled;
+ qCDebug(lcSharing) << "Account connected?" << enabled;
if (_userGroupWidget != NULL) {
_userGroupWidget->setEnabled(enabled);
namespace OCC {
+Q_LOGGING_CATEGORY(lcSharing, "gui.sharing", QtInfoMsg)
+
Sharee::Sharee(const QString shareWith,
const QString displayName,
const Type type)
#include <QObject>
#include <QFlags>
#include <QAbstractListModel>
+#include <QLoggingCategory>
#include <QModelIndex>
#include <QVariant>
#include <QSharedPointer>
namespace OCC {
+Q_DECLARE_LOGGING_CATEGORY(lcSharing)
+
class Sharee {
public:
//
// _ui->checkBox_shareLink->setEnabled(false);
// uploadExternalFile();
- qDebug() << Q_FUNC_INFO << "Unable to share files not in a sync folder.";
+ qCDebug(lcSharing) << "Unable to share files not in a sync folder.";
return;
}
void ShareLinkWidget::slotSharesFetched(const QList<QSharedPointer<Share>> &shares)
{
const QString versionString = _account->serverVersion();
- qDebug() << Q_FUNC_INFO << versionString << "Fetched" << shares.count() << "shares";
+ qCDebug(lcSharing) << versionString << "Fetched" << shares.count() << "shares";
// Preserve the previous selection
QString selectedShareId;
_pi_password->stopAnimation();
_pi_editing->stopAnimation();
- qDebug() << "Error from server" << code << message;
+ qCDebug(lcSharing) << "Error from server" << code << message;
displayError(message);
}
{
auto tmpShares = reply.object().value("ocs").toObject().value("data").toArray();
const QString versionString = _account->serverVersion();
- qDebug() << Q_FUNC_INFO << versionString << "Fetched" << tmpShares.count() << "shares";
+ qCDebug(lcSharing) << versionString << "Fetched" << tmpShares.count() << "shares";
QList<QSharedPointer<Share>> shares;
shares.append(QSharedPointer<Share>(newShare));
}
- qDebug() << Q_FUNC_INFO << "Sending " << shares.count() << "shares";
+ qCDebug(lcSharing) << "Sending " << shares.count() << "shares";
emit sharesFetched(shares);
}
delete pi;
}
- qDebug() << "Error from server" << code << message;
+ qCDebug(lcSharing) << "Sharing error from server" << code << message;
_ui->errorLabel->setText(message);
_ui->errorLabel->show();
_ui->shareeLineEdit->setEnabled(true);
#include "asserts.h"
#include <QBitArray>
-#include <QDebug>
#include <QUrl>
#include <QMetaMethod>
#include <QMetaObject>
// The second number should be changed when there are new features.
#define MIRALL_SOCKET_API_VERSION "1.0"
-#define DEBUG qDebug() << "SocketApi: "
-
static inline QString removeTrailingSlash(QString path)
{
Q_ASSERT(path.endsWith(QLatin1Char('/')));
namespace OCC {
+Q_LOGGING_CATEGORY(lcSocketApi, "gui.socketapi", QtInfoMsg)
+
class BloomFilter {
// Initialize with m=1024 bits and k=2 (high and low 16 bits of a qHash).
// For a client navigating in less than 100 directories, this gives us a probability less than (1-e^(-2*100/1024))^2 = 0.03147872136 false positives.
void sendMessage(const QString& message, bool doWait = false) const
{
- DEBUG << "Sending message: " << message;
+ qCDebug(lcSocketApi) << "Sending message: " << message;
QString localMessage = message;
if( ! localMessage.endsWith(QLatin1Char('\n'))) {
localMessage.append(QLatin1Char('\n'));
socket->waitForBytesWritten(1000);
}
if( sent != bytesToSend.length() ) {
- qDebug() << "WARN: Could not send all data on socket for " << localMessage;
+ qCDebug(lcSocketApi) << "WARN: Could not send all data on socket for " << localMessage;
}
}
#endif
socketPath = runtimeDir + "/" + Theme::instance()->appName() + "/socket";
} else {
- DEBUG << "An unexpected system detected";
+ qCDebug(lcSocketApi) << "An unexpected system detected";
}
SocketApiServer::removeServer(socketPath);
QFileInfo info(socketPath);
if (!info.dir().exists()) {
bool result = info.dir().mkpath(".");
- DEBUG << "creating" << info.dir().path() << result;
+ qCDebug(lcSocketApi) << "creating" << info.dir().path() << result;
if( result ) {
QFile::setPermissions(socketPath,
QFile::Permissions(QFile::ReadOwner+QFile::WriteOwner+QFile::ExeOwner));
}
}
if(!_localServer.listen(socketPath)) {
- DEBUG << "can't start server" << socketPath;
+ qCDebug(lcSocketApi) << "can't start server" << socketPath;
} else {
- DEBUG << "server started, listening at " << socketPath;
+ qCDebug(lcSocketApi) << "server started, listening at " << socketPath;
}
connect(&_localServer, SIGNAL(newConnection()), this, SLOT(slotNewConnection()));
SocketApi::~SocketApi()
{
- DEBUG << "dtor";
+ qCDebug(lcSocketApi) << "dtor";
_localServer.close();
// All remaining sockets will be destroyed with _localServer, their parent
ASSERT(_listeners.isEmpty() || _listeners.first().socket->parent() == &_localServer);
if( ! socket ) {
return;
}
- DEBUG << "New connection" << socket;
+ qCDebug(lcSocketApi) << "New connection" << socket;
connect(socket, SIGNAL(readyRead()), this, SLOT(slotReadSocket()));
connect(socket, SIGNAL(disconnected()), this, SLOT(onLostConnection()));
connect(socket, SIGNAL(destroyed(QObject*)), this, SLOT(slotSocketDestroyed(QObject*)));
void SocketApi::onLostConnection()
{
- DEBUG << "Lost connection " << sender();
+ qCDebug(lcSocketApi) << "Lost connection " << sender();
sender()->deleteLater();
}
if(indexOfMethod != -1) {
staticMetaObject.method(indexOfMethod).invoke(this, Q_ARG(QString, argument), Q_ARG(SocketListener*, listener));
} else {
- DEBUG << "The command is not supported by this version of the client:" << command << "with argument:" << argument;
+ qCDebug(lcSocketApi) << "The command is not supported by this version of the client:" << command << "with argument:" << argument;
}
}
}
broadcastMessage(buildMessage(QLatin1String("UPDATE_VIEW"), rootPath));
} else {
- qDebug() << "Not sending UPDATE_VIEW for" << f->alias() << "because status() is" << f->syncResult().status();
+ qCDebug(lcSocketApi) << "Not sending UPDATE_VIEW for" << f->alias() << "because status() is" << f->syncResult().status();
}
}
}
void SocketApi::command_RETRIEVE_FOLDER_STATUS(const QString& argument, SocketListener* listener)
{
// This command is the same as RETRIEVE_FILE_STATUS
-
- //qDebug() << Q_FUNC_INFO << argument;
command_RETRIEVE_FILE_STATUS(argument, listener);
}
void SocketApi::command_RETRIEVE_FILE_STATUS(const QString& argument, SocketListener* listener)
{
- qDebug() << Q_FUNC_INFO << argument;
+ qCDebug(lcSocketApi) << argument;
QString statusString;
QString systemPath = QDir::cleanPath(argument);
if( systemPath.endsWith(QLatin1Char('/')) ) {
systemPath.truncate(systemPath.length()-1);
- qWarning() << "Removed trailing slash for directory: " << systemPath << "Status pushes won't have one.";
+ qCWarning(lcSocketApi) << "Removed trailing slash for directory: " << systemPath << "Status pushes won't have one.";
}
// The user probably visited this directory in the file shell.
// Let the listener know that it should now send status pushes for sibblings of this file.
void SocketApi::command_SHARE(const QString& localFile, SocketListener* listener)
{
- qDebug() << Q_FUNC_INFO << localFile;
+ qCDebug(lcSocketApi) << localFile;
auto theme = Theme::instance();
void SocketApi::command_SHARE_STATUS(const QString &localFile, SocketListener* listener)
{
- qDebug() << Q_FUNC_INFO << localFile;
+ qCDebug(lcSocketApi) << localFile;
Folder *shareFolder = FolderMan::instance()->folderForPath(localFile);
namespace OCC {
+Q_LOGGING_CATEGORY(lcSsl, "gui.ssl", QtInfoMsg)
+
SslButton::SslButton(QWidget *parent) :
QToolButton(parent)
{
QList<QSslCertificate> chain = account->_peerCertificateChain;
if (chain.isEmpty()) {
- qWarning() << "empty certificate chain";
+ qCWarning(lcSsl) << "Empty certificate chain";
return;
}
namespace OCC
{
+Q_LOGGING_CATEGORY(lcSslErrorDialog, "gui.sslerrordialog", QtInfoMsg)
+
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
namespace Utility {
// Used for QSSLCertificate::subjectInfo which returns a QStringList in Qt5, but a QString in Qt4
{
(void) conf;
if (!certs) {
- qDebug() << "Certs parameter required but is NULL!";
+ qCDebug(lcSslErrorDialog) << "Certs parameter required but is NULL!";
return false;
}
}
msg += QL("</div></body></html>");
- //qDebug() << "# # # # # # ";
- //qDebug() << msg;
QTextDocument *doc = new QTextDocument(0);
QString style = styleSheet();
doc->addResource( QTextDocument::StyleSheetResource, QUrl( QL("format.css") ), style);
if( _allTrusted ) return true;
bool stat = ( _ui->_cbTrustConnect->checkState() == Qt::Checked );
- qDebug() << "SSL-Connection is trusted: " << stat;
+ qCDebug(lcSslErrorDialog) << "SSL-Connection is trusted: " << stat;
return stat;
}
#include "systray.h"
#include "theme.h"
-#include <QDebug>
#ifdef USE_FDO_NOTIFICATIONS
#include <QDBusConnection>
#include <QString>
-#include <QDebug>
#import <Cocoa/Cocoa.h>
@interface NotificationCenterDelegate : NSObject
void sendOsXUserNotification(const QString &title, const QString &message)
{
- qDebug() << Q_FUNC_INFO << title << message;
Class cuserNotificationCenter = NSClassFromString(@"NSUserNotificationCenter");
id userNotificationCenter = [cuserNotificationCenter defaultUserNotificationCenter];
#include <QTreeView>
#include <QHelpEvent>
#include <QToolTip>
-#include <QDebug>
using namespace OCC;
auto checkInterval = cfg.updateCheckInterval();
if( checkInterval != _updateCheckTimer.interval() ) {
_updateCheckTimer.setInterval(checkInterval);
- qDebug() << "Setting new update check interval " << checkInterval;
+ qCDebug(lcUpdater) << "Setting new update check interval " << checkInterval;
}
// consider the skipUpdateCheck flag in the config.
if( cfg.skipUpdateCheck() ) {
- qDebug() << Q_FUNC_INFO << "Skipping update check because of config file";
+ qCDebug(lcUpdater) << "Skipping update check because of config file";
return;
}
case UpToDate:
case DownloadFailed:
case DownloadTimedOut:
- qDebug() << Q_FUNC_INFO << "checking for available update";
+ qCDebug(lcUpdater) << "checking for available update";
checkForUpdate();
break;
case DownloadComplete:
- qDebug() << "Update is downloaded, skip new check.";
+ qCDebug(lcUpdater) << "Update is downloaded, skip new check.";
break;
case UpdateOnlyAvailableThroughSystem:
- qDebug() << "Update is only available through system, skip check.";
+ qCDebug(lcUpdater) << "Update is only available through system, skip check.";
break;
}
}
QString updateFile = settings.value(updateAvailableC).toString();
settings.setValue(autoUpdateAttemptedC, true);
settings.sync();
- qDebug() << "Running updater" << updateFile;
+ qCDebug(lcUpdater) << "Running updater" << updateFile;
QProcess::startDetached(updateFile, QStringList() << "/S" << "/launch");
}
QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
reply->deleteLater();
if( reply->error() != QNetworkReply::NoError ) {
- qDebug() << "Failed to reach version check url: " << reply->errorString();
+ qCDebug(lcUpdater) << "Failed to reach version check url: " << reply->errorString();
return;
}
if( ok ) {
versionInfoArrived(_updateInfo);
} else {
- qDebug() << "Could not parse update information.";
+ qCDebug(lcUpdater) << "Could not parse update information.";
}
}
_file->close();
QFile::copy(_file->fileName(), _targetFile);
setDownloadState(DownloadComplete);
- qDebug() << "Downloaded" << url.toString() << "to" << _targetFile;
+ qCDebug(lcUpdater) << "Downloaded" << url.toString() << "to" << _targetFile;
ConfigFile cfg;
QSettings settings(cfg.configFile(), QSettings::IniFormat);
settings.setValue(updateTargetVersionC, updateInfo().version());
|| infoVersion <= currVersion
|| infoVersion <= seenVersion)
{
- qDebug() << "Client is on latest version!";
+ qCDebug(lcUpdater) << "Client is on latest version!";
setDownloadState(UpToDate);
} else {
QString url = info.downloadUrl();
// on linux, check if the installed binary is still the same version
// as the one that is running. If not, restart if possible.
const QByteArray fsVersion = Utility::versionOfInstalledBinary();
- qDebug() << Q_FUNC_INFO;
if( !(fsVersion.isEmpty() || _runningAppVersion.isEmpty()) && fsVersion != _runningAppVersion ) {
emit requestRestart();
}
if( info.version().isEmpty() ||
currentVer >= remoteVer ) {
- qDebug() << "Client is on latest version!";
+ qCDebug(lcUpdater) << "Client is on latest version!";
setDownloadState(UpToDate);
} else {
setDownloadState(UpdateOnlyAvailableThroughSystem);
#include "utility.h"
-#include <QDebug>
-
// Does not work yet
@interface DelegateObject : NSObject <SUUpdaterDelegate>
- (BOOL)updaterMayCheckForUpdates:(SUUpdater *)bundle;
// Only possible in later versions, we're not up to date here.
- (BOOL)updaterMayCheckForUpdates:(SUUpdater *)bundle
{
- qDebug() << Q_FUNC_INFO << "may check: YES";
+ qCDebug(lcUpdater) << "may check: YES";
return YES;
}
// Sent when a valid update is found by the update driver.
- (void)updater:(SUUpdater *)updater didFindValidUpdate:(SUAppcastItem *)update
{
- qDebug() << Q_FUNC_INFO;
}
// Sent when a valid update is not found.
// Does not seem to get called ever.
- (void)updaterDidNotFindUpdate:(SUUpdater *)update
{
- qDebug() << Q_FUNC_INFO;
}
// Sent immediately before installing the specified update.
- (void)updater:(SUUpdater *)updater willInstallUpdate:(SUAppcastItem *)update
{
- qDebug() << Q_FUNC_INFO;
}
// Tried implementing those methods, but they never ever seem to get called
//- (void) updater:(SUUpdater *)updater didAbortWithError:(NSError *)error
//{
-// qDebug() << Q_FUNC_INFO << [error localizedDescription];
//}
//- (void)updater:(SUUpdater *)updater didFinishLoadingAppcast:(SUAppcast *)appcast
//{
-// qDebug() << Q_FUNC_INFO << appcast;
//}
if ([expectedPath isEqualTo:bundlePath]) {
return true;
}
- qDebug() << "ERROR: We are not in /Applications, won't check for update!";
+ qCDebug(lcUpdater) << "ERROR: We are not in /Applications, won't check for update!";
return false;
}
void SparkleUpdater::backgroundCheckForUpdate()
{
- qDebug() << Q_FUNC_INFO << "launching background check";
+ qCDebug(lcUpdater) << "launching background check";
if (autoUpdaterAllowed()) {
[d->updater checkForUpdatesInBackground];
}
// All changes you do to this file will be lost.
#include "updateinfo.h"
+#include "updater.h"
#include <QtDebug>
#include <QFile>
UpdateInfo UpdateInfo::parseElement( const QDomElement &element, bool *ok )
{
if ( element.tagName() != QLatin1String("owncloudclient") ) {
- qCritical() << "Expected 'owncloudclient', got '" << element.tagName() << "'.";
+ qCCritical(lcUpdater) << "Expected 'owncloudclient', got '" << element.tagName() << "'.";
if ( ok ) *ok = false;
return UpdateInfo();
}
{
QFile file( filename );
if ( !file.open( QIODevice::ReadOnly ) ) {
- qCritical() << "Unable to open file '" << filename << "'";
+ qCCritical(lcUpdater) << "Unable to open file '" << filename << "'";
if ( ok ) *ok = false;
return UpdateInfo();
}
int errorLine, errorCol;
QDomDocument doc;
if ( !doc.setContent( &file, false, &errorMsg, &errorLine, &errorCol ) ) {
- qCritical() << errorMsg << " at " << errorLine << "," << errorCol;
+ qCCritical(lcUpdater) << errorMsg << " at " << errorLine << "," << errorCol;
if ( ok ) *ok = false;
return UpdateInfo();
}
int errorLine, errorCol;
QDomDocument doc;
if ( !doc.setContent( xml, false, &errorMsg, &errorLine, &errorCol ) ) {
- qCritical() << errorMsg << " at " << errorLine << "," << errorCol;
+ qCCritical(lcUpdater) << errorMsg << " at " << errorLine << "," << errorCol;
if ( ok ) *ok = false;
return UpdateInfo();
}
{
QFile file( filename );
if ( !file.open( QIODevice::WriteOnly ) ) {
- qCritical() << "Unable to open file '" << filename << "'";
+ qCCritical(lcUpdater) << "Unable to open file '" << filename << "'";
return false;
}
#include <QUrl>
#include <QProcess>
-#include <QDebug>
#include "updater/updater.h"
#include "updater/sparkleupdater.h"
namespace OCC {
+Q_LOGGING_CATEGORY(lcUpdater, "gui.updater", QtInfoMsg)
+
Updater *Updater::_instance = 0;
Updater * Updater::instance()
process.start( QLatin1String("lsb_release -a") );
process.waitForFinished();
QByteArray output = process.readAllStandardOutput();
- qDebug() << "Sys Info size: " << output.length();
+ qCDebug(lcUpdater) << "Sys Info size: " << output.length();
if( output.length() > 1024 ) output.clear(); // don't send too much.
return QString::fromLocal8Bit( output.toBase64() );
updateBaseUrl = QUrl(QLatin1String(APPLICATION_UPDATE_URL));
}
if (!updateBaseUrl.isValid() || updateBaseUrl.host() == ".") {
- qDebug() << "Not a valid updater URL, will not do update check";
+ qCDebug(lcUpdater) << "Not a valid updater URL, will not do update check";
return 0;
}
updateBaseUrl = addQueryParams(updateBaseUrl);
#ifndef UPDATER_H
#define UPDATER_H
+#include <QLoggingCategory>
#include <QObject>
class QUrl;
namespace OCC {
+Q_DECLARE_LOGGING_CATEGORY(lcUpdater)
+
class Updater : public QObject {
Q_OBJECT
public:
namespace OCC
{
+Q_LOGGING_CATEGORY(lcWizard, "gui.wizard", QtInfoMsg)
+
OwncloudWizard::OwncloudWizard(QWidget *parent)
: QWizard(parent),
_account(0),
case WizardCommon::Page_ServerSetup:
case WizardCommon::Page_Result:
- qWarning("Should not happen at this stage.");
+ qCWarning(lcWizard, "Should not happen at this stage.");
break;
}
// TODO: update this function
void OwncloudWizard::slotCurrentPageChanged( int id )
{
- qDebug() << "Current Wizard page changed to " << id;
+ qCDebug(lcWizard) << "Current Wizard page changed to " << id;
if( id == WizardCommon::Page_ServerSetup ) {
emit clearPendingRequests();
void OwncloudWizard::appendToConfigurationLog( const QString& msg, LogType /*type*/ )
{
_setupLog << msg;
- qDebug() << "Setup-Log: " << msg;
+ qCDebug(lcWizard) << "Setup-Log: " << msg;
}
void OwncloudWizard::setOCUrl( const QString& url )
#define MIRALL_OWNCLOUD_WIZARD_H
#include <QWizard>
+#include <QLoggingCategory>
#include <QSslKey>
#include <QSslCertificate>
namespace OCC {
+Q_DECLARE_LOGGING_CATEGORY(lcWizard)
+
class OwncloudSetupPage;
class OwncloudHttpCredsPage;
#ifndef NO_SHIBBOLETH
* for more details.
*/
-#include <QDebug>
#include <QDesktopServices>
#include <QDir>
#include <QUrl>
{
Theme* theme = Theme::instance();
QUrl url = QUrl(field("OCUrl").toString() + theme->wizardUrlPostfix());
- qDebug() << Q_FUNC_INFO << url;
QDesktopServices::openUrl(url);
}
#include <QStyle>
#include <QStyleOptionFrame>
-#include <QDebug>
-
#include "postfixlineedit.h"
namespace OCC {
if (prefixString.endsWith(postfix())) {
prefixString.chop(postfix().length());
}
- qDebug() << prefixString;
setText(prefixString);
}
* for more details.
*/
+#include <QLoggingCategory>
#include <QNetworkRequest>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QStack>
#include <QTimer>
#include <QMutex>
-#include <QDebug>
#include <QCoreApplication>
#include "networkjobs.h"
namespace OCC {
+Q_LOGGING_CATEGORY(lcNetworkJob, "sync.networkjob", QtInfoMsg)
AbstractNetworkJob::AbstractNetworkJob(AccountPtr account, const QString &path, QObject *parent)
: QObject(parent)
void AbstractNetworkJob::setTimeout(qint64 msec)
{
- //qDebug() << Q_FUNC_INFO << msec;
-
_timer.start(msec);
}
_timer.stop();
if( _reply->error() == QNetworkReply::SslHandshakeFailedError ) {
- qDebug() << "SslHandshakeFailedError: " << errorString() << " : can be caused by a webserver wanting SSL client certificates";
+ qCDebug(lcNetworkJob) << "SslHandshakeFailedError: " << errorString() << " : can be caused by a webserver wanting SSL client certificates";
}
if( _reply->error() != QNetworkReply::NoError ) {
- qDebug() << Q_FUNC_INFO << _reply->error() << errorString()
+ qCDebug(lcNetworkJob) << _reply->error() << errorString()
<< _reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
if (_reply->error() == QNetworkReply::ProxyAuthenticationRequiredError) {
- qDebug() << Q_FUNC_INFO << _reply->rawHeader("Proxy-Authenticate");
+ qCDebug(lcNetworkJob) << _reply->rawHeader("Proxy-Authenticate");
}
emit networkError(_reply);
}
QByteArray verb = requestVerb(*reply());
if (requestedUrl.scheme() == QLatin1String("https") &&
redirectUrl.scheme() == QLatin1String("http")) {
- qWarning() << this << "HTTPS->HTTP downgrade detected!";
+ qCWarning(lcNetworkJob) << this << "HTTPS->HTTP downgrade detected!";
} else if (requestedUrl == redirectUrl || _redirectCount >= maxRedirects()) {
- qWarning() << this << "Redirect loop detected!";
+ qCWarning(lcNetworkJob) << this << "Redirect loop detected!";
} else if (_requestBody && _requestBody->isSequential()) {
- qWarning() << this << "cannot redirect request with sequential body";
+ qCWarning(lcNetworkJob) << this << "cannot redirect request with sequential body";
} else if (verb.isEmpty()) {
- qWarning() << this << "cannot redirect request: could not detect original verb";
+ qCWarning(lcNetworkJob) << this << "cannot redirect request: could not detect original verb";
} else {
// Create the redirected request and send it
- qDebug() << "Redirecting" << verb << requestedUrl << redirectUrl;
+ qCDebug(lcNetworkJob) << "Redirecting" << verb << requestedUrl << redirectUrl;
resetTimeout();
if (_requestBody) {
_requestBody->seek(0);
const QString displayUrl = QString( "%1://%2%3").arg(url.scheme()).arg(url.host()).arg(url.path());
QString parentMetaObjectName = parent() ? parent()->metaObject()->className() : "";
- qDebug() << "!!!" << metaObject()->className() << "created for" << displayUrl << "+" << path() << parentMetaObjectName;
+ qCDebug(lcNetworkJob) << metaObject()->className() << "created for" << displayUrl << "+" << path() << parentMetaObjectName;
}
void AbstractNetworkJob::slotTimeout()
{
_timedout = true;
- qDebug() << this << "Timeout" << (reply() ? reply()->request().url() : path());
+ qCDebug(lcNetworkJob) << this << "Timeout" << (reply() ? reply()->request().url() : path());
onTimedOut();
}
* for more details.
*/
+#include <QLoggingCategory>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QNetworkProxy>
namespace OCC
{
+Q_LOGGING_CATEGORY(lcAccessManager, "sync.accessmanager", QtInfoMsg)
+
AccessManager::AccessManager(QObject* parent)
: QNetworkAccessManager (parent)
{
{
QNetworkCookie cookie(rawCookie.left(rawCookie.indexOf('=')),
rawCookie.mid(rawCookie.indexOf('=')+1));
- qDebug() << Q_FUNC_INFO << cookie.name() << cookie.value();
+ qCDebug(lcAccessManager) << cookie.name() << cookie.value();
QList<QNetworkCookie> cookieList;
cookieList.append(cookie);
#include "asserts.h"
#include <QSettings>
+#include <QLoggingCategory>
#include <QMutex>
#include <QNetworkReply>
#include <QNetworkAccessManager>
#include <QNetworkCookieJar>
#include <QFileInfo>
#include <QDir>
-#include <QDebug>
#include <QSslKey>
namespace OCC {
+Q_LOGGING_CATEGORY(lcAccount, "sync.account", QtInfoMsg)
Account::Account(QObject *parent)
: QObject(parent)
return;
}
- qDebug() << "Resetting QNAM";
+ qCDebug(lcAccount) << "Resetting QNAM";
QNetworkCookieJar* jar = _am->cookieJar();
// Use a QSharedPointer to allow locking the life of the QNAM on the stack.
// If all certs have previously been rejected by the user, don't ask again.
if( allPreviouslyRejected ) {
- qDebug() << out << "Certs not trusted by user decision, returning.";
+ qCDebug(lcAccount) << out << "Certs not trusted by user decision, returning.";
return;
}
QList<QSslCertificate> approvedCerts;
if (_sslErrorHandler.isNull() ) {
- qDebug() << out << Q_FUNC_INFO << "called without valid SSL error handler for account" << url();
+ qCDebug(lcAccount) << out << "called without valid SSL error handler for account" << url();
return;
}
addApprovedCerts(approvedCerts);
emit wantsAccountSaved(this);
// all ssl certs are known and accepted. We can ignore the problems right away.
-// qDebug() << out << "Certs are known and trusted! This is not an actual error.";
+ qCDebug(lcAccount) << out << "Certs are known and trusted! This is not an actual error.";
// Warning: Do *not* use ignoreSslErrors() (without args) here:
// it permanently ignores all SSL errors for this host, even
#include <winbase.h>
#endif
+#include <QLoggingCategory>
#include <QTimer>
#include <QObject>
namespace OCC {
+Q_LOGGING_CATEGORY(lcBandwidthManager, "sync.bandwidthmanager", QtInfoMsg)
+
// Because of the many layers of buffering inside Qt (and probably the OS and the network)
// we cannot lower this value much more. If we do, the estimated bw will be very high
// because the buffers fill fast while the actual network algorithms are not relevant yet.
BandwidthManager::~BandwidthManager()
{
- qDebug() << Q_FUNC_INFO;
}
void BandwidthManager::registerUploadDevice(UploadDevice *p)
{
- //qDebug() << Q_FUNC_INFO << p;
_absoluteUploadDeviceList.append(p);
_relativeUploadDeviceList.append(p);
QObject::connect(p, SIGNAL(destroyed(QObject*)), this, SLOT(unregisterUploadDevice(QObject*)));
void BandwidthManager::unregisterUploadDevice(UploadDevice* p)
{
- //qDebug() << Q_FUNC_INFO << p;
_absoluteUploadDeviceList.removeAll(p);
_relativeUploadDeviceList.removeAll(p);
if (p == _relativeLimitCurrentMeasuredDevice) {
void BandwidthManager::registerDownloadJob(GETFileJob* j)
{
- //qDebug() << Q_FUNC_INFO << j;
_downloadJobList.append(j);
QObject::connect(j, SIGNAL(destroyed(QObject*)), this, SLOT(unregisterDownloadJob(QObject*)));
return;
}
if (_relativeLimitCurrentMeasuredDevice == 0) {
- qDebug() << Q_FUNC_INFO << "No device set, just waiting 1 sec";
+ qCDebug(lcBandwidthManager) << "No device set, just waiting 1 sec";
_relativeUploadDelayTimer.setInterval(1000);
_relativeUploadDelayTimer.start();
return;
}
-// qDebug() << Q_FUNC_INFO << _relativeUploadDeviceList.count() << "Starting Delay";
+ qCDebug(lcBandwidthManager) << _relativeUploadDeviceList.count() << "Starting Delay";
qint64 relativeLimitProgressMeasured = (_relativeLimitCurrentMeasuredDevice->_readWithProgress
+ _relativeLimitCurrentMeasuredDevice->_read) / 2;
qint64 relativeLimitProgressDifference = relativeLimitProgressMeasured - _relativeUploadLimitProgressAtMeasuringRestart;
-// qDebug() << Q_FUNC_INFO << _relativeUploadLimitProgressAtMeasuringRestart
-// << relativeLimitProgressMeasured << relativeLimitProgressDifference;
+ qCDebug(lcBandwidthManager) << _relativeUploadLimitProgressAtMeasuringRestart
+ << relativeLimitProgressMeasured << relativeLimitProgressDifference;
-// qint64 speedkBPerSec = (relativeLimitProgressDifference / relativeLimitMeasuringTimerIntervalMsec*1000.0) / 1024.0;
-// qDebug() << Q_FUNC_INFO << relativeLimitProgressDifference/1024 <<"kB =>" << speedkBPerSec << "kB/sec on full speed ("
-// << _relativeLimitCurrentMeasuredDevice->_readWithProgress << _relativeLimitCurrentMeasuredDevice->_read
-// << qAbs(_relativeLimitCurrentMeasuredDevice->_readWithProgress
-// - _relativeLimitCurrentMeasuredDevice->_read) << ")";
+ qint64 speedkBPerSec = (relativeLimitProgressDifference / relativeLimitMeasuringTimerIntervalMsec*1000.0) / 1024.0;
+ qCDebug(lcBandwidthManager) << relativeLimitProgressDifference/1024 <<"kB =>" << speedkBPerSec << "kB/sec on full speed ("
+ << _relativeLimitCurrentMeasuredDevice->_readWithProgress << _relativeLimitCurrentMeasuredDevice->_read
+ << qAbs(_relativeLimitCurrentMeasuredDevice->_readWithProgress
+ - _relativeLimitCurrentMeasuredDevice->_read) << ")";
qint64 uploadLimitPercent = -_currentUploadLimit;
// don't use too extreme values
qint64 wholeTimeMsec = (100.0 / uploadLimitPercent) * relativeLimitMeasuringTimerIntervalMsec;
qint64 waitTimeMsec = wholeTimeMsec - relativeLimitMeasuringTimerIntervalMsec;
qint64 realWaitTimeMsec = waitTimeMsec + wholeTimeMsec;
-// qDebug() << Q_FUNC_INFO << waitTimeMsec << " - "<< realWaitTimeMsec <<
-// " msec for " << uploadLimitPercent << "%";
-// qDebug() << Q_FUNC_INFO << "XXXX" << uploadLimitPercent << relativeLimitMeasuringTimerIntervalMsec;
+ qCDebug(lcBandwidthManager) << waitTimeMsec << " - "<< realWaitTimeMsec <<
+ " msec for " << uploadLimitPercent << "%";
// We want to wait twice as long since we want to give all
// devices the same quota we used now since we don't want
int deviceCount = _relativeUploadDeviceList.count();
qint64 quotaPerDevice = relativeLimitProgressDifference * (uploadLimitPercent / 100.0) / deviceCount + 1.0;
-// qDebug() << Q_FUNC_INFO << "YYYY" << relativeLimitProgressDifference << uploadLimitPercent << deviceCount;
Q_FOREACH(UploadDevice *ud, _relativeUploadDeviceList) {
ud->setBandwidthLimited(true);
ud->setChoked(false);
ud->giveBandwidthQuota(quotaPerDevice);
-// qDebug() << Q_FUNC_INFO << "Gave" << quotaPerDevice/1024.0 << "kB to" << ud;
+ qCDebug(lcBandwidthManager) << "Gave" << quotaPerDevice/1024.0 << "kB to" << ud;
}
_relativeLimitCurrentMeasuredDevice = 0;
}
return;
}
-// qDebug() << Q_FUNC_INFO << _relativeUploadDeviceList.count() << "Starting measuring";
+ qCDebug(lcBandwidthManager) << _relativeUploadDeviceList.count() << "Starting measuring";
// Take first device and then append it again (= we round robin all devices)
_relativeLimitCurrentMeasuredDevice = _relativeUploadDeviceList.takeFirst();
return;
}
if (_relativeLimitCurrentMeasuredJob == 0) {
- qDebug() << Q_FUNC_INFO << "No job set, just waiting 1 sec";
+ qCDebug(lcBandwidthManager) << "No job set, just waiting 1 sec";
_relativeDownloadDelayTimer.setInterval(1000);
_relativeDownloadDelayTimer.start();
return;
}
-// qDebug() << Q_FUNC_INFO << _downloadJobList.count() << "Starting Delay";
+ qCDebug(lcBandwidthManager) << _downloadJobList.count() << "Starting Delay";
qint64 relativeLimitProgressMeasured = _relativeLimitCurrentMeasuredJob->currentDownloadPosition();
qint64 relativeLimitProgressDifference = relativeLimitProgressMeasured - _relativeDownloadLimitProgressAtMeasuringRestart;
- qDebug() << Q_FUNC_INFO << _relativeDownloadLimitProgressAtMeasuringRestart
+ qCDebug(lcBandwidthManager) << _relativeDownloadLimitProgressAtMeasuringRestart
<< relativeLimitProgressMeasured << relativeLimitProgressDifference;
-// qint64 speedkBPerSec = (relativeLimitProgressDifference / relativeLimitMeasuringTimerIntervalMsec*1000.0) / 1024.0;
-// qDebug() << Q_FUNC_INFO << relativeLimitProgressDifference/1024 <<"kB =>" << speedkBPerSec << "kB/sec on full speed ("
-// << _relativeLimitCurrentMeasuredJob->currentDownloadPosition() ;
+ qint64 speedkBPerSec = (relativeLimitProgressDifference / relativeLimitMeasuringTimerIntervalMsec*1000.0) / 1024.0;
+ qCDebug(lcBandwidthManager) << relativeLimitProgressDifference/1024 <<"kB =>" << speedkBPerSec << "kB/sec on full speed ("
+ << _relativeLimitCurrentMeasuredJob->currentDownloadPosition() ;
qint64 downloadLimitPercent = -_currentDownloadLimit;
// don't use too extreme values
qint64 wholeTimeMsec = (100.0 / downloadLimitPercent) * relativeLimitMeasuringTimerIntervalMsec;
qint64 waitTimeMsec = wholeTimeMsec - relativeLimitMeasuringTimerIntervalMsec;
qint64 realWaitTimeMsec = waitTimeMsec + wholeTimeMsec;
-// qDebug() << Q_FUNC_INFO << waitTimeMsec << " - "<< realWaitTimeMsec <<
-// " msec for " << downloadLimitPercent << "%";
-// qDebug() << Q_FUNC_INFO << "XXXX" << downloadLimitPercent << relativeLimitMeasuringTimerIntervalMsec;
+ qCDebug(lcBandwidthManager) << waitTimeMsec << " - "<< realWaitTimeMsec <<
+ " msec for " << downloadLimitPercent << "%";
// We want to wait twice as long since we want to give all
// devices the same quota we used now since we don't want
int jobCount = _downloadJobList.count();
qint64 quota = relativeLimitProgressDifference * (downloadLimitPercent / 100.0);
-// if (quota > 20*1024) {
-// qDebug() << "======== ADJUSTING QUOTA FROM " << quota << " TO " << quota - 20*1024;
-// quota -= 20*1024;
-// }
+ if (quota > 20*1024) {
+ qCDebug(lcBandwidthManager) << "======== ADJUSTING QUOTA FROM " << quota << " TO " << quota - 20*1024;
+ quota -= 20*1024;
+ }
qint64 quotaPerJob = quota / jobCount + 1.0;
-// qDebug() << Q_FUNC_INFO << "YYYY" << relativeLimitProgressDifference << downloadLimitPercent << jobCount;
Q_FOREACH(GETFileJob *gfj, _downloadJobList) {
gfj->setBandwidthLimited(true);
gfj->setChoked(false);
gfj->giveBandwidthQuota(quotaPerJob);
-// qDebug() << Q_FUNC_INFO << "Gave" << quotaPerJob/1024.0 << "kB to" << gfj;
+ qCDebug(lcBandwidthManager) << "Gave" << quotaPerJob/1024.0 << "kB to" << gfj;
}
_relativeLimitCurrentMeasuredDevice = 0;
}
}
if (_downloadJobList.isEmpty()) {
- //qDebug() << Q_FUNC_INFO << _downloadJobList.count() << "No jobs?";
+ qCDebug(lcBandwidthManager) << _downloadJobList.count() << "No jobs?";
return;
}
-// qDebug() << Q_FUNC_INFO << _downloadJobList.count() << "Starting measuring";
+ qCDebug(lcBandwidthManager) << _downloadJobList.count() << "Starting measuring";
// Take first device and then append it again (= we round robin all devices)
_relativeLimitCurrentMeasuredJob = _downloadJobList.takeFirst();
void BandwidthManager::switchingTimerExpired() {
qint64 newUploadLimit = _propagator->_uploadLimit.fetchAndAddAcquire(0);
if (newUploadLimit != _currentUploadLimit) {
- qDebug() << Q_FUNC_INFO << "Upload Bandwidth limit changed" << _currentUploadLimit << newUploadLimit;
+ qCDebug(lcBandwidthManager) << "Upload Bandwidth limit changed" << _currentUploadLimit << newUploadLimit;
_currentUploadLimit = newUploadLimit;
Q_FOREACH(UploadDevice *ud, _relativeUploadDeviceList) {
if (newUploadLimit == 0) {
}
qint64 newDownloadLimit = _propagator->_downloadLimit.fetchAndAddAcquire(0);
if (newDownloadLimit != _currentDownloadLimit) {
- qDebug() << Q_FUNC_INFO << "Download Bandwidth limit changed" << _currentDownloadLimit << newDownloadLimit;
+ qCDebug(lcBandwidthManager) << "Download Bandwidth limit changed" << _currentDownloadLimit << newDownloadLimit;
_currentDownloadLimit = newDownloadLimit;
Q_FOREACH(GETFileJob *j, _downloadJobList) {
if (usingAbsoluteDownloadLimit()) {
{
if (usingAbsoluteUploadLimit() && _absoluteUploadDeviceList.count() > 0) {
qint64 quotaPerDevice = _currentUploadLimit / qMax(1, _absoluteUploadDeviceList.count());
-// qDebug() << Q_FUNC_INFO << quotaPerDevice << _absoluteUploadDeviceList.count() << _currentUploadLimit;
+ qCDebug(lcBandwidthManager) << quotaPerDevice << _absoluteUploadDeviceList.count() << _currentUploadLimit;
Q_FOREACH(UploadDevice *device, _absoluteUploadDeviceList) {
device->giveBandwidthQuota(quotaPerDevice);
-// qDebug() << Q_FUNC_INFO << "Gave " << quotaPerDevice/1024.0 << " kB to" << device;
+ qCDebug(lcBandwidthManager) << "Gave " << quotaPerDevice/1024.0 << " kB to" << device;
}
}
if (usingAbsoluteDownloadLimit() && _downloadJobList.count() > 0) {
qint64 quotaPerJob = _currentDownloadLimit / qMax(1, _downloadJobList.count());
-// qDebug() << Q_FUNC_INFO << quotaPerJob << _downloadJobList.count() << _currentDownloadLimit;
+ qCDebug(lcBandwidthManager) << quotaPerJob << _downloadJobList.count() << _currentDownloadLimit;
Q_FOREACH(GETFileJob *j, _downloadJobList) {
j->giveBandwidthQuota(quotaPerJob);
-// qDebug() << Q_FUNC_INFO << "Gave " << quotaPerJob/1024.0 << " kB to" << j;
+ qCDebug(lcBandwidthManager) << "Gave " << quotaPerJob/1024.0 << " kB to" << j;
}
}
}
#include "configfile.h"
#include <QVariantMap>
-#include <QDebug>
namespace OCC {
#include "propagatorjobs.h"
#include "account.h"
+#include <QLoggingCategory>
#include <qtconcurrentrun.h>
/** \file checksums.cpp
namespace OCC {
+Q_LOGGING_CATEGORY(lcChecksums, "sync.checksums", QtInfoMsg)
+
QByteArray makeChecksumHeader(const QByteArray& checksumType, const QByteArray& checksum)
{
QByteArray header = checksumType;
#endif
// for an unknown checksum or no checksum, we're done right now
if( !checksumType.isEmpty() ) {
- qDebug() << "Unknown checksum type:" << checksumType;
+ qCDebug(lcChecksums) << "Unknown checksum type:" << checksumType;
}
return QByteArray();
}
}
if( !parseChecksumHeader(checksumHeader, &_expectedChecksumType, &_expectedChecksum) ) {
- qDebug() << "Checksum header malformed:" << checksumHeader;
+ qCDebug(lcChecksums) << "Checksum header malformed:" << checksumHeader;
emit validationFailed(tr("The checksum header is malformed."));
return;
}
{
QByteArray checksumType = _journal->getChecksumType(checksumTypeId);
if (checksumType.isEmpty()) {
- qDebug() << "Checksum type" << checksumTypeId << "not found";
+ qCDebug(lcChecksums) << "Checksum type" << checksumTypeId << "not found";
return QByteArray();
}
QByteArray checksum = ComputeChecksum::computeNow(path, checksumType);
if (checksum.isNull()) {
- qDebug() << "Failed to compute checksum" << checksumType << "for" << path;
+ qCDebug(lcChecksums) << "Failed to compute checksum" << checksumType << "for" << path;
return QByteArray();
}
#include "clientproxy.h"
#include "configfile.h"
+#include <QLoggingCategory>
#include <QUrl>
#include <QThreadPool>
namespace OCC {
+Q_LOGGING_CATEGORY(lcClientProxy, "sync.clientproxy", QtInfoMsg)
+
ClientProxy::ClientProxy(QObject *parent) :
QObject(parent)
{
switch(proxyType) {
case QNetworkProxy::NoProxy:
- qDebug() << "Set proxy configuration to use NO proxy";
+ qCDebug(lcClientProxy) << "Set proxy configuration to use NO proxy";
QNetworkProxyFactory::setUseSystemConfiguration(false);
QNetworkProxy::setApplicationProxy(QNetworkProxy::NoProxy);
break;
case QNetworkProxy::DefaultProxy:
- qDebug() << "Set proxy configuration to use system configuration";
+ qCDebug(lcClientProxy) << "Set proxy configuration to use system configuration";
QNetworkProxyFactory::setUseSystemConfiguration(true);
break;
case QNetworkProxy::Socks5Proxy:
proxy.setType(QNetworkProxy::Socks5Proxy);
- qDebug() << "Set proxy configuration to SOCKS5" << printQNetworkProxy(proxy);
+ qCDebug(lcClientProxy) << "Set proxy configuration to SOCKS5" << printQNetworkProxy(proxy);
QNetworkProxyFactory::setUseSystemConfiguration(false);
QNetworkProxy::setApplicationProxy(proxy);
break;
case QNetworkProxy::HttpProxy:
proxy.setType(QNetworkProxy::HttpProxy);
- qDebug() << "Set proxy configuration to HTTP" << printQNetworkProxy(proxy);
+ qCDebug(lcClientProxy) << "Set proxy configuration to HTTP" << printQNetworkProxy(proxy);
QNetworkProxyFactory::setUseSystemConfiguration(false);
QNetworkProxy::setApplicationProxy(proxy);
break;
#include <QDir>
#include <QFile>
#include <QFileInfo>
+#include <QLoggingCategory>
#include <QSettings>
-#include <QDebug>
#include <QNetworkProxy>
#define DEFAULT_REMOTE_POLL_INTERVAL 30000 // default remote poll time in milliseconds
namespace OCC {
+Q_LOGGING_CATEGORY(lcConfigFile, "sync.configfile", QtInfoMsg)
+
//static const char caCertsKeyC[] = "CaCertificates"; only used from account.cpp
static const char remotePollIntervalC[] = "remotePollInterval";
static const char forceSyncIntervalC[] = "forceSyncInterval";
QSettings settings(config, QSettings::IniFormat);
settings.beginGroup( defaultConnection() );
-
- // qDebug() << Q_FUNC_INFO << "Loading config: " << config << " (URL is " << settings.value("url").toString() << ")";
}
bool ConfigFile::setConfDir(const QString &value)
}
if( fi.exists() && fi.isDir() ) {
dirPath = fi.absoluteFilePath();
- qDebug() << "** Using custom config dir " << dirPath;
+ qCDebug(lcConfigFile) << "** Using custom config dir " << dirPath;
_confDir=dirPath;
return true;
}
int remoteInterval = settings.value( QLatin1String(remotePollIntervalC), DEFAULT_REMOTE_POLL_INTERVAL ).toInt();
if( remoteInterval < 5000) {
- qDebug() << "Remote Interval is less than 5 seconds, reverting to" << DEFAULT_REMOTE_POLL_INTERVAL;
+ qCDebug(lcConfigFile) << "Remote Interval is less than 5 seconds, reverting to" << DEFAULT_REMOTE_POLL_INTERVAL;
remoteInterval = DEFAULT_REMOTE_POLL_INTERVAL;
}
return remoteInterval;
if( connection.isEmpty() ) con = defaultConnection();
if( interval < 5000 ) {
- qDebug() << "Remote Poll interval of " << interval << " is below five seconds.";
+ qCDebug(lcConfigFile) << "Remote Poll interval of " << interval << " is below five seconds.";
return;
}
QSettings settings(configFile(), QSettings::IniFormat);
quint64 defaultInterval = 2 * 60 * 60 * 1000ull; // 2h
quint64 interval = settings.value( QLatin1String(forceSyncIntervalC), defaultInterval ).toULongLong();
if( interval < pollInterval) {
- qDebug() << "Force sync interval is less than the remote poll inteval, reverting to" << pollInterval;
+ qCDebug(lcConfigFile) << "Force sync interval is less than the remote poll inteval, reverting to" << pollInterval;
interval = pollInterval;
}
return interval;
quint64 defaultInterval = 5 * 60 * 1000ull; // 5 minutes
quint64 interval = settings.value( QLatin1String(notificationRefreshIntervalC), defaultInterval ).toULongLong();
if( interval < 60*1000ull) {
- qDebug() << "notification refresh interval smaller than one minute, setting to one minute";
+ qCDebug(lcConfigFile) << "notification refresh interval smaller than one minute, setting to one minute";
interval = 60*1000ull;
}
return interval;
int minInterval = 1000*60*5;
if( interval < minInterval) {
- qDebug() << "Update check interval less than five minutes, setting " << minInterval;
+ qCDebug(lcConfigFile) << "Update check interval less than five minutes, setting " << minInterval;
interval = minInterval;
}
return interval;
* for more details.
*/
-#include <QtCore>
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <QLoggingCategory>
#include <QNetworkReply>
#include <QNetworkProxyFactory>
#include <QPixmap>
namespace OCC {
+Q_LOGGING_CATEGORY(lcConnectionValidator, "sync.connectionvalidator", QtInfoMsg)
+
// Make sure the timeout for this job is less than how often we get called
// This makes sure we get tried often enough without "ConnectionValidator already running"
static qint64 timeoutToUseMsec = qMax(1000, ConnectionValidator::DefaultCallingIntervalMsec - 5*1000);
reportResult( NotConfigured );
return;
}
- qDebug() << "Checking server and authentication";
+ qCDebug(lcConnectionValidator) << "Checking server and authentication";
_isCheckingServerAndAuth = true;
// Lookup system proxy in a thread https://github.com/owncloud/client/issues/2993
if (ClientProxy::isUsingSystemDefault()) {
- qDebug() << "Trying to look up system proxy";
+ qCDebug(lcConnectionValidator) << "Trying to look up system proxy";
ClientProxy::lookupSystemProxyAsync(_account->url(),
this, SLOT(systemProxyLookupDone(QNetworkProxy)));
} else {
void ConnectionValidator::systemProxyLookupDone(const QNetworkProxy &proxy) {
if (!_account) {
- qDebug() << "Bailing out, Account had been deleted";
+ qCDebug(lcConnectionValidator) << "Bailing out, Account had been deleted";
return;
}
if (proxy.type() != QNetworkProxy::NoProxy) {
- qDebug() << "Setting QNAM proxy to be system proxy" << printQNetworkProxy(proxy);
+ qCDebug(lcConnectionValidator) << "Setting QNAM proxy to be system proxy" << printQNetworkProxy(proxy);
} else {
- qDebug() << "No system proxy set by OS";
+ qCDebug(lcConnectionValidator) << "No system proxy set by OS";
}
_account->networkAccessManager()->setProxy(proxy);
QString serverVersion = CheckServerJob::version(info);
// status.php was found.
- qDebug() << "** Application: ownCloud found: "
+ qCDebug(lcConnectionValidator) << "** Application: ownCloud found: "
<< url << " with version "
<< CheckServerJob::versionString(info)
<< "(" << serverVersion << ")";
void ConnectionValidator::slotNoStatusFound(QNetworkReply *reply)
{
auto job = qobject_cast<CheckServerJob *>(sender());
- qDebug() << Q_FUNC_INFO << reply->error() << job->errorString() << reply->peek(1024);
+ qCDebug(lcConnectionValidator) << reply->error() << job->errorString() << reply->peek(1024);
if (!_account->credentials()->ready()) {
// This could be needed for SSL client certificates
// We need to load them from keychain and try
// simply GET the webdav root, will fail if credentials are wrong.
// continue in slotAuthCheck here :-)
- qDebug() << "# Check whether authenticated propfind works.";
+ qCDebug(lcConnectionValidator) << "# Check whether authenticated propfind works.";
PropfindJob *job = new PropfindJob(_account, "/", this);
job->setTimeout(timeoutToUseMsec);
job->setProperties(QList<QByteArray>() << "getlastmodified");
if( reply->error() == QNetworkReply::AuthenticationRequiredError ||
!_account->credentials()->stillValid(reply)) {
- qDebug() << reply->error() << job->errorString();
- qDebug() << "******** Password is wrong!";
+ qCDebug(lcConnectionValidator) << reply->error() << job->errorString();
+ qCDebug(lcConnectionValidator) << "******** Password is wrong!";
_errors << tr("The provided credentials are not correct");
stat = CredentialsMissingOrWrong;
void ConnectionValidator::slotCapabilitiesRecieved(const QJsonDocument &json)
{
auto caps = json.object().value("ocs").toObject().value("data").toObject().value("capabilities").toObject();
- qDebug() << "Server capabilities" << caps;
+ qCDebug(lcConnectionValidator) << "Server capabilities" << caps;
_account->setCapabilities(caps.toVariantMap());
// New servers also report the version in the capabilities
bool ConnectionValidator::setAndCheckServerVersion(const QString& version)
{
- qDebug() << _account->url() << "has server version" << version;
+ qCInfo(lcConnectionValidator) << _account->url() << "has server version" << version;
_account->setServerVersion(version);
// We cannot deal with servers < 5.0.0
#include "configfile.h"
-#include <QDebug>
#include <QFile>
#include <QDateTime>
+#include <QLoggingCategory>
#include <QNetworkCookie>
#include <QDataStream>
namespace OCC {
+Q_LOGGING_CATEGORY(lcCookieJar, "sync.cookiejar", QtInfoMsg)
+
namespace {
const unsigned int JAR_VERSION = 23;
}
stream >> value;
QList<QNetworkCookie> newCookies = QNetworkCookie::parseCookies(value);
if (newCookies.count() == 0 && value.length() != 0) {
- qWarning() << "CookieJar: Unable to parse saved cookie:" << value;
+ qCWarning(lcCookieJar) << "CookieJar: Unable to parse saved cookie:" << value;
}
for (int j = 0; j < newCookies.count(); ++j)
list.append(newCookies.at(j));
QList<QNetworkCookie> CookieJar::cookiesForUrl(const QUrl &url) const
{
QList<QNetworkCookie> cookies = QNetworkCookieJar::cookiesForUrl(url);
-// qDebug() << url << "requests:" << cookies;
+ qCDebug(lcCookieJar) << url << "requests:" << cookies;
return cookies;
}
{
QFile file;
file.setFileName(fileName);
- qDebug() << fileName;
+ qCDebug(lcCookieJar) << fileName;
file.open(QIODevice::WriteOnly);
QDataStream stream(&file);
stream << removeExpired(allCookies());
* for more details.
*/
+#include <QLoggingCategory>
#include <QString>
-#include <QDebug>
#include "asserts.h"
#include "creds/abstractcredentials.h"
namespace OCC
{
+Q_LOGGING_CATEGORY(lcCredentials, "sync.credentials", QtInfoMsg)
+
AbstractCredentials::AbstractCredentials()
: _account(0)
{
{
QString u(url);
if( u.isEmpty() ) {
- qDebug() << "Empty url in keyChain, error!";
+ qCDebug(lcCredentials) << "Empty url in keyChain, error!";
return QString::null;
}
if( user.isEmpty() ) {
- qDebug() << "Error: User is empty!";
+ qCDebug(lcCredentials) << "Error: User is empty!";
return QString::null;
}
#include <QSslCertificate>
#include <QSslConfiguration>
-#include <QDebug>
-
#include "creds/credentialscommon.h"
#include "utility.h"
* for more details.
*/
+#include <QLoggingCategory>
#include <QMutex>
-#include <QDebug>
#include <QNetworkReply>
#include <QSettings>
#include <QSslKey>
namespace OCC
{
+Q_LOGGING_CATEGORY(lcHttpCredentials, "sync.credentials.http", QtInfoMsg)
+
namespace
{
const char userC[] = "user";
QByteArray credHash = QByteArray(_cred->user().toUtf8()+":"+_cred->password().toUtf8()).toBase64();
QNetworkRequest req(request);
req.setRawHeader(QByteArray("Authorization"), QByteArray("Basic ") + credHash);
- //qDebug() << "Request for " << req.url() << "with authorization"
- // << QByteArray::fromBase64(credHash)
- // << _cred->_clientSslKey << _cred->_clientSslCertificate
- // << _cred->_clientSslKey.isNull() << _cred->_clientSslCertificate.isNull();
if (!_cred->_clientSslKey.isNull() && !_cred->_clientSslCertificate.isNull()) {
// SSL configuration
addSettingsToJob(_account, job);
job->setInsecureFallback(false);
job->setKey(kck);
- qDebug() << "-------- ----->" << _clientSslCertificate << _clientSslKey;
+ qCDebug(lcHttpCredentials) << "-------- ----->" << _clientSslCertificate << _clientSslKey;
connect(job, SIGNAL(finished(QKeychain::Job*)), SLOT(slotReadClientCertPEMJobDone(QKeychain::Job*)));
job->start();
}
#endif
if (_clientSslKey.isNull()) {
- qDebug() << "Warning: Could not load SSL key into Qt!";
+ qCDebug(lcHttpCredentials) << "Warning: Could not load SSL key into Qt!";
}
}
_password = job->textData();
if( _user.isEmpty()) {
- qDebug() << "Strange: User is empty!";
+ qCDebug(lcHttpCredentials) << "Strange: User is empty!";
}
QKeychain::Error error = job->error();
const QString kck = keychainKey(_account->url().toString(), _user);
if( kck.isEmpty() ) {
- qDebug() << "InvalidateToken: User is empty, bailing out!";
+ qCDebug(lcHttpCredentials) << "InvalidateToken: User is empty, bailing out!";
return;
}
case NoError:
break;
default:
- qDebug() << "Error while writing password" << job->errorString();
+ qCDebug(lcHttpCredentials) << "Error while writing password" << job->errorString();
}
WritePasswordJob *wjob = qobject_cast<WritePasswordJob*>(job);
wjob->deleteLater();
Q_UNUSED(authenticator)
// Because of issue #4326, we need to set the login and password manually at every requests
// Thus, if we reach this signal, those credentials were invalid and we terminate.
- qDebug() << "Stop request: Authentication failed for " << reply->url().toString();
+ qCDebug(lcHttpCredentials) << "Stop request: Authentication failed for " << reply->url().toString();
reply->setProperty(authenticationFailedC, true);
reply->close();
}
* for more details.
*/
+#include <QLoggingCategory>
#include <QMutex>
-#include <QDebug>
#include <QNetworkReply>
#include <QSettings>
#include <QNetworkCookieJar>
namespace OCC
{
+Q_LOGGING_CATEGORY(lcTokenCredentials, "sync.credentials.token", QtInfoMsg)
+
namespace
{
protected:
QNetworkReply *createRequest(Operation op, const QNetworkRequest &request, QIODevice *outgoingData) {
if (_cred->user().isEmpty() || _cred->password().isEmpty()) {
- qWarning() << Q_FUNC_INFO << "Empty user/password provided!";
+ qCWarning(lcTokenCredentials) << "Empty user/password provided!";
}
QNetworkRequest req(request);
void TokenCredentials::invalidateToken()
{
- qDebug() << Q_FUNC_INFO;
+ qCDebug(lcTokenCredentials) << "Invalidating token";
_ready = false;
_account->clearCookieJar();
_token = QString();
// we cannot use QAuthenticator, because it sends username and passwords with latin1
// instead of utf8 encoding. Instead, we send it manually. Thus, if we reach this signal,
// those credentials were invalid and we terminate.
- qDebug() << "Stop request: Authentication failed for " << reply->url().toString();
+ qCDebug(lcTokenCredentials) << "Stop request: Authentication failed for " << reply->url().toString();
reply->setProperty(authenticationFailedC, true);
reply->close();
}
#include <csync_private.h>
#include <csync_rename.h>
-#include <qdebug.h>
+#include <QLoggingCategory>
#include <QUrl>
#include <QFileInfo>
#include <cstring>
namespace OCC {
+Q_LOGGING_CATEGORY(lcDiscovery, "sync.discovery", QtInfoMsg)
/* Given a sorted list of paths ending with '/', return whether or not the given path is within one of the paths of the list*/
static bool findPathInList(const QStringList &list, const QString &path)
csync_vio_file_stat_t* file_stat = csync_vio_file_stat_new();
for (auto it = map.constBegin(); it != map.constEnd(); ++it) {
- //qDebug() << it.key() << it.value();
+ qCDebug(lcDiscovery) << "Property key:" << it.key() << "with value:" << it.value();
QString property = it.key();
QString value = it.value();
if (property == "resourcetype") {
strcpy(file_stat->remotePerm, v.constData());
file_stat->fields |= CSYNC_VIO_FILE_STAT_FIELDS_PERM;
} else {
- qWarning() << "permissions too large" << v;
+ qCWarning(lcDiscovery) << "permissions too large" << v;
}
}
}
void DiscoverySingleDirectoryJob::directoryListingIteratedSlot(QString file, const QMap<QString,QString> &map)
{
- //qDebug() << Q_FUNC_INFO << _subPath << file << map.count() << map.keys() << _account->davPath() << _lsColJob->reply()->request().url().path();
if (!_ignoredFirst) {
// The first entry is for the folder itself, we should process it differently.
_ignoredFirst = true;
FileStatPointer file_stat(propertyMapToFileStat(map));
file_stat->name = strdup(file.toUtf8());
if (!file_stat->etag || strlen(file_stat->etag) == 0) {
- qDebug() << "WARNING: etag of" << file_stat->name << "is" << file_stat->etag << " This must not happen.";
+ qCDebug(lcDiscovery) << "WARNING: etag of" << file_stat->name << "is" << file_stat->etag << " This must not happen.";
}
if (_isExternalStorage) {
/* All the entries in a external storage have 'M' in their permission. However, for all
if( slashPos > -1 ) {
fileRef = file.midRef(slashPos+1);
}
- //qDebug() << "!!!!" << file_stat << file_stat->name << file_stat->file_id << map.count();
_results.append(file_stat);
}
QString httpReason = r->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString();
QString msg = r->errorString();
int errnoCode = EIO; // Something went wrong
- qDebug() << Q_FUNC_INFO << r->errorString() << httpCode << r->error();
+ qCDebug(lcDiscovery) << r->errorString() << httpCode << r->error();
if (httpCode != 0 && httpCode != 207) {
errnoCode = get_errno_from_http_errcode(httpCode, httpReason);
} else if (r->error() != QNetworkReply::NoError) {
if (!_currentDiscoveryDirectoryResult) {
return; // possibly aborted
}
- qDebug() << Q_FUNC_INFO << "Have" << result.count() << "results for " << _currentDiscoveryDirectoryResult->path;
+ qCDebug(lcDiscovery) << "Have" << result.count() << "results for " << _currentDiscoveryDirectoryResult->path;
_currentDiscoveryDirectoryResult->list = result;
if (!_currentDiscoveryDirectoryResult) {
return; // possibly aborted
}
- qDebug() << Q_FUNC_INFO << csyncErrnoCode << msg;
+ qCDebug(lcDiscovery) << csyncErrnoCode << msg;
_currentDiscoveryDirectoryResult->code = csyncErrnoCode;
_currentDiscoveryDirectoryResult->msg = msg;
{
// Should be thread safe since the sync thread is blocked
if (!_discoveryJob->_csync_ctx->remote.root_perms) {
- qDebug() << "Permissions for root dir:" << p;
+ qCDebug(lcDiscovery) << "Permissions for root dir:" << p;
_discoveryJob->_csync_ctx->remote.root_perms = strdup(p.toUtf8());
}
}
return; // possibly aborted
}
- qWarning() << "Error getting the size of the directory";
+ qCWarning(lcDiscovery) << "Error getting the size of the directory";
// just let let the discovery job continue then
_currentGetSizeResult = 0;
QMutexLocker locker(&_discoveryJob->_vioMutex);
}
*_currentGetSizeResult = map.value(QLatin1String("size")).toLongLong();
- qDebug() << "Size of folder:" << *_currentGetSizeResult;
+ qCDebug(lcDiscovery) << "Size of folder:" << *_currentGetSizeResult;
_currentGetSizeResult = 0;
QMutexLocker locker(&_discoveryJob->_vioMutex);
_discoveryJob->_vioWaitCondition.wakeAll();
{
DiscoveryJob *discoveryJob = static_cast<DiscoveryJob*>(userdata);
if (discoveryJob) {
- qDebug() << discoveryJob << url << "Calling into main thread...";
+ qCDebug(lcDiscovery) << discoveryJob << url << "Calling into main thread...";
QScopedPointer<DiscoveryDirectoryResult> directoryResult(new DiscoveryDirectoryResult());
directoryResult->code = EIO;
discoveryJob->_vioWaitCondition.wait(&discoveryJob->_vioMutex, ULONG_MAX); // FIXME timeout?
discoveryJob->_vioMutex.unlock();
- qDebug() << discoveryJob << url << "...Returned from main thread";
+ qCDebug(lcDiscovery) << discoveryJob << url << "...Returned from main thread";
// Upon awakening from the _vioWaitCondition, iterator should be a valid iterator.
if (directoryResult->code != 0) {
- qDebug() << directoryResult->code << "when opening" << url << "msg=" << directoryResult->msg;
+ qCDebug(lcDiscovery) << directoryResult->code << "when opening" << url << "msg=" << directoryResult->msg;
errno = directoryResult->code;
// save the error string to the context
discoveryJob->_csync_ctx->error_string = qstrdup( directoryResult->msg.toUtf8().constData() );
if (discoveryJob) {
DiscoveryDirectoryResult *directoryResult = static_cast<DiscoveryDirectoryResult*> (dhandle);
QString path = directoryResult->path;
- qDebug() << Q_FUNC_INFO << discoveryJob << path;
+ qCDebug(lcDiscovery) << discoveryJob << path;
delete directoryResult; // just deletes the struct and the iterator, the data itself is owned by the SyncEngine/DiscoveryMainThread
}
}
#include "utility.h"
#include <QFile>
#include <QFileInfo>
+#include <QLoggingCategory>
#include <QCoreApplication>
-#include <QDebug>
#include <QCryptographicHash>
#ifdef ZLIB_FOUND
namespace OCC {
+Q_LOGGING_CATEGORY(lcFileSystem, "sync.filesystem", QtInfoMsg)
+
QString FileSystem::longWinPath( const QString& inpath )
{
QString path(inpath);
QFile f1(fn1);
QFile f2(fn2);
if (!f1.open(QIODevice::ReadOnly) || !f2.open(QIODevice::ReadOnly)) {
- qDebug() << "fileEquals: Failed to open " << fn1 << "or" << fn2;
+ qCDebug(lcFileSystem) << "fileEquals: Failed to open " << fn1 << "or" << fn2;
return false;
}
&& (stat->fields & CSYNC_VIO_FILE_STAT_FIELDS_MTIME)) {
result = stat->mtime;
} else {
- qDebug() << "Could not get modification time for" << filename
+ qCDebug(lcFileSystem) << "Could not get modification time for" << filename
<< "with csync, using QFileInfo";
result = Utility::qDateTimeToTime_t(QFileInfo(filename).lastModified());
}
times[0].tv_usec = times[1].tv_usec = 0;
int rc = c_utimes(filename.toUtf8().data(), times);
if (rc != 0) {
- qDebug() << "Error setting mtime for" << filename
+ qCDebug(lcFileSystem) << "Error setting mtime for" << filename
<< "failed: rc" << rc << ", errno:" << errno;
return false;
}
}
if (!success) {
- qDebug() << "FAIL: renaming file" << originFileName
+ qCDebug(lcFileSystem) << "FAIL: renaming file" << originFileName
<< "to" << destinationFileName
<< "failed: " << error;
if (errorString) {
const qint64 actualSize = getSize(fileName);
const time_t actualMtime = getModTime(fileName);
if (actualSize != previousSize || actualMtime != previousMtime) {
- qDebug() << "File" << fileName << "has changed:"
+ qCDebug(lcFileSystem) << "File" << fileName << "has changed:"
<< "size: " << previousSize << "<->" << actualSize
<< ", mtime: " << previousMtime << "<->" << actualMtime;
return false;
QFile orig(originFileName);
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
success = orig.fileEngine()->rename(destinationFileName);
- // qDebug() << "Renaming " << tmpFile.fileName() << " to " << fn;
#else
// We want a rename that also overwites. QFile::rename does not overwite.
// Qt 5.1 has QSaveFile::renameOverwrite we could use.
bool destExists = fileExists(destinationFileName);
if( destExists && !QFile::remove(destinationFileName) ) {
*errorString = orig.errorString();
- qDebug() << Q_FUNC_INFO << "Target file could not be removed.";
+ qCDebug(lcFileSystem) << "Target file could not be removed.";
success = false;
}
if( success ) {
#endif
if (!success) {
*errorString = orig.errorString();
- qDebug() << "FAIL: renaming temp file to final failed: " << *errorString ;
+ qCDebug(lcFileSystem) << "FAIL: renaming temp file to final failed: " << *errorString ;
return false;
}
(LPWSTR)&string, 0, NULL);
*errorString = QString::fromWCharArray(string);
- qDebug() << "FAIL: renaming temp file to final failed: " << *errorString;
+ qCDebug(lcFileSystem) << "FAIL: renaming temp file to final failed: " << *errorString;
LocalFree((HLOCAL)string);
return false;
}
&& (stat->fields & CSYNC_VIO_FILE_STAT_FIELDS_SIZE)) {
result = stat->size;
} else {
- qDebug() << "Could not get size for" << filename << "with csync";
+ qCDebug(lcFileSystem) << "Could not get size for" << filename << "with csync";
}
csync_vio_file_stat_destroy(stat);
return result;
* for more details.
*/
+#include <QLoggingCategory>
#include <QNetworkRequest>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QStack>
#include <QTimer>
#include <QMutex>
-#include <QDebug>
#include <QCoreApplication>
#include <QPixmap>
#include <QJsonDocument>
namespace OCC {
+Q_LOGGING_CATEGORY(lcEtag, "sync.networkjob.etag", QtInfoMsg)
+Q_LOGGING_CATEGORY(lcLsCol, "sync.networkjob.lscol", QtInfoMsg)
+Q_LOGGING_CATEGORY(lcCheckServer, "sync.networkjob.checkserver", QtInfoMsg)
+Q_LOGGING_CATEGORY(lcPropfind, "sync.networkjob.propfind", QtInfoMsg)
+Q_LOGGING_CATEGORY(lcAvatar, "sync.networkjob.avatar", QtInfoMsg)
+Q_LOGGING_CATEGORY(lcProppatch, "sync.networkjob.proppatch", QtInfoMsg)
+Q_LOGGING_CATEGORY(lcJsonApi, "sync.networkjob.jsonapi", QtInfoMsg)
+
RequestEtagJob::RequestEtagJob(AccountPtr account, const QString &path, QObject *parent)
: AbstractNetworkJob(account, path, parent)
{
sendRequest("PROPFIND", makeDavUrl(path()), req, buf);
if( reply()->error() != QNetworkReply::NoError ) {
- qDebug() << "getting etag: request network error: " << reply()->errorString();
+ qCDebug(lcEtag) << "request network error: " << reply()->errorString();
}
AbstractNetworkJob::start();
}
// but the result will have URL encoding..
QString hrefString = QString::fromUtf8(QByteArray::fromPercentEncoding(reader.readElementText().toUtf8()));
if (!hrefString.startsWith(expectedPath)) {
- qDebug() << "Invalid href" << hrefString << "expected starting with" << expectedPath;
+ qCDebug(lcLsCol) << "Invalid href" << hrefString << "expected starting with" << expectedPath;
return false;
}
currentHref = hrefString;
if (reader.hasError()) {
// XML Parser error? Whatever had been emitted before will come as directoryListingIterated
- qDebug() << "ERROR" << reader.errorString() << xml;
+ qCDebug(lcLsCol) << "ERROR" << reader.errorString() << xml;
return false;
} else if (!insideMultiStatus) {
- qDebug() << "ERROR no WebDAV response?" << xml;
+ qCDebug(lcLsCol) << "ERROR no WebDAV response?" << xml;
return false;
} else {
emit directoryListingSubfolders(folders);
QList<QByteArray> properties = _properties;
if (properties.isEmpty()) {
- qWarning() << "Propfind with no properties!";
+ qCWarning(lcLsCol) << "Propfind with no properties!";
}
QByteArray propStr;
foreach (const QByteArray &prop, properties) {
void CheckServerJob::onTimedOut()
{
- qDebug() << "TIMEOUT" << Q_FUNC_INFO;
+ qCDebug(lcCheckServer) << "TIMEOUT";
if (reply() && reply()->isRunning()) {
emit timeout(reply()->url());
} else if (!reply()) {
- qDebug() << Q_FUNC_INFO << "Timeout even there was no reply?";
+ qCDebug(lcCheckServer) << "Timeout even there was no reply?";
}
deleteLater();
}
if (reply()->request().url().scheme() == QLatin1String("https")
&& reply()->sslConfiguration().sessionTicket().isEmpty()
&& reply()->error() == QNetworkReply::NoError) {
- qDebug() << "No SSL session identifier / session ticket is used, this might impact sync performance negatively.";
+ qCDebug(lcCheckServer) << "No SSL session identifier / session ticket is used, this might impact sync performance negatively.";
}
#endif
_subdirFallback = true;
setPath(QLatin1String(owncloudDirC)+QLatin1String(statusphpC));
start();
- qDebug() << "Retrying with" << reply()->url();
+ qCDebug(lcCheckServer) << "Retrying with" << reply()->url();
return false;
}
QByteArray body = reply()->peek(4*1024);
int httpStatus = reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
if( body.isEmpty() || httpStatus != 200) {
- qDebug() << "error: status.php replied " << httpStatus << body;
+ qCDebug(lcCheckServer) << "error: status.php replied " << httpStatus << body;
emit instanceNotFound(reply());
} else {
QJsonParseError error;
auto status = QJsonDocument::fromJson(body, &error);
// empty or invalid response
if (error.error != QJsonParseError::NoError || status.isNull()) {
- qDebug() << "status.php from server is not valid JSON!" << body << reply()->request().url() << error.errorString();
+ qCDebug(lcCheckServer) << "status.php from server is not valid JSON!" << body << reply()->request().url() << error.errorString();
}
- qDebug() << "status.php returns: " << status << " " << reply()->error() << " Reply: " << reply();
+ qCDebug(lcCheckServer) << "status.php returns: " << status << " " << reply()->error() << " Reply: " << reply();
if( status.object().contains("installed") ) {
emit instanceFound(reply()->url(), status.object());
} else {
- qDebug() << "No proper answer on " << reply()->url();
+ qCDebug(lcCheckServer) << "No proper answer on " << reply()->url();
emit instanceNotFound(reply());
}
}
QList<QByteArray> properties = _properties;
if (properties.isEmpty()) {
- qWarning() << "Propfind with no properties!";
+ qCWarning(lcLsCol) << "Propfind with no properties!";
}
QNetworkRequest req;
// Always have a higher priority than the propagator because we use this from the UI
}
}
if (reader.hasError()) {
- qDebug() << "PROPFIND request XML parser error: " << reader.errorString();
+ qCDebug(lcPropfind) << "XML parser error: " << reader.errorString();
emit finishedWithError(reply());
} else {
emit result(items);
}
} else {
- qDebug() << "PROPFIND request *not* successful, http result code is" << http_result_code
+ qCDebug(lcPropfind) << "*not* successful, http result code is" << http_result_code
<< (http_result_code == 302 ? reply()->header(QNetworkRequest::LocationHeader).toString() : QLatin1String(""));
emit finishedWithError(reply());
}
if( pngData.size() ) {
if( avImage.loadFromData(pngData) ) {
- qDebug() << "Retrieved Avatar pixmap!";
+ qCDebug(lcAvatar) << "Retrieved Avatar pixmap!";
}
}
}
void ProppatchJob::start()
{
if (_properties.isEmpty()) {
- qWarning() << "Proppatch with no properties!";
+ qCWarning(lcProppatch) << "Proppatch with no properties!";
}
QNetworkRequest req;
if (http_result_code == 207) {
emit success();
} else {
- qDebug() << "PROPPATCH request *not* successful, http result code is" << http_result_code
+ qCDebug(lcProppatch) << "*not* successful, http result code is" << http_result_code
<< (http_result_code == 302 ? reply()->header(QNetworkRequest::LocationHeader).toString() : QLatin1String(""));
emit finishedWithError();
}
int statusCode = 0;
if (reply()->error() != QNetworkReply::NoError) {
- qWarning() << "Network error: " << path() << errorString() << reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute);
+ qCWarning(lcJsonApi) << "Network error: " << path() << errorString() << reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute);
emit jsonReceived(QJsonDocument(), statusCode);
return true;
}
auto json = QJsonDocument::fromJson(jsonStr.toUtf8(), &error);
// empty or invalid response
if (error.error != QJsonParseError::NoError || json.isNull()) {
- qWarning() << "invalid JSON!" << jsonStr << error.errorString();
+ qCWarning(lcJsonApi) << "invalid JSON!" << jsonStr << error.errorString();
emit jsonReceived(json, statusCode);
return true;
}
#include <QStack>
#include <QFileInfo>
#include <QDir>
+#include <QLoggingCategory>
#include <QTimer>
#include <QObject>
#include <QTimerEvent>
-#include <QDebug>
#include <qmath.h>
namespace OCC {
+Q_LOGGING_CATEGORY(lcPropagator, "sync.propagator", QtInfoMsg)
+Q_LOGGING_CATEGORY(lcDirectory, "sync.propagator.directory", QtInfoMsg)
+Q_LOGGING_CATEGORY(lcCleanupPolls, "sync.propagator.cleanuppolls", QtInfoMsg)
+
qint64 criticalFreeSpaceLimit()
{
qint64 value = 50 * 1000 * 1000LL;
entry._ignoreDuration = old._ignoreDuration * 5;
if( item._httpErrorCode == 403 ) {
- qDebug() << "Probably firewall error: " << item._httpErrorCode << ", blacklisting up to 1h only";
+ qCDebug(lcPropagator) << "Probably firewall error: " << item._httpErrorCode << ", blacklisting up to 1h only";
entry._ignoreDuration = qMin(entry._ignoreDuration, time_t(60*60));
} else if( item._httpErrorCode == 413 || item._httpErrorCode == 415 ) {
- qDebug() << "Fatal Error condition" << item._httpErrorCode << ", maximum blacklist ignore time!";
+ qCDebug(lcPropagator) << "Fatal Error condition" << item._httpErrorCode << ", maximum blacklist ignore time!";
entry._ignoreDuration = maxBlacklistTime;
}
item._status = SyncFileItem::FileIgnored;
item._errorString.prepend(PropagateItemJob::tr("Continue blacklisting:") + " ");
- qDebug() << "blacklisting " << item._file
+ qCDebug(lcPropagator) << "blacklisting " << item._file
<< " for " << newEntry._ignoreDuration
<< ", retry count " << newEntry._retryCount;
// Some soft errors might become louder on repeat occurrence
if (item._status == SyncFileItem::SoftError
&& newEntry._retryCount > 1) {
- qDebug() << "escalating soft error on " << item._file
+ qCDebug(lcPropagator) << "escalating soft error on " << item._file
<< " to normal error, " << item._httpErrorCode;
item._status = SyncFileItem::NormalError;
return;
} else if (item->_instruction == CSYNC_INSTRUCTION_RENAME) {
// all is good, the rename will be executed before the directory deletion
} else {
- qWarning() << "WARNING: Job within a removed directory? This should not happen!"
+ qCWarning(lcPropagator) << "WARNING: Job within a removed directory? This should not happen!"
<< item->_file << item->_instruction;
}
}
connect(_rootJob.data(), SIGNAL(finished(SyncFileItem::Status)), this, SLOT(emitFinished(SyncFileItem::Status)));
- qDebug() << "Using QNAM/HTTP parallel code path";
+ qCDebug(lcPropagator) << "Using QNAM/HTTP parallel code path";
scheduleNextJob();
}
QFileInfo fileInfo(file);
if (!fileInfo.exists()) {
re = false;
- qDebug() << Q_FUNC_INFO << "No valid fileinfo";
+ qCDebug(lcPropagator) << "No valid fileinfo";
} else {
// Need to normalize to composited form because of
// https://bugreports.qt-project.org/browse/QTBUG-39622
const QString cName = fileInfo.canonicalFilePath().normalized(QString::NormalizationForm_C);
- // qDebug() << Q_FUNC_INFO << "comparing " << cName << " with " << file;
bool equal = (file == cName);
re = (!equal && ! cName.endsWith(relFile, Qt::CaseSensitive) );
- // qDebug() << Q_FUNC_INFO << "Returning for localFileNameClash: " << re;
}
#elif defined(Q_OS_WIN)
const QString file( _localDir + relFile );
- qDebug() << "CaseClashCheck for " << file;
+ qCDebug(lcPropagator) << "CaseClashCheck for " << file;
WIN32_FIND_DATA FindFileData;
HANDLE hFind;
hFind = FindFirstFileW( (wchar_t*)file.utf16(), &FindFileData);
if (hFind == INVALID_HANDLE_VALUE) {
- //qDebug() << "FindFirstFile failed " << GetLastError();
// returns false.
} else {
QString realFileName = QString::fromWCharArray( FindFileData.cFileName );
FindClose(hFind);
if( ! file.endsWith(realFileName, Qt::CaseSensitive) ) {
- qDebug() << Q_FUNC_INFO << "Detected case clash between" << file << "and" << realFileName;
+ qCDebug(lcPropagator) << "Detected case clash between" << file << "and" << realFileName;
re = true;
}
}
if (firstFile != secondFile
&& QString::compare(firstFile, secondFile, Qt::CaseInsensitive) == 0) {
result = true;
- qDebug() << "Found two filepaths that only differ in case: " << firstFile << secondFile;
+ qCDebug(lcPropagator) << "Found two filepaths that only differ in case: " << firstFile << secondFile;
}
}
FindClose(hFind);
}
}
if (_activeJobList.count() < maximumActiveTransferJob() + likelyFinishedQuicklyCount) {
- qDebug() << "Can pump in another request! activeJobs =" << _activeJobList.count();
+ qCDebug(lcPropagator) << "Can pump in another request! activeJobs =" << _activeJobList.count();
if (_rootJob->scheduleSelfOrChild()) {
scheduleNextJob();
}
_tasksToDo.remove(0);
PropagatorJob *job = propagator()->createJob(nextTask);
if (!job) {
- qWarning() << "Useless task found for file" << nextTask->destination() << "instruction" << nextTask->_instruction;
+ qCWarning(lcDirectory) << "Useless task found for file" << nextTask->destination() << "instruction" << nextTask->_instruction;
continue;
}
if (!ok) {
status = _item->_status = SyncFileItem::FatalError;
_item->_errorString = tr("Error writing metadata to the database");
- qWarning() << "Error writing to the database for file" << _item->_file;
+ qCWarning(lcDirectory) << "Error writing to the database for file" << _item->_file;
}
}
}
deleteLater();
return;
} else if (job->_item->_status != SyncFileItem::Success) {
- qDebug() << "There was an error with file " << job->_item->_file << job->_item->_errorString;
+ qCDebug(lcCleanupPolls) << "There was an error with file " << job->_item->_file << job->_item->_errorString;
} else {
if (!_journal->setFileRecord(SyncJournalFileRecord(*job->_item, _localPath + job->_item->_file))) {
- qWarning() << "database error";
+ qCWarning(lcCleanupPolls) << "database error";
job->_item->_status = SyncFileItem::FatalError;
job->_item->_errorString = tr("Error writing metadata to the database");
emit aborted(job->_item->_errorString);
namespace OCC {
+Q_DECLARE_LOGGING_CATEGORY(lcPropagator)
+
/** Free disk space threshold below which syncs will abort and not even start.
*/
qint64 criticalFreeSpaceLimit();
#pragma once
-#include <QNetworkReply>
-#include <QDebug>
+#include "owncloudpropagator.h"
#include "syncfileitem.h"
+#include <QLoggingCategory>
+#include <QNetworkReply>
namespace OCC {
ret = etag;
}
if (ocEtag.length() > 0 && ocEtag != etag) {
- qDebug() << "Quite peculiar, we have an etag != OC-Etag [no problem!]" << etag << ocEtag;
+ qCDebug(lcPropagator) << "Quite peculiar, we have an etag != OC-Etag [no problem!]" << etag << ocEtag;
}
return ret;
}
#include <QApplication>
#endif
#include <QCoreApplication>
-#include <QDebug>
#include "version.h"
#include "config.h"
ownCloudTheme::ownCloudTheme() :
Theme()
{
- // qDebug() << " ** running ownCloud theme!";
}
QString ownCloudTheme::configFileName() const
#include <QDateTime>
+#include <QLoggingCategory>
#include <QString>
-#include <QDebug>
#include <QFile>
#include <QFileInfo>
#include <QDir>
namespace OCC {
+Q_LOGGING_CATEGORY(lcSql, "sync.database.sql", QtInfoMsg)
+
SqlDatabase::SqlDatabase()
:_db(0),
_errId(0)
SQLITE_DO( sqlite3_open_v2(filename.toUtf8().constData(), &_db, sqliteFlags, 0) );
if( _errId != SQLITE_OK ) {
- qDebug() << "Error:" << _error << "for" << filename;
+ qCDebug(lcSql) << "Error:" << _error << "for" << filename;
close();
return false;
}
if( !_db ) {
- qDebug() << "Error: no database for" << filename;
+ qCDebug(lcSql) << "Error: no database for" << filename;
return false;
}
SqlQuery quick_check(*this);
quick_check.prepare("PRAGMA quick_check;", /*allow_failure=*/true);
if( !quick_check.exec() ) {
- qDebug() << "Error running quick_check on database";
+ qCDebug(lcSql) << "Error running quick_check on database";
return false;
}
quick_check.next();
QString result = quick_check.stringValue(0);
if( result != "ok" ) {
- qDebug() << "quick_check returned failure:" << result;
+ qCDebug(lcSql) << "quick_check returned failure:" << result;
return false;
}
// When disk space is low, checking the db may fail even though it's fine.
qint64 freeSpace = Utility::freeDiskSpace(QFileInfo(filename).dir().absolutePath());
if (freeSpace != -1 && freeSpace < 1000000) {
- qDebug() << "Consistency check failed, disk space is low, aborting" << freeSpace;
+ qCDebug(lcSql) << "Consistency check failed, disk space is low, aborting" << freeSpace;
close();
return false;
}
- qDebug() << "Consistency check failed, removing broken db" << filename;
+ qCDebug(lcSql) << "Consistency check failed, removing broken db" << filename;
close();
QFile::remove(filename);
}
if( !checkDb() ) {
- qDebug() << "Consistency check failed in readonly mode, giving up" << filename;
+ qCDebug(lcSql) << "Consistency check failed in readonly mode, giving up" << filename;
close();
return false;
}
if( _errId != SQLITE_OK ) {
_error = QString::fromUtf8(sqlite3_errmsg(_db));
- qWarning() << "Sqlite prepare statement error:" << _error << "in" <<_sql;
+ qCWarning(lcSql) << "Sqlite prepare statement error:" << _error << "in" <<_sql;
ENFORCE(allow_failure, "SQLITE Prepare error");
}
}
if (_errId != SQLITE_DONE && _errId != SQLITE_ROW) {
_error = QString::fromUtf8(sqlite3_errmsg(_db));
- qDebug() << "Sqlite exec statement error:" << _errId << _error << "in" <<_sql;
+ qCDebug(lcSql) << "Sqlite exec statement error:" << _errId << _error << "in" <<_sql;
}
return (_errId == SQLITE_DONE); // either SQLITE_ROW or SQLITE_DONE
}
break; }
}
if (res != SQLITE_OK) {
- qDebug() << Q_FUNC_INFO << "ERROR" << value << res;
+ qCDebug(lcSql) << "ERROR" << value << res;
}
ASSERT( res == SQLITE_OK );
}
#include <QObject>
#include <QMetaType>
-#include <QDebug>
#include <QCoreApplication>
namespace OCC {
#include <QQueue>
#include <QElapsedTimer>
#include <QTimer>
-#include <QDebug>
#include "syncfileitem.h"
#include "checksums.h"
#include "asserts.h"
+#include <QLoggingCategory>
#include <QNetworkAccessManager>
#include <QFileInfo>
#include <QDir>
-#include <QDebug>
#include <cmath>
#ifdef Q_OS_UNIX
namespace OCC {
+Q_LOGGING_CATEGORY(lcGetFile, "sync.networkjob.get", QtInfoMsg)
+Q_LOGGING_CATEGORY(lcPropagateDownload, "sync.propagator.download", QtInfoMsg)
+
// Always coming in with forward slashes.
// In csync_excluded_no_ctx we ignore all files with longer than 254 chars
// This function also adds a dot at the beginning of the filename to hide the file on OS X and Linux
if (_resumeStart > 0) {
_headers["Range"] = "bytes=" + QByteArray::number(_resumeStart) +'-';
_headers["Accept-Ranges"] = "bytes";
- qDebug() << "Retry with range " << _headers["Range"];
+ qCDebug(lcGetFile) << "Retry with range " << _headers["Range"];
}
QNetworkRequest req;
}
reply()->setReadBufferSize(16 * 1024); // keep low so we can easier limit the bandwidth
- qDebug() << Q_FUNC_INFO << _bandwidthManager << _bandwidthChoked << _bandwidthLimited;
+ qCDebug(lcGetFile) << _bandwidthManager << _bandwidthChoked << _bandwidthLimited;
if (_bandwidthManager) {
_bandwidthManager->registerDownloadJob(this);
}
if( reply()->error() != QNetworkReply::NoError ) {
- qWarning() << Q_FUNC_INFO << " Network error: " << errorString();
+ qCWarning(lcGetFile) << " Network error: " << errorString();
}
connect(reply(), SIGNAL(metaDataChanged()), this, SLOT(slotMetaDataChanged()));
_etag = getEtagFromReply(reply());
if (!_directDownloadUrl.isEmpty() && !_etag.isEmpty()) {
- qDebug() << Q_FUNC_INFO << "Direct download used, ignoring server ETag" << _etag;
+ qCDebug(lcGetFile) << "Direct download used, ignoring server ETag" << _etag;
_etag = QByteArray(); // reset received ETag
} else if (!_directDownloadUrl.isEmpty()) {
// All fine, ETag empty and directDownloadUrl used
} else if (_etag.isEmpty()) {
- qDebug() << Q_FUNC_INFO << "No E-Tag reply by server, considering it invalid";
+ qCDebug(lcGetFile) << "No E-Tag reply by server, considering it invalid";
_errorString = tr("No E-Tag received from server, check Proxy/Gateway");
_errorStatus = SyncFileItem::NormalError;
reply()->abort();
return;
} else if (!_expectedEtagForResume.isEmpty() && _expectedEtagForResume != _etag) {
- qDebug() << Q_FUNC_INFO << "We received a different E-Tag for resuming!"
+ qCDebug(lcGetFile) << "We received a different E-Tag for resuming!"
<< _expectedEtagForResume << "vs" << _etag;
_errorString = tr("We received a different E-Tag for resuming. Retrying next time.");
_errorStatus = SyncFileItem::NormalError;
}
}
if (start != _resumeStart) {
- qDebug() << Q_FUNC_INFO << "Wrong content-range: "<< ranges << " while expecting start was" << _resumeStart;
+ qCDebug(lcGetFile) << "Wrong content-range: "<< ranges << " while expecting start was" << _resumeStart;
if (ranges.isEmpty()) {
// device doesn't support range, just try again from scratch
_device->close();
void GETFileJob::giveBandwidthQuota(qint64 q)
{
_bandwidthQuota = q;
- qDebug() << Q_FUNC_INFO << "Got" << q << "bytes";
+ qCDebug(lcGetFile) << "Got" << q << "bytes";
QMetaObject::invokeMethod(this, "slotReadyRead", Qt::QueuedConnection);
}
int bufferSize = qMin(1024*8ll , reply()->bytesAvailable());
QByteArray buffer(bufferSize, Qt::Uninitialized);
- //qDebug() << Q_FUNC_INFO << reply()->bytesAvailable() << reply()->isOpen() << reply()->isFinished();
-
while(reply()->bytesAvailable() > 0) {
if (_bandwidthChoked) {
- qDebug() << Q_FUNC_INFO << "Download choked";
+ qCDebug(lcGetFile) << "Download choked";
break;
}
qint64 toRead = bufferSize;
if (_bandwidthLimited) {
toRead = qMin(qint64(bufferSize), _bandwidthQuota);
if (toRead == 0) {
- //qDebug() << Q_FUNC_INFO << "Out of quota";
+ qCDebug(lcGetFile) << "Out of quota";
break;
}
_bandwidthQuota -= toRead;
- //qDebug() << Q_FUNC_INFO << "Reading" << toRead << "remaining" << _bandwidthQuota;
}
qint64 r = reply()->read(buffer.data(), toRead);
if (r < 0) {
_errorString = networkReplyErrorString(*reply());
_errorStatus = SyncFileItem::NormalError;
- qDebug() << "Error while reading from device: " << _errorString;
+ qCDebug(lcGetFile) << "Error while reading from device: " << _errorString;
reply()->abort();
return;
}
if (w != r) {
_errorString = _device->errorString();
_errorStatus = SyncFileItem::NormalError;
- qDebug() << "Error while writing to file" << w << r << _errorString;
+ qCDebug(lcGetFile) << "Error while writing to file" << w << r << _errorString;
reply()->abort();
return;
}
}
}
- //qDebug() << Q_FUNC_INFO << "END" << reply()->isFinished() << reply()->bytesAvailable() << _hasEmittedFinishedSignal;
if (reply()->isFinished() && reply()->bytesAvailable() == 0) {
- qDebug() << Q_FUNC_INFO << "Actually finished!";
+ qCDebug(lcGetFile) << "Actually finished!";
if (_bandwidthManager) {
_bandwidthManager->unregisterDownloadJob(this);
}
void GETFileJob::onTimedOut()
{
- qDebug() << "Timeout" << (reply() ? reply()->request().url() : path());
+ qCDebug(lcGetFile) << "Timeout" << (reply() ? reply()->request().url() : path());
if (!reply())
return;
_errorString = tr("Connection Timeout");
if (propagator()->_abortRequested.fetchAndAddRelaxed(0))
return;
- qDebug() << Q_FUNC_INFO << _item->_file << propagator()->_activeJobList.count();
+ qCDebug(lcPropagateDownload) << _item->_file << propagator()->_activeJobList.count();
_stopwatch.start();
if (_deleteExisting) {
_resumeStart = _tmpFile.size();
if (_resumeStart > 0) {
if (_resumeStart == _item->_size) {
- qDebug() << "File is already complete, no need to download";
+ qCDebug(lcPropagateDownload) << "File is already complete, no need to download";
_tmpFile.close();
downloadFinished();
return;
&_tmpFile, headers, expectedEtagForResume, _resumeStart, this);
} else {
// We were provided a direct URL, use that one
- qDebug() << Q_FUNC_INFO << "directDownloadUrl given for " << _item->_file << _item->_directDownloadUrl;
+ qCDebug(lcPropagateDownload) << "directDownloadUrl given for " << _item->_file << _item->_directDownloadUrl;
if (!_item->_directDownloadCookies.isEmpty()) {
headers["Cookie"] = _item->_directDownloadCookies.toUtf8();
GETFileJob *job = qobject_cast<GETFileJob *>(sender());
ASSERT(job);
- qDebug() << Q_FUNC_INFO << job->reply()->request().url() << "FINISHED WITH STATUS"
+ qCDebug(lcPropagateDownload) << job->reply()->request().url() << "FINISHED WITH STATUS"
<< job->reply()->error()
<< (job->reply()->error() == QNetworkReply::NoError ? QLatin1String("") : job->errorString())
<< _item->_httpErrorCode
// without the header.
const bool badRangeHeader = job->resumeStart() > 0 && _item->_httpErrorCode == 416;
if (badRangeHeader) {
- qDebug() << Q_FUNC_INFO << "server replied 416 to our range request, trying again without";
+ qCDebug(lcPropagateDownload) << "server replied 416 to our range request, trying again without";
propagator()->_anotherSyncNeeded = true;
}
// Getting a 404 probably means that the file was deleted on the server.
const bool fileNotFound = _item->_httpErrorCode == 404;
if (fileNotFound) {
- qDebug() << Q_FUNC_INFO << "server replied 404, assuming file was deleted";
+ qCDebug(lcPropagateDownload) << "server replied 404, assuming file was deleted";
}
// Don't keep the temporary file if it is empty or we
if(!_item->_directDownloadUrl.isEmpty() && err != QNetworkReply::OperationCanceledError) {
// If this was with a direct download, retry without direct download
- qWarning() << "Direct download of" << _item->_directDownloadUrl << "failed. Retrying through owncloud.";
+ qCWarning(lcPropagateDownload) << "Direct download of" << _item->_directDownloadUrl << "failed. Retrying through owncloud.";
_item->_directDownloadUrl.clear();
start();
return;
if (!job->reply()->rawHeader(sizeHeader).isEmpty() && _tmpFile.size() > 0 && bodySize == 0) {
// Strange bug with broken webserver or webfirewall https://github.com/owncloud/client/issues/3373#issuecomment-122672322
// This happened when trying to resume a file. The Content-Range header was files, Content-Length was == 0
- qDebug() << bodySize << _item->_size << _tmpFile.size() << job->resumeStart();
+ qCDebug(lcPropagateDownload) << bodySize << _item->_size << _tmpFile.size() << job->resumeStart();
FileSystem::remove(_tmpFile.fileName());
done(SyncFileItem::SoftError, QLatin1String("Broken webserver returning empty content length for non-empty file on resume"));
return;
}
if(bodySize > 0 && bodySize != _tmpFile.size() - job->resumeStart() ) {
- qDebug() << bodySize << _tmpFile.size() << job->resumeStart();
+ qCDebug(lcPropagateDownload) << bodySize << _tmpFile.size() << job->resumeStart();
propagator()->_anotherSyncNeeded = true;
done(SyncFileItem::SoftError, tr("The file could not be downloaded completely."));
return;
void handleRecallFile(const QString& filePath, const QString& folderPath, SyncJournalDb& journal)
{
- qDebug() << "handleRecallFile: " << filePath;
+ qCDebug(lcPropagateDownload) << "handleRecallFile: " << filePath;
FileSystem::setFileHidden(filePath, true);
QFile file(filePath);
if (!file.open(QIODevice::ReadOnly)) {
- qWarning() << "Could not open recall file" << file.errorString();
+ qCWarning(lcPropagateDownload) << "Could not open recall file" << file.errorString();
return;
}
QFileInfo existingFile(filePath);
QString recalledFile = QDir::cleanPath(baseDir.filePath(line));
if (!recalledFile.startsWith(folderPath) || !recalledFile.startsWith(baseDir.path())) {
- qDebug() << "Ignoring recall of " << recalledFile;
+ qCDebug(lcPropagateDownload) << "Ignoring recall of " << recalledFile;
continue;
}
SyncJournalFileRecord record = journal.getFileRecord(localRecalledFile);
if (!record.isValid()) {
- qDebug() << "No db entry for recall of" << localRecalledFile;
+ qCDebug(lcPropagateDownload) << "No db entry for recall of" << localRecalledFile;
continue;
}
- qDebug() << "Recalling" << localRecalledFile << "Checksum:" << record._contentChecksumType << record._contentChecksum;
+ qCDebug(lcPropagateDownload) << "Recalling" << localRecalledFile << "Checksum:" << record._contentChecksumType << record._contentChecksum;
QString targetPath = makeRecallFileName(recalledFile);
- qDebug() << "Copy recall file: " << recalledFile << " -> " << targetPath;
+ qCDebug(lcPropagateDownload) << "Copy recall file: " << recalledFile << " -> " << targetPath;
// Remove the target first, QFile::copy will not overwrite it.
FileSystem::remove(targetPath);
QFile::copy(recalledFile, targetPath);
done(SyncFileItem::SoftError, renameError);
return;
}
- qDebug() << "Created conflict file" << fn << "->" << conflictFileName;
+ qCDebug(lcPropagateDownload) << "Created conflict file" << fn << "->" << conflictFileName;
}
FileSystem::setModTime(_tmpFile.fileName(), _item->_modtime);
emit propagator()->touchedFile(fn);
// The fileChanged() check is done above to generate better error messages.
if (!FileSystem::uncheckedRenameReplace(_tmpFile.fileName(), fn, &error)) {
- qDebug() << Q_FUNC_INFO << QString("Rename failed: %1 => %2").arg(_tmpFile.fileName()).arg(fn);
+ qCDebug(lcPropagateDownload) << QString("Rename failed: %1 => %2").arg(_tmpFile.fileName()).arg(fn);
// If we moved away the original file due to a conflict but can't
// put the downloaded file in its place, we are in a bad spot:
qint64 duration = _stopwatch.elapsed();
if (isLikelyFinishedQuickly() && duration > 5*1000) {
- qDebug() << "WARNING: Unexpectedly slow connection, took" << duration << "msec for" << _item->_size - _resumeStart << "bytes for" << _item->_file;
+ qCDebug(lcPropagateDownload) << "WARNING: Unexpectedly slow connection, took" << duration << "msec for" << _item->_size - _resumeStart << "bytes for" << _item->_file;
}
}
virtual void start() Q_DECL_OVERRIDE;
virtual bool finished() Q_DECL_OVERRIDE {
-// qDebug() << Q_FUNC_INFO << reply()->bytesAvailable() << _hasEmittedFinishedSignal;
if (reply()->bytesAvailable()) {
-// qDebug() << Q_FUNC_INFO << "Not all read yet because of bandwidth limits";
return false;
} else {
if (_bandwidthManager) {
#include "account.h"
#include "asserts.h"
+#include <QLoggingCategory>
+
namespace OCC {
+Q_LOGGING_CATEGORY(lcDeleteJob, "sync.networkjob.delete", QtInfoMsg)
+Q_LOGGING_CATEGORY(lcPropagateRemoteDelete, "sync.propagator.remotedelete", QtInfoMsg)
+
DeleteJob::DeleteJob(AccountPtr account, const QString& path, QObject* parent)
: AbstractNetworkJob(account, path, parent)
{ }
}
if( reply()->error() != QNetworkReply::NoError ) {
- qWarning() << Q_FUNC_INFO << " Network error: " << reply()->errorString();
+ qCWarning(lcDeleteJob) << " Network error: " << reply()->errorString();
}
AbstractNetworkJob::start();
}
if (propagator()->_abortRequested.fetchAndAddRelaxed(0))
return;
- qDebug() << Q_FUNC_INFO << _item->_file;
+ qCDebug(lcPropagateRemoteDelete) << _item->_file;
_job = new DeleteJob(propagator()->account(),
propagator()->_remoteFolder + _item->_file,
ASSERT(_job);
- qDebug() << Q_FUNC_INFO << _job->reply()->request().url() << "FINISHED WITH STATUS"
+ qCDebug(lcPropagateRemoteDelete) << _job->reply()->request().url() << "FINISHED WITH STATUS"
<< _job->reply()->error()
<< (_job->reply()->error() == QNetworkReply::NoError ? QLatin1String("") : _job->errorString());
#include "syncjournalfilerecord.h"
#include "propagateremotedelete.h"
#include "asserts.h"
+
#include <QFile>
+#include <QLoggingCategory>
namespace OCC {
+Q_LOGGING_CATEGORY(lcPropagateRemoteMkdir, "sync.propagator.remotemkdir", QtInfoMsg)
+
void PropagateRemoteMkdir::start()
{
if (propagator()->_abortRequested.fetchAndAddRelaxed(0))
return;
- qDebug() << Q_FUNC_INFO << _item->_file;
+ qCDebug(lcPropagateRemoteMkdir) << _item->_file;
propagator()->_activeJobList.append(this);
if (propagator()->_abortRequested.fetchAndAddRelaxed(0))
return;
- qDebug() << Q_FUNC_INFO << _item->_file;
+ qCDebug(lcPropagateRemoteMkdir) << _item->_file;
_job = new MkColJob(propagator()->account(),
propagator()->_remoteFolder + _item->_file,
ASSERT(_job);
- qDebug() << Q_FUNC_INFO << _job->reply()->request().url() << "FINISHED WITH STATUS"
+ qCDebug(lcPropagateRemoteMkdir) << _job->reply()->request().url() << "FINISHED WITH STATUS"
<< _job->reply()->error()
<< (_job->reply()->error() == QNetworkReply::NoError ? QLatin1String("") : _job->errorString());
namespace OCC {
+Q_LOGGING_CATEGORY(lcPropagateRemoteMove, "sync.propagator.remotemove", QtInfoMsg)
+
MoveJob::MoveJob(AccountPtr account, const QString& path,
const QString &destination, QObject* parent)
: AbstractNetworkJob(account, path, parent), _destination(destination)
}
if( reply()->error() != QNetworkReply::NoError ) {
- qWarning() << Q_FUNC_INFO << " Network error: " << reply()->errorString();
+ qCWarning(lcPropagateRemoteMove) << " Network error: " << reply()->errorString();
}
AbstractNetworkJob::start();
}
if (propagator()->_abortRequested.fetchAndAddRelaxed(0))
return;
- qDebug() << Q_FUNC_INFO << _item->_file << _item->_renameTarget;
+ qCDebug(lcPropagateRemoteMove) << _item->_file << _item->_renameTarget;
QString targetFile(propagator()->getFilePath(_item->_renameTarget));
ASSERT(_job);
- qDebug() << Q_FUNC_INFO << _job->reply()->request().url() << "FINISHED WITH STATUS"
+ qCDebug(lcPropagateRemoteMove) << _job->reply()->request().url() << "FINISHED WITH STATUS"
<< _job->reply()->error()
<< (_job->reply()->error() == QNetworkReply::NoError ? QLatin1String("") : _job->errorString());
record._contentChecksum = oldRecord._contentChecksum;
record._contentChecksumType = oldRecord._contentChecksumType;
if (record._fileSize != oldRecord._fileSize) {
- qDebug() << "Warning: file sizes differ on server vs sync journal: " << record._fileSize << oldRecord._fileSize;
+ qCDebug(lcPropagateRemoteMove) << "Warning: file sizes differ on server vs sync journal: " << record._fileSize << oldRecord._fileSize;
record._fileSize = oldRecord._fileSize; // server might have claimed different size, we take the old one from the DB
}
}
namespace OCC {
+Q_LOGGING_CATEGORY(lcPutFile, "sync.networkjob.put", QtInfoMsg)
+Q_LOGGING_CATEGORY(lcPoll, "sync.networkjob.poll", QtInfoMsg)
+Q_LOGGING_CATEGORY(lcPropagateUpload, "sync.propagator.upload", QtInfoMsg)
+
/**
* We do not want to upload files that are currently being modified.
* To avoid that, we don't upload files that have a modification time
}
if( reply()->error() != QNetworkReply::NoError ) {
- qWarning() << Q_FUNC_INFO << " Network error: " << reply()->errorString();
+ qCWarning(lcPutFile) << " Network error: " << reply()->errorString();
}
connect(reply(), SIGNAL(uploadProgress(qint64,qint64)), this, SIGNAL(uploadProgress(qint64,qint64)));
}
QByteArray jsonData = reply()->readAll().trimmed();
- qDebug() << Q_FUNC_INFO << ">" << jsonData << "<" << reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
+ qCDebug(lcPoll) << ">" << jsonData << "<" << reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
QJsonParseError jsonParseError;
QJsonObject status = QJsonDocument::fromJson(jsonData, &jsonParseError).object();
if (jsonParseError.error != QJsonParseError::NoError) {
}
qint64 UploadDevice::readData(char* data, qint64 maxlen) {
- //qDebug() << Q_FUNC_INFO << maxlen << _read << _size << _bandwidthQuota;
if (_data.size() - _read <= 0) {
// at end
if (_bandwidthManager) {
if (isBandwidthLimited()) {
maxlen = qMin(maxlen, _bandwidthQuota);
if (maxlen <= 0) { // no quota
- //qDebug() << "no quota";
return 0;
}
_bandwidthQuota -= maxlen;
void UploadDevice::slotJobUploadProgress(qint64 sent, qint64 t)
{
- //qDebug() << Q_FUNC_INFO << sent << _read << t << _size << _bandwidthQuota;
if (sent == 0 || t == 0) {
return;
}
}
qint64 UploadDevice::size() const{
-// qDebug() << this << Q_FUNC_INFO << _size;
return _data.size();
}
qint64 UploadDevice::bytesAvailable() const
{
-// qDebug() << this << Q_FUNC_INFO << _size << _read << QIODevice::bytesAvailable()
-// << _size - _read + QIODevice::bytesAvailable();
return _data.size() - _read + QIODevice::bytesAvailable();
}
auto uploadInfo = propagator()->_journal->getUploadInfo(_item->_file);
uploadInfo._errorCount += 1;
if (uploadInfo._errorCount > 3) {
- qDebug() << "Reset transfer of" << _item->_file
+ qCDebug(lcPropagateUpload) << "Reset transfer of" << _item->_file
<< "due to repeated error" << _item->_httpErrorCode;
uploadInfo = SyncJournalDb::UploadInfo();
} else {
- qDebug() << "Error count for maybe-reset error" << _item->_httpErrorCode
+ qCDebug(lcPropagateUpload) << "Error count for maybe-reset error" << _item->_httpErrorCode
<< "on file" << _item->_file
<< "is" << uploadInfo._errorCount;
}
{
foreach(auto *job, _jobs) {
if (job->reply()) {
- qDebug() << Q_FUNC_INFO << job << this->_item->_file;
+ qCDebug(lcPropagateUpload) << job << this->_item->_file;
job->reply()->abort();
}
}
#include <QBuffer>
#include <QFile>
-#include <QDebug>
#include <QElapsedTimer>
namespace OCC {
+
+Q_DECLARE_LOGGING_CATEGORY(lcPropagateUpload)
+
class BandwidthManager;
/**
if (_sent > _item->_size) {
// Normally this can't happen because the size is xor'ed with the transfer id, and it is
// therefore impossible that there is more data on the server than on the file.
- qWarning() << "Inconsistency while resuming " << _item->_file
+ qCWarning(lcPropagateUpload) << "Inconsistency while resuming " << _item->_file
<< ": the size on the server (" << _sent << ") is bigger than the size of the file ("
<< _item->_size << ")";
startNewUpload();
return;
}
- qDebug() << "Resuming "<< _item->_file << " from chunk " << _currentChunk << "; sent ="<< _sent;
+ qCDebug(lcPropagateUpload) << "Resuming "<< _item->_file << " from chunk " << _currentChunk << "; sent ="<< _sent;
if (!_serverChunks.isEmpty()) {
- qDebug() << "To Delete" << _serverChunks.keys();
+ qCDebug(lcPropagateUpload) << "To Delete" << _serverChunks.keys();
propagator()->_activeJobList.append(this);
_removeJobError = false;
abortWithError(status, job->errorString());
return;
} else {
- qWarning() << "DeleteJob errored out" << job->errorString() << job->reply()->url();
+ qCWarning(lcPropagateUpload) << "DeleteJob errored out" << job->errorString() << job->reply()->url();
_removeJobError = true;
// Let the other jobs finish
}
const QString fileName = propagator()->getFilePath(_item->_file);
if (! device->prepareAndOpen(fileName, _sent, _currentChunkSize)) {
- qDebug() << "ERR: Could not prepare upload device: " << device->errorString();
+ qCDebug(lcPropagateUpload) << "ERR: Could not prepare upload device: " << device->errorString();
// If the file is currently locked, we want to retry the sync
// when it becomes available again.
slotJobDestroyed(job); // remove it from the _jobs list
- qDebug() << job->reply()->request().url() << "FINISHED WITH STATUS"
+ qCDebug(lcPropagateUpload) << job->reply()->request().url() << "FINISHED WITH STATUS"
<< job->reply()->error()
<< (job->reply()->error() == QNetworkReply::NoError ? QLatin1String("") : job->errorString())
<< job->reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute)
if (err == QNetworkReply::OperationCanceledError && job->reply()->property("owncloud-should-soft-cancel").isValid()) {
// Abort the job and try again later.
// This works around a bug in QNAM wich might reuse a non-empty buffer for the next request.
- qDebug() << "Forcing job abort on HTTP connection reset with Qt < 5.4.2.";
+ qCDebug(lcPropagateUpload) << "Forcing job abort on HTTP connection reset with Qt < 5.4.2.";
propagator()->_anotherSyncNeeded = true;
abortWithError(SyncFileItem::SoftError, tr("Forcing job abort on HTTP connection reset with Qt < 5.4.2."));
return;
_item->_httpErrorCode = job->reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
QByteArray replyContent;
QString errorString = job->errorStringParsingBody(&replyContent);
- qDebug() << replyContent; // display the XML error in the debug
+ qCDebug(lcPropagateUpload) << replyContent; // display the XML error in the debug
// Ensure errors that should eventually reset the chunked upload are tracked.
checkResettingErrors();
targetSize,
propagator()->syncOptions()._maxChunkSize);
- qDebug() << "Chunked upload of" << _currentChunkSize << "bytes took" << uploadTime
+ qCDebug(lcPropagateUpload) << "Chunked upload of" << _currentChunkSize << "bytes took" << uploadTime
<< "ms, desired is" << targetDuration << "ms, expected good chunk size is"
<< predictedGoodSize << "bytes and nudged next chunk size to "
<< propagator()->_chunkSize << "bytes";
QByteArray fid = job->reply()->rawHeader("OC-FileID");
if(fid.isEmpty()) {
- qWarning() << "Server did not return a OC-FileID" << _item->_file;
+ qCWarning(lcPropagateUpload) << "Server did not return a OC-FileID" << _item->_file;
abortWithError(SyncFileItem::NormalError, tr("Missing File ID from server"));
return;
} else {
// the old file id should only be empty for new files uploaded
if( !_item->_fileId.isEmpty() && _item->_fileId != fid ) {
- qDebug() << "WARN: File ID changed!" << _item->_fileId << fid;
+ qCDebug(lcPropagateUpload) << "WARN: File ID changed!" << _item->_fileId << fid;
}
_item->_fileId = fid;
}
_item->_etag = getEtagFromReply(job->reply());;
if (_item->_etag.isEmpty()) {
- qWarning() << "Server did not return an ETAG" << _item->_file;
+ qCWarning(lcPropagateUpload) << "Server did not return an ETAG" << _item->_file;
abortWithError(SyncFileItem::NormalError, tr("Missing ETag from server"));
return;
}
#ifdef WITH_TESTING
// performance logging
quint64 duration = _stopWatch.stop();
- qDebug() << "*==* duration UPLOAD" << _item->_size
+ qCDebug(lcPropagateUpload) << "*==* duration UPLOAD" << _item->_size
<< _stopWatch.durationOfLap(QLatin1String("ContentChecksum"))
<< _stopWatch.durationOfLap(QLatin1String("TransmissionChecksum"))
<< duration;
#include <cstring>
namespace OCC {
+
void PropagateUploadFileV1::doStartUpload()
{
_chunkCount = std::ceil(_item->_size / double(chunkSize()));
if (progressInfo._valid && Utility::qDateTimeToTime_t(progressInfo._modtime) == _item->_modtime ) {
_startChunk = progressInfo._chunk;
_transferId = progressInfo._transferid;
- qDebug() << Q_FUNC_INFO << _item->_file << ": Resuming from chunk " << _startChunk;
+ qCDebug(lcPropagateUpload) << _item->_file << ": Resuming from chunk " << _startChunk;
}
_currentChunk = 0;
int sendingChunk = (_currentChunk + _startChunk) % _chunkCount;
// XOR with chunk size to make sure everything goes well if chunk size changes between runs
uint transid = _transferId ^ chunkSize();
- qDebug() << "Upload chunk" << sendingChunk << "of" << _chunkCount << "transferid(remote)=" << transid;
+ qCDebug(lcPropagateUpload) << "Upload chunk" << sendingChunk << "of" << _chunkCount << "transferid(remote)=" << transid;
path += QString("-chunking-%1-%2-%3").arg(transid).arg(_chunkCount).arg(sendingChunk);
headers["OC-Chunked"] = "1";
// if there's only one chunk, it's the final one
isFinalChunk = true;
}
- qDebug() << _chunkCount << isFinalChunk << chunkStart << currentChunkSize;
+ qCDebug(lcPropagateUpload) << _chunkCount << isFinalChunk << chunkStart << currentChunkSize;
if (isFinalChunk && !_transmissionChecksumType.isEmpty()) {
headers[checkSumHeaderC] = makeChecksumHeader(
const QString fileName = propagator()->getFilePath(_item->_file);
if (! device->prepareAndOpen(fileName, chunkStart, currentChunkSize)) {
- qDebug() << "ERR: Could not prepare upload device: " << device->errorString();
+ qCDebug(lcPropagateUpload) << "ERR: Could not prepare upload device: " << device->errorString();
// If the file is currently locked, we want to retry the sync
// when it becomes available again.
slotJobDestroyed(job); // remove it from the _jobs list
- qDebug() << Q_FUNC_INFO << job->reply()->request().url() << "FINISHED WITH STATUS"
+ qCDebug(lcPropagateUpload) << job->reply()->request().url() << "FINISHED WITH STATUS"
<< job->reply()->error()
<< (job->reply()->error() == QNetworkReply::NoError ? QLatin1String("") : job->errorString())
<< job->reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute)
#if QT_VERSION < QT_VERSION_CHECK(5, 4, 2)
if (err == QNetworkReply::OperationCanceledError && job->reply()->property("owncloud-should-soft-cancel").isValid()) { // Abort the job and try again later.
// This works around a bug in QNAM wich might reuse a non-empty buffer for the next request.
- qDebug() << "Forcing job abort on HTTP connection reset with Qt < 5.4.2.";
+ qCDebug(lcPropagateUpload) << "Forcing job abort on HTTP connection reset with Qt < 5.4.2.";
propagator()->_anotherSyncNeeded = true;
abortWithError(SyncFileItem::SoftError, tr("Forcing job abort on HTTP connection reset with Qt < 5.4.2."));
return;
}
QByteArray replyContent;
QString errorString = job->errorStringParsingBody(&replyContent);
- qDebug() << replyContent; // display the XML error in the debug
+ qCDebug(lcPropagateUpload) << replyContent; // display the XML error in the debug
if (_item->_httpErrorCode == 412) {
// Precondition Failed: Either an etag or a checksum mismatch.
QByteArray fid = job->reply()->rawHeader("OC-FileID");
if( !fid.isEmpty() ) {
if( !_item->_fileId.isEmpty() && _item->_fileId != fid ) {
- qDebug() << "WARN: File ID changed!" << _item->_fileId << fid;
+ qCDebug(lcPropagateUpload) << "WARN: File ID changed!" << _item->_fileId << fid;
}
_item->_fileId = fid;
}
if (job->reply()->rawHeader("X-OC-MTime") != "accepted") {
// X-OC-MTime is supported since owncloud 5.0. But not when chunking.
// Normally Owncloud 6 always puts X-OC-MTime
- qWarning() << "Server does not support X-OC-MTime" << job->reply()->rawHeader("X-OC-MTime");
+ qCWarning(lcPropagateUpload) << "Server does not support X-OC-MTime" << job->reply()->rawHeader("X-OC-MTime");
// Well, the mtime was not set
done(SyncFileItem::SoftError, "Server does not support X-OC-MTime");
}
#ifdef WITH_TESTING
// performance logging
quint64 duration = _stopWatch.stop();
- qDebug() << "*==* duration UPLOAD" << _item->_size
+ qCDebug(lcPropagateUpload) << "*==* duration UPLOAD" << _item->_size
<< _stopWatch.durationOfLap(QLatin1String("ContentChecksum"))
<< _stopWatch.durationOfLap(QLatin1String("TransmissionChecksum"))
<< duration;
#else
#include <qsavefile.h>
#endif
-#include <QDebug>
#include <QDateTime>
#include <qstack.h>
#include <QCoreApplication>
namespace OCC {
+Q_LOGGING_CATEGORY(lcPropagateLocalRemove, "sync.propagator.localremove", QtInfoMsg)
+Q_LOGGING_CATEGORY(lcPropagateLocalMkdir, "sync.propagator.localmkdir", QtInfoMsg)
+Q_LOGGING_CATEGORY(lcPropagateLocalRename, "sync.propagator.localrename", QtInfoMsg)
+
/**
* Code inspired from Qt5's QDir::removeRecursively
* The code will update the database in case of error.
if (!ok) {
_error += PropagateLocalRemove::tr("Error removing '%1': %2;").
arg(QDir::toNativeSeparators(di.filePath()), removeError) + " ";
- qDebug() << "Error removing " << di.filePath() << ':' << removeError;
+ qCDebug(lcPropagateLocalRemove) << "Error removing " << di.filePath() << ':' << removeError;
}
}
if (success && !ok) {
if (!success) {
_error += PropagateLocalRemove::tr("Could not remove folder '%1'")
.arg(QDir::toNativeSeparators(absolute)) + " ";
- qDebug() << "Error removing folder" << absolute;
+ qCDebug(lcPropagateLocalRemove) << "Error removing folder" << absolute;
}
}
return success;
QString filename = propagator()->_localDir + _item->_file;
- qDebug() << filename;
+ qCDebug(lcPropagateLocalRemove) << filename;
if( propagator()->localFileNameClash(_item->_file)) {
done(SyncFileItem::NormalError, tr("Could not remove %1 because of a local file name clash")
}
if( Utility::fsCasePreserving() && propagator()->localFileNameClash(_item->_file ) ) {
- qDebug() << "WARN: new folder to create locally already exists!";
+ qCDebug(lcPropagateLocalMkdir) << "WARN: new folder to create locally already exists!";
done( SyncFileItem::NormalError, tr("Attention, possible case sensitivity clash with %1").arg(newDirStr) );
return;
}
// to _item->renameTarget and the file is not moved as a result.
if (_item->_file != _item->_renameTarget) {
propagator()->reportProgress(*_item, 0);
- qDebug() << "MOVE " << existingFile << " => " << targetFile;
+ qCDebug(lcPropagateLocalRename) << "MOVE " << existingFile << " => " << targetFile;
if (QString::compare(_item->_file, _item->_renameTarget, Qt::CaseInsensitive) != 0
&& propagator()->localFileNameClash(_item->_renameTarget)) {
#include "owncloudpropagator.h"
#include <QFile>
-#include <qdebug.h>
namespace OCC {
#include <assert.h>
#include <QCoreApplication>
-#include <QDebug>
#include <QSslSocket>
#include <QDir>
+#include <QLoggingCategory>
#include <QMutexLocker>
#include <QThread>
#include <QStringList>
namespace OCC {
+Q_LOGGING_CATEGORY(lcEngine, "sync.engine")
+
bool SyncEngine::s_anySyncRunning = false;
qint64 SyncEngine::minimumFileAgeForUpload = 2000;
bool SyncEngine::checkErrorBlacklisting( SyncFileItem &item )
{
if( !_journal ) {
- qWarning() << "Journal is undefined!";
+ qCWarning(lcEngine) << "Journal is undefined!";
return false;
}
// If duration has expired, it's not blacklisted anymore
time_t now = Utility::qDateTimeToTime_t(QDateTime::currentDateTime());
if( now >= entry._lastTryTime + entry._ignoreDuration ) {
- qDebug() << "blacklist entry for " << item._file << " has expired!";
+ qCDebug(lcEngine) << "blacklist entry for " << item._file << " has expired!";
return false;
}
if(item._modtime == 0 || entry._lastTryModtime == 0) {
return false;
} else if( item._modtime != entry._lastTryModtime ) {
- qDebug() << item._file << " is blacklisted, but has changed mtime!";
+ qCDebug(lcEngine) << item._file << " is blacklisted, but has changed mtime!";
return false;
} else if( item._renameTarget != entry._renameTarget) {
- qDebug() << item._file << " is blacklisted, but rename target changed from" << entry._renameTarget;
+ qCDebug(lcEngine) << item._file << " is blacklisted, but rename target changed from" << entry._renameTarget;
return false;
}
} else if( item._direction == SyncFileItem::Down ) {
// download, check the etag.
if( item._etag.isEmpty() || entry._lastTryEtag.isEmpty() ) {
- qDebug() << item._file << "one ETag is empty, no blacklisting";
+ qCDebug(lcEngine) << item._file << "one ETag is empty, no blacklisting";
return false;
} else if( item._etag != entry._lastTryEtag ) {
- qDebug() << item._file << " is blacklisted, but has changed etag!";
+ qCDebug(lcEngine) << item._file << " is blacklisted, but has changed etag!";
return false;
}
}
- qDebug() << "Item is on blacklist: " << entry._file
+ qCDebug(lcEngine) << "Item is on blacklist: " << entry._file
<< "retries:" << entry._retryCount
<< "for another" << (entry._lastTryTime + entry._ignoreDuration - now) << "s";
item._instruction = CSYNC_INSTRUCTION_ERROR;
_journal->getAndDeleteStaleDownloadInfos(download_file_paths);
foreach (const SyncJournalDb::DownloadInfo & deleted_info, deleted_infos) {
const QString tmppath = _propagator->getFilePath(deleted_info._tmpfile);
- qDebug() << "Deleting stale temporary file: " << tmppath;
+ qCDebug(lcEngine) << "Deleting stale temporary file: " << tmppath;
FileSystem::remove(tmppath);
}
}
auto instruction = file->instruction;
if (utf8State.invalidChars > 0 || utf8State.remainingChars > 0) {
- qWarning() << "File ignored because of invalid utf-8 sequence: " << file->path;
+ qCWarning(lcEngine) << "File ignored because of invalid utf-8 sequence: " << file->path;
instruction = CSYNC_INSTRUCTION_IGNORE;
} else {
renameTarget = codec->toUnicode(file->rename_path, qstrlen(file->rename_path), &utf8State);
if (utf8State.invalidChars > 0 || utf8State.remainingChars > 0) {
- qWarning() << "File ignored because of invalid utf-8 sequence in the rename_path: " << file->path << file->rename_path;
+ qCWarning(lcEngine) << "File ignored because of invalid utf-8 sequence in the rename_path: " << file->path << file->rename_path;
instruction = CSYNC_INSTRUCTION_IGNORE;
}
if (instruction == CSYNC_INSTRUCTION_RENAME) {
item->_modtime = file->modtime;
} else {
if (instruction != CSYNC_INSTRUCTION_NONE) {
- qWarning() << "ERROR: Instruction" << item->_instruction << "vs" << instruction << "for" << fileUtf8;
+ qCWarning(lcEngine) << "ERROR: Instruction" << item->_instruction << "vs" << instruction << "for" << fileUtf8;
ASSERT(false);
// Set instruction to NONE for safety.
file->instruction = item->_instruction = instruction = CSYNC_INSTRUCTION_NONE;
// issues or DST changes. (We simply ignore files that goes in the past less than
// two hours for the backup detection heuristics.)
_backInTimeFiles++;
- qDebug() << file->path << "has a timestamp earlier than the local file";
+ qCDebug(lcEngine) << file->path << "has a timestamp earlier than the local file";
} else if (difftime > 0) {
_hasForwardInTimeFiles = true;
}
if( errStr.contains("ownclouds://") ) errStr.replace("ownclouds://", "https://");
if( errStr.contains("owncloud://") ) errStr.replace("owncloud://", "http://");
- qDebug() << " #### ERROR during "<< state << ": " << errStr;
+ qCDebug(lcEngine) << " #### ERROR during "<< state << ": " << errStr;
if( CSYNC_STATUS_IS_EQUAL( err, CSYNC_STATUS_ABORTED) ) {
- qDebug() << "Update phase was aborted by user!";
+ qCDebug(lcEngine) << "Update phase was aborted by user!";
} else if( CSYNC_STATUS_IS_EQUAL( err, CSYNC_STATUS_SERVICE_UNAVAILABLE ) ||
CSYNC_STATUS_IS_EQUAL( err, CSYNC_STATUS_CONNECT_ERROR )) {
emit csyncUnavailable();
if (_journal->exists()) {
QVector< SyncJournalDb::PollInfo > pollInfos = _journal->getPollInfos();
if (!pollInfos.isEmpty()) {
- qDebug() << "Finish Poll jobs before starting a sync";
+ qCDebug(lcEngine) << "Finish Poll jobs before starting a sync";
CleanupPollsJob *job = new CleanupPollsJob(pollInfos, _account,
_journal, _localPath, this);
connect(job, SIGNAL(finished()), this, SLOT(startSync()));
const qint64 minFree = criticalFreeSpaceLimit();
const qint64 freeBytes = Utility::freeDiskSpace(_localPath);
if (freeBytes >= 0) {
- qDebug() << "There are" << freeBytes << "bytes available at" << _localPath
+ qCDebug(lcEngine) << "There are" << freeBytes << "bytes available at" << _localPath
<< "and at least" << minFree << "are required";
if (freeBytes < minFree) {
_anotherSyncNeeded = DelayedFollowUp;
return;
}
} else {
- qDebug() << "Could not determine free space available at" << _localPath;
+ qCDebug(lcEngine) << "Could not determine free space available at" << _localPath;
}
_syncItemMap.clear();
int fileRecordCount = -1;
if (!_journal->exists()) {
- qDebug() << "===== new sync (no sync journal exists)";
+ qCDebug(lcEngine) << "New sync (no sync journal exists)";
} else {
- qDebug() << "===== sync with existing sync journal";
+ qCDebug(lcEngine) << "Sync with existing sync journal";
}
- QString verStr("===== Using Qt ");
+ QString verStr("Using Qt ");
verStr.append( qVersion() );
#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
verStr.append( " SSL library " ).append(QSslSocket::sslLibraryVersionString().toUtf8().data());
#endif
verStr.append( " on ").append(Utility::platformName());
- qDebug() << verStr;
+ qCDebug(lcEngine) << verStr;
fileRecordCount = _journal->getFileRecordCount(); // this creates the DB if it does not exist yet
if( fileRecordCount == -1 ) {
- qDebug() << "No way to create a sync journal!";
+ qCDebug(lcEngine) << "No way to create a sync journal!";
emit csyncError(tr("Unable to open or create the local sync database. Make sure you have write access in the sync folder."));
finalize(false);
return;
auto selectiveSyncBlackList = _journal->getSelectiveSyncList(SyncJournalDb::SelectiveSyncBlackList, &ok);
if (ok) {
bool usingSelectiveSync = (!selectiveSyncBlackList.isEmpty());
- qDebug() << Q_FUNC_INFO << (usingSelectiveSync ? "====Using Selective Sync" : "====NOT Using Selective Sync");
+ qCDebug(lcEngine) << (usingSelectiveSync ? "Using Selective Sync" : "NOT Using Selective Sync");
} else {
- qDebug() << Q_FUNC_INFO << "Could not retrieve selective sync list from DB";
+ qCDebug(lcEngine) << "Could not retrieve selective sync list from DB";
emit csyncError(tr("Unable to read the blacklist from the local database"));
finalize(false);
return;
_stopWatch.start();
- qDebug() << "#### Discovery start #################################################### >>";
+ qCDebug(lcEngine) << "#### Discovery start #################################################### >>";
// Usually the discovery runs in the background: We want to avoid
// stealing too much time from other processes that the user might
_discoveryMainThread = new DiscoveryMainThread(account());
_discoveryMainThread->setParent(this);
connect(this, SIGNAL(finished(bool)), _discoveryMainThread, SLOT(deleteLater()));
- qDebug() << "=====Server" << account()->serverVersion()
+ qCDebug(lcEngine) << "=====Server" << account()->serverVersion()
<< QString("rootEtagChangesNotOnlySubFolderEtags=%1").arg(account()->rootEtagChangesNotOnlySubFolderEtags());
if (account()->rootEtagChangesNotOnlySubFolderEtags()) {
connect(_discoveryMainThread, SIGNAL(etag(QString)), this, SLOT(slotRootEtagReceived(QString)));
_journal->getSelectiveSyncList(SyncJournalDb::SelectiveSyncWhiteList, &ok);
if (!ok) {
delete discoveryJob;
- qDebug() << Q_FUNC_INFO << "Unable to read selective sync list, aborting.";
+ qCDebug(lcEngine) << "Unable to read selective sync list, aborting.";
emit csyncError(tr("Unable to read from the sync journal."));
finalize(false);
return;
void SyncEngine::slotRootEtagReceived(const QString &e) {
if (_remoteRootEtag.isEmpty()) {
- qDebug() << Q_FUNC_INFO << e;
+ qCDebug(lcEngine) << e;
_remoteRootEtag = e;
emit rootEtag(_remoteRootEtag);
}
handleSyncError(_csync_ctx, "csync_update");
return;
}
- qDebug() << "<<#### Discovery end #################################################### " << _stopWatch.addLapTime(QLatin1String("Discovery Finished"));
+ qCDebug(lcEngine) << "<<#### Discovery end #################################################### " << _stopWatch.addLapTime(QLatin1String("Discovery Finished"));
// Sanity check
if (!_journal->isConnected()) {
- qDebug() << "Bailing out, DB failure";
+ qCDebug(lcEngine) << "Bailing out, DB failure";
emit csyncError(tr("Cannot open the sync journal"));
finalize(false);
return;
return;
}
- qDebug() << "<<#### Reconcile end #################################################### " << _stopWatch.addLapTime(QLatin1String("Reconcile Finished"));
+ qCDebug(lcEngine) << "<<#### Reconcile end #################################################### " << _stopWatch.addLapTime(QLatin1String("Reconcile Finished"));
_hasNoneFiles = false;
_hasRemoveFile = false;
_renamedFolders.clear();
if( csync_walk_local_tree(_csync_ctx, &treewalkLocal, 0) < 0 ) {
- qDebug() << "Error in local treewalk.";
+ qCDebug(lcEngine) << "Error in local treewalk.";
walkOk = false;
}
if( walkOk && csync_walk_remote_tree(_csync_ctx, &treewalkRemote, 0) < 0 ) {
- qDebug() << "Error in remote treewalk.";
+ qCDebug(lcEngine) << "Error in remote treewalk.";
}
if (_csync_ctx->remote.root_perms) {
_remotePerms[QLatin1String("")] = _csync_ctx->remote.root_perms;
- qDebug() << "Permissions of the root folder: " << _remotePerms[QLatin1String("")];
+ qCDebug(lcEngine) << "Permissions of the root folder: " << _remotePerms[QLatin1String("")];
}
// Re-init the csync context to free memory
}
if (!_hasNoneFiles && _hasRemoveFile) {
- qDebug() << Q_FUNC_INFO << "All the files are going to be changed, asking the user";
+ qCDebug(lcEngine) << "All the files are going to be changed, asking the user";
bool cancel = false;
emit aboutToRemoveAllFiles(syncItems.first()->_direction, &cancel);
if (cancel) {
- qDebug() << Q_FUNC_INFO << "Abort sync";
+ qCDebug(lcEngine) << "Abort sync";
finalize(false);
return;
}
// Note that an empty ("") fingerprint is valid and means it was empty on the server before.
if (!databaseFingerprint.isNull()
&& _discoveryMainThread->_dataFingerprint != databaseFingerprint) {
- qDebug() << "data fingerprint changed, assume restore from backup" << databaseFingerprint << _discoveryMainThread->_dataFingerprint;
+ qCDebug(lcEngine) << "data fingerprint changed, assume restore from backup" << databaseFingerprint << _discoveryMainThread->_dataFingerprint;
restoreOldFiles(syncItems);
} else if (!_hasForwardInTimeFiles && _backInTimeFiles >= 2
&& _account->serverVersionInt() < Account::makeServerVersion(9, 1, 0)) {
// The server before ownCloud 9.1 did not have the data-fingerprint property. So in that
// case we use heuristics to detect restored backup. This is disabled with newer version
// because this causes troubles to the user and is not as reliable as the data-fingerprint.
- qDebug() << "All the changes are bringing files in the past, asking the user";
+ qCDebug(lcEngine) << "All the changes are bringing files in the past, asking the user";
// this typically happen when a backup is restored on the server
bool restore = false;
emit aboutToRestoreBackup(&restore);
#ifndef NDEBUG
QString script = qgetenv("OWNCLOUD_POST_UPDATE_SCRIPT");
- qDebug() << "OOO => Post Update Script: " << script;
+ qCDebug(lcEngine) << "OOO => Post Update Script: " << script;
QProcess::execute(script.toUtf8());
#else
- qWarning() << "**** Attention: POST_UPDATE_SCRIPT installed, but not executed because compiled with NDEBUG";
+ qCWarning(lcEngine) << "**** Attention: POST_UPDATE_SCRIPT installed, but not executed because compiled with NDEBUG";
#endif
}
_propagator->start(syncItems);
- qDebug() << "<<#### Post-Reconcile end #################################################### " << _stopWatch.addLapTime(QLatin1String("Post-Reconcile Finished"));
+ qCDebug(lcEngine) << "<<#### Post-Reconcile end #################################################### " << _stopWatch.addLapTime(QLatin1String("Post-Reconcile Finished"));
}
void SyncEngine::slotCleanPollsJobAborted(const QString &error)
;
if( propDownloadLimit != 0 || propUploadLimit != 0 ) {
- qDebug() << " N------N Network Limits (down/up) " << propDownloadLimit << propUploadLimit;
+ qCDebug(lcEngine) << " N------N Network Limits (down/up) " << propDownloadLimit << propUploadLimit;
}
}
void SyncEngine::slotItemCompleted(const SyncFileItemPtr &item)
{
const char * instruction_str = csync_instruction_str(item->_instruction);
- qDebug() << Q_FUNC_INFO << item->_file << instruction_str << item->_status << item->_errorString;
+ qCDebug(lcEngine) << item->_file << instruction_str << item->_status << item->_errorString;
_progressInfo->setProgressComplete(*item);
// emit the treewalk results.
if( ! _journal->postSyncCleanup( _seenFiles, _temporarilyUnavailablePaths ) ) {
- qDebug() << "Cleaning of synced ";
+ qCDebug(lcEngine) << "Cleaning of synced ";
}
_journal->commit("All Finished.", false);
csync_commit(_csync_ctx);
_journal->close();
- qDebug() << "CSync run took " << _stopWatch.addLapTime(QLatin1String("Sync Finished"));
+ qCDebug(lcEngine) << "CSync run took " << _stopWatch.addLapTime(QLatin1String("Sync Finished"));
_stopWatch.stop();
s_anySyncRunning = false;
// No permissions set
break;
} else if ((*it)->_isDirectory && !perms.contains("K")) {
- qDebug() << "checkForPermission: ERROR" << (*it)->_file;
+ qCDebug(lcEngine) << "checkForPermission: ERROR" << (*it)->_file;
(*it)->_instruction = CSYNC_INSTRUCTION_ERROR;
(*it)->_status = SyncFileItem::NormalError;
(*it)->_errorString = tr("Not allowed because you don't have permission to add subfolders to that folder");
// but delete and upload. It will then be restored if needed.
_journal->avoidRenamesOnNextSync((*it)->_file);
_anotherSyncNeeded = ImmediateFollowUp;
- qDebug() << "Moving of " << (*it)->_file << " canceled because no permission to add parent folder";
+ qCDebug(lcEngine) << "Moving of " << (*it)->_file << " canceled because no permission to add parent folder";
}
(*it)->_instruction = CSYNC_INSTRUCTION_ERROR;
(*it)->_status = SyncFileItem::SoftError;
}
} else if (!(*it)->_isDirectory && !perms.contains("C")) {
- qDebug() << "checkForPermission: ERROR" << (*it)->_file;
+ qCDebug(lcEngine) << "checkForPermission: ERROR" << (*it)->_file;
(*it)->_instruction = CSYNC_INSTRUCTION_ERROR;
(*it)->_status = SyncFileItem::NormalError;
(*it)->_errorString = tr("Not allowed because you don't have permission to add files in that folder");
// No permissions set
break;
} if (!perms.contains("W")) {
- qDebug() << "checkForPermission: RESTORING" << (*it)->_file;
+ qCDebug(lcEngine) << "checkForPermission: RESTORING" << (*it)->_file;
(*it)->_instruction = CSYNC_INSTRUCTION_CONFLICT;
(*it)->_direction = SyncFileItem::Down;
(*it)->_isRestoration = true;
break;
}
if (!perms.contains("D")) {
- qDebug() << "checkForPermission: RESTORING" << (*it)->_file;
+ qCDebug(lcEngine) << "checkForPermission: RESTORING" << (*it)->_file;
(*it)->_instruction = CSYNC_INSTRUCTION_NEW;
(*it)->_direction = SyncFileItem::Down;
(*it)->_isRestoration = true;
it = it_next;
if ((*it)->_instruction != CSYNC_INSTRUCTION_REMOVE) {
- qWarning() << "non-removed job within a removed folder"
+ qCWarning(lcEngine) << "non-removed job within a removed folder"
<< (*it)->_file << (*it)->_instruction;
continue;
}
- qDebug() << "checkForPermission: RESTORING" << (*it)->_file;
+ qCDebug(lcEngine) << "checkForPermission: RESTORING" << (*it)->_file;
(*it)->_instruction = CSYNC_INSTRUCTION_NEW;
(*it)->_direction = SyncFileItem::Down;
(*it)->_direction = SyncFileItem::Down;
(*it)->_errorString = tr("Move not allowed, item restored");
(*it)->_isRestoration = true;
- qDebug() << "checkForPermission: MOVING BACK" << (*it)->_file;
+ qCDebug(lcEngine) << "checkForPermission: MOVING BACK" << (*it)->_file;
// in case something does wrong, we will not do it next time
_journal->avoidRenamesOnNextSync((*it)->_file);
} else
sourceOK ? tr("the destination") : tr("the source"));
(*it)->_errorString = errorString;
- qDebug() << "checkForPermission: ERROR MOVING" << (*it)->_file << errorString;
+ qCDebug(lcEngine) << "checkForPermission: ERROR MOVING" << (*it)->_file << errorString;
// Avoid a rename on next sync:
// TODO: do the resolution now already so we don't need two sync
(*it)->_instruction = CSYNC_INSTRUCTION_ERROR;
(*it)->_status = SyncFileItem::NormalError;
(*it)->_errorString = errorString;
- qDebug() << "checkForPermission: ERROR MOVING" << (*it)->_file;
+ qCDebug(lcEngine) << "checkForPermission: ERROR MOVING" << (*it)->_file;
}
}
}
switch ((*it)->_instruction) {
case CSYNC_INSTRUCTION_SYNC:
- qDebug() << "restoreOldFiles: RESTORING" << (*it)->_file;
+ qCDebug(lcEngine) << "restoreOldFiles: RESTORING" << (*it)->_file;
(*it)->_instruction = CSYNC_INSTRUCTION_CONFLICT;
break;
case CSYNC_INSTRUCTION_REMOVE:
- qDebug() << "restoreOldFiles: RESTORING" << (*it)->_file;
+ qCDebug(lcEngine) << "restoreOldFiles: RESTORING" << (*it)->_file;
(*it)->_instruction = CSYNC_INSTRUCTION_NEW;
(*it)->_direction = SyncFileItem::Up;
break;
{
// Sets a flag for the update phase
csync_request_abort(_csync_ctx);
- qDebug() << Q_FUNC_INFO << _discoveryMainThread;
+ qCDebug(lcEngine) << "Aborting sync, _discoveryMainThread:" << _discoveryMainThread;
// Aborts the discovery phase job
if (_discoveryMainThread) {
_discoveryMainThread->abort();
#include "syncfilestatus.h"
-#include <QDebug>
-
namespace OCC {
SyncFileStatus::SyncFileStatus()
:_tag(StatusNone), _sharedWithMe(false)
#include "syncjournalfilerecord.h"
#include "asserts.h"
+#include <QLoggingCategory>
+
namespace OCC {
+Q_LOGGING_CATEGORY(lcStatusTracker, "sync.statustracker", QtInfoMsg)
+
static SyncFileStatus::SyncFileStatusTag lookupProblem(const QString &pathToMatch, const std::map<QString, SyncFileStatus::SyncFileStatusTag> &problemMap)
{
auto lower = problemMap.lower_bound(pathToMatch);
for (auto it = lower; it != problemMap.cend(); ++it) {
const QString &problemPath = it->first;
SyncFileStatus::SyncFileStatusTag severity = it->second;
- // qDebug() << Q_FUNC_INFO << pathToMatch << severity << problemPath;
+
if (problemPath == pathToMatch) {
return severity;
} else if (severity == SyncFileStatus::StatusError
std::swap(_syncProblems, oldProblems);
foreach (const SyncFileItemPtr &item, items) {
- // qDebug() << Q_FUNC_INFO << "Investigating" << item->destination() << item->_status << item->_instruction;
+ qCDebug(lcStatusTracker) << "Investigating" << item->destination() << item->_status << item->_instruction;
_dirtyPaths.remove(item->destination());
if (showErrorInSocketApi(*item)) {
void SyncFileStatusTracker::slotItemCompleted(const SyncFileItemPtr &item)
{
- // qDebug() << Q_FUNC_INFO << item.destination() << item._status << item._instruction;
+ qCDebug(lcStatusTracker) << "Item completed" << item->destination() << item->_status << item->_instruction;
if (showErrorInSocketApi(*item)) {
_syncProblems[item->_file] = SyncFileStatus::StatusError;
*/
#include <QFile>
+#include <QLoggingCategory>
#include <QStringList>
-#include <QDebug>
#include <QElapsedTimer>
#include <QUrl>
namespace OCC {
+Q_LOGGING_CATEGORY(lcDb, "sync.database", QtInfoMsg)
+
SyncJournalDb::SyncJournalDb(const QString& dbFilePath, QObject *parent) :
QObject(parent),
_dbFile(dbFilePath),
if( FileSystem::fileExists( newDbName ) ) {
if( !FileSystem::remove(newDbName, &error) ) {
- qDebug() << "Database migration: Could not remove db file" << newDbName
+ qCDebug(lcDb) << "Database migration: Could not remove db file" << newDbName
<< "due to" << error;
return false;
}
}
if( FileSystem::fileExists( newDbNameWal ) ) {
if( !FileSystem::remove(newDbNameWal, &error) ) {
- qDebug() << "Database migration: Could not remove db WAL file" << newDbNameWal
+ qCDebug(lcDb) << "Database migration: Could not remove db WAL file" << newDbNameWal
<< "due to" << error;
return false;
}
}
if( FileSystem::fileExists( newDbNameShm ) ) {
if( !FileSystem::remove(newDbNameShm, &error) ) {
- qDebug() << "Database migration: Could not remove db SHM file" << newDbNameShm
+ qCDebug(lcDb) << "Database migration: Could not remove db SHM file" << newDbNameShm
<< "due to" << error;
return false;
}
}
if( !FileSystem::rename(oldDbName, newDbName, &error) ) {
- qDebug() << "Database migration: could not rename " << oldDbName
+ qCDebug(lcDb) << "Database migration: could not rename " << oldDbName
<< "to" << newDbName << ":" << error;
return false;
}
if( !FileSystem::rename(oldDbNameWal, newDbNameWal, &error) ) {
- qDebug() << "Database migration: could not rename " << oldDbNameWal
+ qCDebug(lcDb) << "Database migration: could not rename " << oldDbNameWal
<< "to" << newDbNameWal << ":" << error;
return false;
}
if( !FileSystem::rename(oldDbNameShm, newDbNameShm, &error) ) {
- qDebug() << "Database migration: could not rename " << oldDbNameShm
+ qCDebug(lcDb) << "Database migration: could not rename " << oldDbNameShm
<< "to" << newDbNameShm << ":" << error;
return false;
}
- qDebug() << "Journal successfully migrated from" << oldDbName << "to" << newDbName;
+ qCDebug(lcDb) << "Journal successfully migrated from" << oldDbName << "to" << newDbName;
return true;
}
SqlQuery pragma1(_db);
pragma1.prepare("PRAGMA wal_checkpoint(FULL);");
if (!pragma1.exec()) {
- qDebug() << pragma1.error();
+ qCDebug(lcDb) << pragma1.error();
} else {
- qDebug() << Q_FUNC_INFO << "took" << t.elapsed() << "msec";
+ qCDebug(lcDb) << "took" << t.elapsed() << "msec";
}
}
{
if( _transaction == 0 ) {
if( !_db.transaction() ) {
- qDebug() << "ERROR starting transaction: " << _db.error();
+ qCDebug(lcDb) << "ERROR starting transaction: " << _db.error();
return;
}
_transaction = 1;
- // qDebug() << "XXX Transaction start!";
+ // qCDebug(lcDb) << "XXX Transaction start!";
} else {
- qDebug() << "Database Transaction is running, not starting another one!";
+ qCDebug(lcDb) << "Database Transaction is running, not starting another one!";
}
}
{
if( _transaction == 1 ) {
if( ! _db.commit() ) {
- qDebug() << "ERROR committing to the database: " << _db.error();
+ qCDebug(lcDb) << "ERROR committing to the database: " << _db.error();
return;
}
_transaction = 0;
- // qDebug() << "XXX Transaction END!";
+ // qCDebug(lcDb) << "XXX Transaction END!";
} else {
- qDebug() << "No database Transaction to commit";
+ qCDebug(lcDb) << "No database Transaction to commit";
}
}
bool SyncJournalDb::sqlFail( const QString& log, const SqlQuery& query )
{
commitTransaction();
- qWarning() << "SQL Error" << log << query.error();
+ qCWarning(lcDb) << "SQL Error" << log << query.error();
ASSERT(false);
_db.close();
return false;
// See #2693: Some exFAT file systems seem unable to cope with the
// WAL journaling mode. They work fine with DELETE.
QString fileSystem = FileSystem::fileSystemForPath(dbPath);
- qDebug() << "Detected filesystem" << fileSystem << "for" << dbPath;
+ qCDebug(lcDb) << "Detected filesystem" << fileSystem << "for" << dbPath;
if (fileSystem.contains("FAT")) {
- qDebug() << "Filesystem contains FAT - using DELETE journal mode";
+ qCDebug(lcDb) << "Filesystem contains FAT - using DELETE journal mode";
return "DELETE";
}
#else
}
if( _dbFile.isEmpty()) {
- qDebug() << "Database filename" + _dbFile + " is empty";
+ qCDebug(lcDb) << "Database filename" + _dbFile + " is empty";
return false;
}
// The database file is created by this call (SQLITE_OPEN_CREATE)
if( !_db.openOrCreateReadWrite(_dbFile) ) {
QString error = _db.error();
- qDebug() << "Error opening the db: " << error;
+ qCDebug(lcDb) << "Error opening the db: " << error;
return false;
}
if( !QFile::exists(_dbFile) ) {
- qDebug() << "Database file" + _dbFile + " does not exist";
+ qCDebug(lcDb) << "Database file" + _dbFile + " does not exist";
return false;
}
return sqlFail("SELECT sqlite_version()", pragma1);
} else {
pragma1.next();
- qDebug() << "sqlite3 version" << pragma1.stringValue(0);
+ qCDebug(lcDb) << "sqlite3 version" << pragma1.stringValue(0);
}
// Allow forcing the journal mode for debugging
return sqlFail("Set PRAGMA journal_mode", pragma1);
} else {
pragma1.next();
- qDebug() << "sqlite3 journal_mode=" << pragma1.stringValue(0);
+ qCDebug(lcDb) << "sqlite3 journal_mode=" << pragma1.stringValue(0);
}
// For debugging purposes, allow temp_store to be set
if (!pragma1.exec()) {
return sqlFail("Set PRAGMA temp_store", pragma1);
}
- qDebug() << "sqlite3 with temp_store =" << env_temp_store;
+ qCDebug(lcDb) << "sqlite3 with temp_store =" << env_temp_store;
}
pragma1.prepare("PRAGMA synchronous = 1;");
SqlQuery versionQuery("SELECT major, minor, patch FROM version;", _db);
if (!versionQuery.next()) {
// If there was no entry in the table, it means we are likely upgrading from 1.5
- qDebug() << Q_FUNC_INFO << "possibleUpgradeFromMirall_1_5 detected!";
+ qCDebug(lcDb) << "possibleUpgradeFromMirall_1_5 detected!";
forceRemoteDiscovery = true;
createQuery.prepare("INSERT INTO version VALUES (?1, ?2, ?3, ?4);");
int patch = versionQuery.intValue(2);
if( major == 1 && minor == 8 && (patch == 0 || patch == 1) ) {
- qDebug() << Q_FUNC_INFO << "possibleUpgradeFromMirall_1_8_0_or_1 detected!";
+ qCDebug(lcDb) << "possibleUpgradeFromMirall_1_8_0_or_1 detected!";
forceRemoteDiscovery = true;
}
// local files and a remote discovery will fix them.
// See #5190 #5242.
if( major == 2 && minor < 3) {
- qDebug() << Q_FUNC_INFO << "upgrade form client < 2.3.0 detected! forcing remote discovery";
+ qCDebug(lcDb) << "upgrade form client < 2.3.0 detected! forcing remote discovery";
forceRemoteDiscovery = true;
}
bool rc = updateDatabaseStructure();
if( !rc ) {
- qDebug() << "WARN: Failed to update the database structure!";
+ qCDebug(lcDb) << "WARN: Failed to update the database structure!";
}
/*
void SyncJournalDb::close()
{
QMutexLocker locker(&_mutex);
- qDebug() << Q_FUNC_INFO << _dbFile;
+ qCDebug(lcDb) << "Closing DB" << _dbFile;
commitTransaction();
if(!query.exec()) {
QString err = query.error();
- qDebug() << "Error creating prepared statement: " << query.lastQuery() << ", Error:" << err;;
+ qCDebug(lcDb) << "Error creating prepared statement: " << query.lastQuery() << ", Error:" << err;;
return columns;
}
}
}
}
- qDebug() << "Columns in the current journal: " << columns;
+ qCDebug(lcDb) << "Columns in the current journal: " << columns;
return columns;
}
QString prefix = record._path + "/";
foreach(const QString &it, _avoidReadFromDbOnNextSyncFilter) {
if (it.startsWith(prefix)) {
- qDebug() << "Filtered writing the etag of" << prefix << "because it is a prefix of" << it;
+ qCDebug(lcDb) << "Filtered writing the etag of" << prefix << "because it is a prefix of" << it;
record._etag = "_invalid_";
break;
}
_setFileRecordQuery->bindValue(16, contentChecksumTypeId );
if( !_setFileRecordQuery->exec() ) {
- qWarning() << "Error SQL statement setFileRecord: " << _setFileRecordQuery->lastQuery() << " :"
+ qCWarning(lcDb) << "Error SQL statement setFileRecord: " << _setFileRecordQuery->lastQuery() << " :"
<< _setFileRecordQuery->error();
return false;
}
- qDebug() << _setFileRecordQuery->lastQuery() << phash << plen << record._path << record._inode
+ qCDebug(lcDb) << _setFileRecordQuery->lastQuery() << phash << plen << record._path << record._inode
<< QString::number(Utility::qDateTimeToTime_t(record._modtime)) << QString::number(record._type)
<< record._etag << record._fileId << record._remotePerm << record._fileSize << (record._serverHasIgnoredFiles ? 1:0)
<< record._contentChecksum << record._contentChecksumType << contentChecksumTypeId;
_setFileRecordQuery->reset_and_clear_bindings();
return true;
} else {
- qDebug() << "Failed to connect database.";
+ qCDebug(lcDb) << "Failed to connect database.";
return false; // checkConnect failed.
}
}
_deleteFileRecordPhash->bindValue( 1, QString::number(phash) );
if( !_deleteFileRecordPhash->exec() ) {
- qWarning() << "Exec error of SQL statement: "
+ qCWarning(lcDb) << "Exec error of SQL statement: "
<< _deleteFileRecordPhash->lastQuery()
<< " : " << _deleteFileRecordPhash->error();
return false;
}
- qDebug() << _deleteFileRecordPhash->lastQuery() << phash << filename;
+ qCDebug(lcDb) << _deleteFileRecordPhash->lastQuery() << phash << filename;
_deleteFileRecordPhash->reset_and_clear_bindings();
if( recursively) {
_deleteFileRecordRecursively->reset_and_clear_bindings();
_deleteFileRecordRecursively->bindValue(1, filename);
if( !_deleteFileRecordRecursively->exec() ) {
- qWarning() << "Exec error of SQL statement: "
+ qCWarning(lcDb) << "Exec error of SQL statement: "
<< _deleteFileRecordRecursively->lastQuery()
<< " : " << _deleteFileRecordRecursively->error();
return false;
}
- qDebug() << _deleteFileRecordRecursively->lastQuery() << filename;
+ qCDebug(lcDb) << _deleteFileRecordRecursively->lastQuery() << filename;
_deleteFileRecordRecursively->reset_and_clear_bindings();
}
return true;
} else {
- qDebug() << "Failed to connect database.";
+ qCDebug(lcDb) << "Failed to connect database.";
return false; // checkConnect failed.
}
}
if (!_getFileRecordQuery->exec()) {
QString err = _getFileRecordQuery->error();
- qDebug() << "Error creating prepared statement: " << _getFileRecordQuery->lastQuery() << ", Error:" << err;;
+ qCDebug(lcDb) << "Error creating prepared statement: " << _getFileRecordQuery->lastQuery() << ", Error:" << err;;
locker.unlock();
close();
return rec;
int errId = _getFileRecordQuery->errorId();
if( errId != SQLITE_DONE ) { // only do this if the problem is different from SQLITE_DONE
QString err = _getFileRecordQuery->error();
- qDebug() << "No journal entry found for " << filename << "Error: " << err;
+ qCDebug(lcDb) << "No journal entry found for " << filename << "Error: " << err;
locker.unlock();
close();
locker.relock();
if (!query.exec()) {
QString err = query.error();
- qDebug() << "Error creating prepared statement: " << query.lastQuery() << ", Error:" << err;;
+ qCDebug(lcDb) << "Error creating prepared statement: " << query.lastQuery() << ", Error:" << err;;
return false;
}
if( superfluousItems.count() ) {
QString sql = "DELETE FROM metadata WHERE phash in ("+ superfluousItems.join(",")+")";
- qDebug() << "Sync Journal cleanup: " << sql;
+ qCDebug(lcDb) << "Sync Journal cleanup: " << sql;
SqlQuery delQuery(_db);
delQuery.prepare(sql);
if( !delQuery.exec() ) {
QString err = delQuery.error();
- qDebug() << "Error removing superfluous journal entries: " << delQuery.lastQuery() << ", Error:" << err;;
+ qCDebug(lcDb) << "Error removing superfluous journal entries: " << delQuery.lastQuery() << ", Error:" << err;;
return false;
}
}
if (!query.exec()) {
QString err = query.error();
- qDebug() << "Error creating prepared statement: " << query.lastQuery() << ", Error:" << err;;
+ qCDebug(lcDb) << "Error creating prepared statement: " << query.lastQuery() << ", Error:" << err;;
return 0;
}
qlonglong phash = getPHash(filename);
if( !checkConnect() ) {
- qDebug() << "Failed to connect database.";
+ qCDebug(lcDb) << "Failed to connect database.";
return false;
}
query->bindValue(3, checksumTypeId);
if( !query->exec() ) {
- qWarning() << "Error SQL statement setFileRecordChecksumQuery: "
+ qCWarning(lcDb) << "Error SQL statement setFileRecordChecksumQuery: "
<< query->lastQuery() << " :"
<< query->error();
return false;
}
- qDebug() << query->lastQuery() << phash << contentChecksum
+ qCDebug(lcDb) << query->lastQuery() << phash << contentChecksum
<< contentChecksumType << checksumTypeId;
query->reset_and_clear_bindings();
qlonglong phash = getPHash(filename);
if( !checkConnect() ) {
- qDebug() << "Failed to connect database.";
+ qCDebug(lcDb) << "Failed to connect database.";
return false;
}
query->bindValue(4, size);
if( !query->exec() ) {
- qWarning() << "Error SQL statement updateLocalMetadata: "
+ qCWarning(lcDb) << "Error SQL statement updateLocalMetadata: "
<< query->lastQuery() << " :"
<< query->error();
return false;
}
- qDebug() << query->lastQuery() << phash << inode
+ qCDebug(lcDb) << query->lastQuery() << phash << inode
<< modtime << size;
query->reset_and_clear_bindings();
if (entries.isEmpty())
return true;
- qDebug() << "Removing stale " << qPrintable(name) << " entries: " << entries.join(", ");
+ qCDebug(lcDb) << "Removing stale " << qPrintable(name) << " entries: " << entries.join(", ");
// FIXME: Was ported from execBatch, check if correct!
foreach( const QString& entry, entries ) {
query.reset_and_clear_bindings();
query.bindValue(1, entry);
if (!query.exec()) {
QString err = query.error();
- qDebug() << "Error removing stale " << qPrintable(name) << " entries: "
+ qCDebug(lcDb) << "Error removing stale " << qPrintable(name) << " entries: "
<< query.lastQuery() << ", Error:" << err;
return false;
}
if (!_getDownloadInfoQuery->exec()) {
QString err = _getDownloadInfoQuery->error();
- qDebug() << "Database error for file " << file << " : " << _getDownloadInfoQuery->lastQuery() << ", Error:" << err;;
+ qCDebug(lcDb) << "Database error for file " << file << " : " << _getDownloadInfoQuery->lastQuery() << ", Error:" << err;;
return res;
}
_setDownloadInfoQuery->bindValue(4, i._errorCount );
if( !_setDownloadInfoQuery->exec() ) {
- qWarning() << "Exec error of SQL statement: " << _setDownloadInfoQuery->lastQuery() << " :" << _setDownloadInfoQuery->error();
+ qCWarning(lcDb) << "Exec error of SQL statement: " << _setDownloadInfoQuery->lastQuery() << " :" << _setDownloadInfoQuery->error();
return;
}
- qDebug() << _setDownloadInfoQuery->lastQuery() << file << i._tmpfile << i._etag << i._errorCount;
+ qCDebug(lcDb) << _setDownloadInfoQuery->lastQuery() << file << i._tmpfile << i._etag << i._errorCount;
_setDownloadInfoQuery->reset_and_clear_bindings();
} else {
_deleteDownloadInfoQuery->bindValue( 1, file );
if( !_deleteDownloadInfoQuery->exec() ) {
- qWarning() << "Exec error of SQL statement: " << _deleteDownloadInfoQuery->lastQuery() << " : " << _deleteDownloadInfoQuery->error();
+ qCWarning(lcDb) << "Exec error of SQL statement: " << _deleteDownloadInfoQuery->lastQuery() << " : " << _deleteDownloadInfoQuery->error();
return;
}
- qDebug() << _deleteDownloadInfoQuery->lastQuery() << file;
+ qCDebug(lcDb) << _deleteDownloadInfoQuery->lastQuery() << file;
_deleteDownloadInfoQuery->reset_and_clear_bindings();
}
}
if (!query.exec()) {
QString err = query.error();
- qDebug() << "Error creating prepared statement: " << query.lastQuery() << ", Error:" << err;
+ qCDebug(lcDb) << "Error creating prepared statement: " << query.lastQuery() << ", Error:" << err;
return empty_result;
}
if (!_getUploadInfoQuery->exec()) {
QString err = _getUploadInfoQuery->error();
- qDebug() << "Database error for file " << file << " : " << _getUploadInfoQuery->lastQuery() << ", Error:" << err;
+ qCDebug(lcDb) << "Database error for file " << file << " : " << _getUploadInfoQuery->lastQuery() << ", Error:" << err;
return res;
}
_setUploadInfoQuery->bindValue(6, Utility::qDateTimeToTime_t(i._modtime) );
if( !_setUploadInfoQuery->exec() ) {
- qWarning() << "Exec error of SQL statement: " << _setUploadInfoQuery->lastQuery() << " :" << _setUploadInfoQuery->error();
+ qCWarning(lcDb) << "Exec error of SQL statement: " << _setUploadInfoQuery->lastQuery() << " :" << _setUploadInfoQuery->error();
return;
}
- qDebug() << _setUploadInfoQuery->lastQuery() << file << i._chunk << i._transferid << i._errorCount;
+ qCDebug(lcDb) << _setUploadInfoQuery->lastQuery() << file << i._chunk << i._transferid << i._errorCount;
_setUploadInfoQuery->reset_and_clear_bindings();
} else {
_deleteUploadInfoQuery->reset_and_clear_bindings();
_deleteUploadInfoQuery->bindValue(1, file);
if( !_deleteUploadInfoQuery->exec() ) {
- qWarning() << "Exec error of SQL statement: " << _deleteUploadInfoQuery->lastQuery() << " : " << _deleteUploadInfoQuery->error();
+ qCWarning(lcDb) << "Exec error of SQL statement: " << _deleteUploadInfoQuery->lastQuery() << " : " << _deleteUploadInfoQuery->error();
return;
}
- qDebug() << _deleteUploadInfoQuery->lastQuery() << file;
+ qCDebug(lcDb) << _deleteUploadInfoQuery->lastQuery() << file;
_deleteUploadInfoQuery->reset_and_clear_bindings();
}
}
if (!query.exec()) {
QString err = query.error();
- qDebug() << "Error creating prepared statement: " << query.lastQuery() << ", Error:" << err;
+ qCDebug(lcDb) << "Error creating prepared statement: " << query.lastQuery() << ", Error:" << err;
return ids;
}
}
_getErrorBlacklistQuery->reset_and_clear_bindings();
} else {
- qWarning() << "Exec error blacklist: " << _getErrorBlacklistQuery->lastQuery() << " : "
+ qCWarning(lcDb) << "Exec error blacklist: " << _getErrorBlacklistQuery->lastQuery() << " : "
<< _getErrorBlacklistQuery->error();
}
}
if (!query.exec()) {
QString err = query.error();
- qDebug() << "Error creating prepared statement: " << query.lastQuery() << ", Error:" << err;
+ qCDebug(lcDb) << "Error creating prepared statement: " << query.lastQuery() << ", Error:" << err;
return false;
}
if( ! query.exec() ) {
sqlFail("Deletion of blacklist item failed.", query);
}
- qDebug() << query.lastQuery() << file;
+ qCDebug(lcDb) << query.lastQuery() << file;
}
}
_setErrorBlacklistQuery->bindValue(8, item._renameTarget);
if( !_setErrorBlacklistQuery->exec() ) {
QString bug = _setErrorBlacklistQuery->error();
- qDebug() << "SQL exec blacklistitem insert or replace failed: "<< bug;
+ qCDebug(lcDb) << "SQL exec blacklistitem insert or replace failed: "<< bug;
}
- qDebug() << "set blacklist entry for " << item._file << item._retryCount
+ qCDebug(lcDb) << "set blacklist entry for " << item._file << item._retryCount
<< item._errorString << item._lastTryTime << item._ignoreDuration
<< item._lastTryModtime << item._lastTryEtag << item._renameTarget ;
_setErrorBlacklistQuery->reset_and_clear_bindings();
if (!query.exec()) {
QString err = query.error();
- qDebug() << "Database error :" << query.lastQuery() << ", Error:" << err;
+ qCDebug(lcDb) << "Database error :" << query.lastQuery() << ", Error:" << err;
return res;
}
}
if (info._url.isEmpty()) {
- qDebug() << "Deleting Poll job" << info._file;
+ qCDebug(lcDb) << "Deleting Poll job" << info._file;
SqlQuery query("DELETE FROM poll WHERE path=?", _db);
query.bindValue(1, info._file);
if( !query.exec() ) {
- qDebug() << "SQL error in setPollInfo: "<< query.error();
+ qCDebug(lcDb) << "SQL error in setPollInfo: "<< query.error();
} else {
- qDebug() << query.lastQuery() << info._file;
+ qCDebug(lcDb) << query.lastQuery() << info._file;
}
} else {
SqlQuery query("INSERT OR REPLACE INTO poll (path, modtime, pollpath) VALUES( ? , ? , ? )", _db);
query.bindValue(2, QString::number(info._modtime));
query.bindValue(3, info._url);
if( !query.exec() ) {
- qDebug() << "SQL error in setPollInfo: "<< query.error();
+ qCDebug(lcDb) << "SQL error in setPollInfo: "<< query.error();
} else {
- qDebug() << query.lastQuery() << info._file << info._url;
+ qCDebug(lcDb) << query.lastQuery() << info._file << info._url;
}
}
}
_getSelectiveSyncListQuery->reset_and_clear_bindings();
_getSelectiveSyncListQuery->bindValue(1, int(type));
if (!_getSelectiveSyncListQuery->exec()) {
- qWarning() << "SQL query failed: "<< _getSelectiveSyncListQuery->error();
+ qCWarning(lcDb) << "SQL query failed: "<< _getSelectiveSyncListQuery->error();
*ok = false;
return result;
}
SqlQuery delQuery("DELETE FROM selectivesync WHERE type == ?1", _db);
delQuery.bindValue(1, int(type));
if( !delQuery.exec() ) {
- qWarning() << "SQL error when deleting selective sync list" << list << delQuery.error();
+ qCWarning(lcDb) << "SQL error when deleting selective sync list" << list << delQuery.error();
}
SqlQuery insQuery("INSERT INTO selectivesync VALUES (?1, ?2)" , _db);
insQuery.bindValue(1, path);
insQuery.bindValue(2, int(type));
if (!insQuery.exec()) {
- qWarning() << "SQL error when inserting into selective sync" << type << path << delQuery.error();
+ qCWarning(lcDb) << "SQL error when inserting into selective sync" << type << path << delQuery.error();
}
}
}
query.bindValue(1, path);
query.bindValue(2, path);
if( !query.exec() ) {
- qDebug() << Q_FUNC_INFO << "SQL error in avoidRenamesOnNextSync: "<< query.error();
+ qCDebug(lcDb) << "SQL error in avoidRenamesOnNextSync: "<< query.error();
} else {
- qDebug() << Q_FUNC_INFO << query.lastQuery() << path << "(" << query.numRowsAffected() << " rows)";
+ qCDebug(lcDb) << query.lastQuery() << path << "(" << query.numRowsAffected() << " rows)";
}
// We also need to remove the ETags so the update phase refreshes the directory paths
query.prepare("UPDATE metadata SET md5='_invalid_' WHERE ?1 LIKE(path||'/%') AND type == 2;"); // CSYNC_FTW_TYPE_DIR == 2
query.bindValue(1, fileName);
if( !query.exec() ) {
- qDebug() << Q_FUNC_INFO << "SQL error in avoidRenamesOnNextSync: "<< query.error();
+ qCDebug(lcDb) << "SQL error in avoidRenamesOnNextSync: "<< query.error();
} else {
- qDebug() << Q_FUNC_INFO << query.lastQuery() << fileName << "(" << query.numRowsAffected() << " rows)";
+ qCDebug(lcDb) << query.lastQuery() << fileName << "(" << query.numRowsAffected() << " rows)";
}
// Prevent future overwrite of the etag for this sync
void SyncJournalDb::forceRemoteDiscoveryNextSyncLocked()
{
- qDebug() << "Forcing remote re-discovery by deleting folder Etags";
+ qCDebug(lcDb) << "Forcing remote re-discovery by deleting folder Etags";
SqlQuery deleteRemoteFolderEtagsQuery(_db);
deleteRemoteFolderEtagsQuery.prepare("UPDATE metadata SET md5='_invalid_' WHERE type=2;");
if( !deleteRemoteFolderEtagsQuery.exec() ) {
- qDebug() << "ERROR: Query failed" << deleteRemoteFolderEtagsQuery.error();
+ qCDebug(lcDb) << "ERROR: Query failed" << deleteRemoteFolderEtagsQuery.error();
} else {
- qDebug() << "Cleared" << deleteRemoteFolderEtagsQuery.numRowsAffected() << "folder ETags";
+ qCDebug(lcDb) << "Cleared" << deleteRemoteFolderEtagsQuery.numRowsAffected() << "folder ETags";
}
}
query.reset_and_clear_bindings();
query.bindValue(1, checksumTypeId);
if( !query.exec() ) {
- qWarning() << "Error SQL statement getChecksumType: "
+ qCWarning(lcDb) << "Error SQL statement getChecksumType: "
<< query.lastQuery() << " :"
<< query.error();
return 0;
}
if( !query.next() ) {
- qDebug() << "No checksum type mapping found for" << checksumTypeId;
+ qCDebug(lcDb) << "No checksum type mapping found for" << checksumTypeId;
return 0;
}
return query.baValue(0);
_insertChecksumTypeQuery->reset_and_clear_bindings();
_insertChecksumTypeQuery->bindValue(1, checksumType);
if( !_insertChecksumTypeQuery->exec() ) {
- qWarning() << "Error SQL statement insertChecksumType: "
+ qCWarning(lcDb) << "Error SQL statement insertChecksumType: "
<< _insertChecksumTypeQuery->lastQuery() << " :"
<< _insertChecksumTypeQuery->error();
return 0;
_getChecksumTypeIdQuery->reset_and_clear_bindings();
_getChecksumTypeIdQuery->bindValue(1, checksumType);
if( !_getChecksumTypeIdQuery->exec() ) {
- qWarning() << "Error SQL statement getChecksumTypeId: "
+ qCWarning(lcDb) << "Error SQL statement getChecksumTypeId: "
<< _getChecksumTypeIdQuery->lastQuery() << " :"
<< _getChecksumTypeIdQuery->error();
return 0;
}
if( !_getChecksumTypeIdQuery->next() ) {
- qDebug() << "No checksum type mapping found for" << checksumType;
+ qCDebug(lcDb) << "No checksum type mapping found for" << checksumType;
return 0;
}
return _getChecksumTypeIdQuery->intValue(0);
_getDataFingerprintQuery->reset_and_clear_bindings();
if (!_getDataFingerprintQuery->exec()) {
- qWarning() << "Error SQL statement dataFingerprint: "
+ qCWarning(lcDb) << "Error SQL statement dataFingerprint: "
<< _getDataFingerprintQuery->lastQuery() << " :"
<< _getDataFingerprintQuery->error();
return QByteArray();
_setDataFingerprintQuery1->reset_and_clear_bindings();
if (!_setDataFingerprintQuery1->exec()) {
- qWarning() << "Error SQL statement setDataFingerprint1: "
+ qCWarning(lcDb) << "Error SQL statement setDataFingerprint1: "
<< _setDataFingerprintQuery1->lastQuery() << " :"
<< _setDataFingerprintQuery1->error();
}
_setDataFingerprintQuery2->reset_and_clear_bindings();
_setDataFingerprintQuery2->bindValue(1, dataFingerprint);
if (!_setDataFingerprintQuery2->exec()) {
- qWarning() << "Error SQL statement setDataFingerprint2: "
+ qCWarning(lcDb) << "Error SQL statement setDataFingerprint2: "
<< _setDataFingerprintQuery2->lastQuery() << " :"
<< _setDataFingerprintQuery2->error();
}
SqlQuery query(_db);
query.prepare("DELETE FROM metadata;");
if (!query.exec()) {
- qWarning() << "SQL error in clearFileTable" << query.error();
+ qCWarning(lcDb) << "SQL error in clearFileTable" << query.error();
} else {
- qDebug() << query.lastQuery() << "(" << query.numRowsAffected() << " rows)";
+ qCDebug(lcDb) << query.lastQuery() << "(" << query.numRowsAffected() << " rows)";
}
}
void SyncJournalDb::commitInternal(const QString& context, bool startTrans )
{
- qDebug() << Q_FUNC_INFO << "Transaction commit " << context << (startTrans ? "and starting new transaction" : "");
+ qCDebug(lcDb) << "Transaction commit " << context << (startTrans ? "and starting new transaction" : "");
commitTransaction();
if( startTrans ) {
#include "utility.h"
#include "filesystem.h"
+#include <QLoggingCategory>
#include <qfileinfo.h>
-#include <qdebug.h>
#ifdef Q_OS_WIN
#include <windows.h>
namespace OCC {
+Q_LOGGING_CATEGORY(lcFileRecord, "sync.database.filerecord", QtInfoMsg)
+
SyncJournalFileRecord::SyncJournalFileRecord()
:_inode(0), _type(0), _fileSize(0), _serverHasIgnoredFiles(false)
{
FILE_ATTRIBUTE_NORMAL+FILE_FLAG_BACKUP_SEMANTICS, NULL );
if( h == INVALID_HANDLE_VALUE ) {
- qWarning() << "Failed to query the 'inode' because CreateFileW failed for file " << localFileName;
+ qCWarning(lcFileRecord) << "Failed to query the 'inode' because CreateFileW failed for file " << localFileName;
} else {
BY_HANDLE_FILE_INFORMATION fileInfo;
_inode = FileIndex.QuadPart;
} else {
- qWarning() << "Failed to query the 'inode' for file " << localFileName;
+ qCWarning(lcFileRecord) << "Failed to query the 'inode' for file " << localFileName;
}
CloseHandle(h);
#else
struct stat sb;
if( stat(QFile::encodeName(localFileName).constData(), &sb) < 0) {
- qWarning() << "Failed to query the 'inode' for file " << localFileName;
+ qCWarning(lcFileRecord) << "Failed to query the 'inode' for file " << localFileName;
} else {
_inode = sb.st_ino;
}
#endif
- qDebug() << Q_FUNC_INFO << localFileName << "Retrieved inode " << _inode << "(previous item inode: " << item._inode << ")";
+ qCDebug(lcFileRecord) << localFileName << "Retrieved inode " << _inode << "(previous item inode: " << item._inode << ")";
}
#include <QDir>
#include <QFile>
#include <QUrl>
-#include <QDebug>
#include <QProcess>
#include <QObject>
#include <QThread>
namespace OCC {
+Q_LOGGING_CATEGORY(lcUtility, "sync.utility", QtInfoMsg)
+
bool Utility::writeRandomFile( const QString& fname, int size )
{
int maxSize = 10*10*1024;
#include <QByteArray>
#include <QDateTime>
#include <QElapsedTimer>
+#include <QLoggingCategory>
#include <QMap>
#include <QUrl>
#include <memory>
namespace OCC {
+Q_DECLARE_LOGGING_CATEGORY(lcUtility)
+
/** \addtogroup libsync
* @{
*/
#include <CoreServices/CoreServices.h>
#include <CoreFoundation/CoreFoundation.h>
+namespace OCC {
+
static void setupFavLink_private(const QString &folder)
{
// Finder: Place under "Places"/"Favorites" on the left sidebar
return returnValue;
}
+} // namespace OCC
#include <QStandardPaths>
#endif
+namespace OCC {
+
static void setupFavLink_private(const QString &folder) {
// Nautilus: add to ~/.gtk-bookmarks
QFile gtkBookmarks(QDir::homePath()+QLatin1String("/.gtk-bookmarks"));
QString desktopFileLocation = userAutoStartPath+appName+QLatin1String(".desktop");
if (enable) {
if (!QDir().exists(userAutoStartPath) && !QDir().mkpath(userAutoStartPath)) {
- qDebug() << "Could not create autostart folder";
+ qCDebug(lcUtility) << "Could not create autostart folder";
return;
}
QFile iniFile(desktopFileLocation);
if (!iniFile.open(QIODevice::WriteOnly)) {
- qDebug() << "Could not write auto start entry" << desktopFileLocation;
+ qCDebug(lcUtility) << "Could not write auto start entry" << desktopFileLocation;
return;
}
QTextStream ts(&iniFile);
;
} else {
if (!QFile::remove(desktopFileLocation)) {
- qDebug() << "Could not remove autostart desktop file";
+ qCDebug(lcUtility) << "Could not remove autostart desktop file";
}
}
}
{
return true;
}
+
+} // namespace OCC
static const char runPathC[] = "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run";
-
+namespace OCC {
static void setupFavLink_private(const QString &folder)
{
linkName = QDir(links).filePath(folderDir.dirName() + QLatin1String(".lnk"));
CoTaskMemFree(path);
}
- qDebug() << Q_FUNC_INFO << " creating link from " << linkName << " to " << folder;
+ qCDebug(lcUtility) << " creating link from " << linkName << " to " << folder;
if (!QFile::link(folder, linkName))
- qDebug() << Q_FUNC_INFO << "linking" << folder << "to" << linkName << "failed!";
+ qCDebug(lcUtility) << "linking" << folder << "to" << linkName << "failed!";
}
{
return true;
}
+
+} // namespace OCC