using namespace OCC;
-static void nullMessageHandler(QtMsgType, const char *) {}
+static void nullMessageHandler(QtMsgType, const char *)
+{
+}
-struct CmdOptions {
+struct CmdOptions
+{
QString source_dir;
QString target_url;
QString config_directory;
// So we have to use a global variable
CmdOptions *opts = 0;
-const qint64 timeoutToUseMsec = qMax(1000, ConnectionValidator::DefaultCallingIntervalMsec - 5*1000);
+const qint64 timeoutToUseMsec = qMax(1000, ConnectionValidator::DefaultCallingIntervalMsec - 5 * 1000);
class EchoDisabler
{
tcsetattr(STDIN_FILENO, TCSANOW, &tios);
#endif
}
+
private:
#ifdef Q_OS_WIN
DWORD mode = 0;
return QString::fromStdString(s);
}
-class HttpCredentialsText : public HttpCredentials {
+class HttpCredentialsText : public HttpCredentials
+{
public:
- HttpCredentialsText(const QString& user, const QString& password)
- : HttpCredentials(user, password), // FIXME: not working with client certs yet (qknight)
- _sslTrusted(false)
- {}
+ HttpCredentialsText(const QString &user, const QString &password)
+ : HttpCredentials(user, password)
+ , // FIXME: not working with client certs yet (qknight)
+ _sslTrusted(false)
+ {
+ }
- void askFromUser() Q_DECL_OVERRIDE {
+ void askFromUser() Q_DECL_OVERRIDE
+ {
_password = ::queryPassword(user());
_ready = true;
persist();
emit asked();
}
- void setSSLTrusted( bool isTrusted ) {
+ void setSSLTrusted(bool isTrusted)
+ {
_sslTrusted = isTrusted;
}
- bool sslIsTrusted() Q_DECL_OVERRIDE {
+ bool sslIsTrusted() Q_DECL_OVERRIDE
+ {
return _sslTrusted;
}
std::cout << " --version, -v Display version and exit" << std::endl;
std::cout << "" << std::endl;
exit(0);
-
}
-void showVersion() {
+void showVersion()
+{
const char *binaryName = APPLICATION_EXECUTABLE "cmd";
std::cout << binaryName << " version " << qPrintable(Theme::instance()->version()) << std::endl;
exit(0);
}
-void parseOptions( const QStringList& app_args, CmdOptions *options )
+void parseOptions(const QStringList &app_args, CmdOptions *options)
{
QStringList args(app_args);
int argCount = args.count();
- if( argCount < 3 ) {
+ if (argCount < 3) {
if (argCount >= 2) {
const QString option = args.at(1);
if (option == "-v" || option == "--version") {
options->source_dir.append('/');
}
QFileInfo fi(options->source_dir);
- if( !fi.exists() ) {
+ if (!fi.exists()) {
std::cerr << "Source dir '" << qPrintable(options->source_dir) << "' does not exist." << std::endl;
exit(1);
}
QStringListIterator it(args);
// skip file name;
- if (it.hasNext()) it.next();
+ if (it.hasNext())
+ it.next();
- while(it.hasNext()) {
+ while (it.hasNext()) {
const QString option = it.next();
- if( option == "--httpproxy" && !it.peekNext().startsWith("-")) {
+ if (option == "--httpproxy" && !it.peekNext().startsWith("-")) {
options->proxy = it.next();
- } else if( option == "-s" || option == "--silent") {
+ } else if (option == "-s" || option == "--silent") {
options->silent = true;
- } else if( option == "--trust") {
+ } else if (option == "--trust") {
options->trustSSL = true;
- } else if( option == "-n") {
+ } else if (option == "-n") {
options->useNetrc = true;
- } else if( option == "-h") {
+ } else if (option == "-h") {
options->ignoreHiddenFiles = false;
- } else if( option == "--non-interactive") {
+ } else if (option == "--non-interactive") {
options->interactive = false;
- } else if( (option == "-u" || option == "--user") && !it.peekNext().startsWith("-") ) {
- options->user = it.next();
- } else if( (option == "-p" || option == "--password") && !it.peekNext().startsWith("-") ) {
- options->password = it.next();
- } else if( option == "--exclude" && !it.peekNext().startsWith("-") ) {
- options->exclude = it.next();
- } else if( option == "--unsyncedfolders" && !it.peekNext().startsWith("-") ) {
+ } else if ((option == "-u" || option == "--user") && !it.peekNext().startsWith("-")) {
+ options->user = it.next();
+ } else if ((option == "-p" || option == "--password") && !it.peekNext().startsWith("-")) {
+ options->password = it.next();
+ } else if (option == "--exclude" && !it.peekNext().startsWith("-")) {
+ options->exclude = it.next();
+ } else if (option == "--unsyncedfolders" && !it.peekNext().startsWith("-")) {
options->unsyncedfolders = it.next();
- } else if( option == "--nonshib" ) {
+ } else if (option == "--nonshib") {
options->nonShib = true;
- } else if( option == "--davpath" && !it.peekNext().startsWith("-") ) {
+ } else if (option == "--davpath" && !it.peekNext().startsWith("-")) {
options->davPath = it.next();
- } else if( option == "--max-sync-retries" && !it.peekNext().startsWith("-") ) {
+ } else if (option == "--max-sync-retries" && !it.peekNext().startsWith("-")) {
options->restartTimes = it.next().toInt();
- } else if( option == "--uplimit" && !it.peekNext().startsWith("-") ) {
+ } else if (option == "--uplimit" && !it.peekNext().startsWith("-")) {
options->uplimit = it.next().toInt() * 1000;
- } else if( option == "--downlimit" && !it.peekNext().startsWith("-") ) {
+ } else if (option == "--downlimit" && !it.peekNext().startsWith("-")) {
options->downlimit = it.next().toInt() * 1000;
} else {
help();
}
}
- if( options->target_url.isEmpty() || options->source_dir.isEmpty() ) {
+ if (options->target_url.isEmpty() || options->source_dir.isEmpty()) {
help();
}
}
bool ok;
auto oldBlackListSet = journal->getSelectiveSyncList(SyncJournalDb::SelectiveSyncBlackList, &ok).toSet();
- if( ok ) {
+ if (ok) {
auto blackListSet = newList.toSet();
auto changes = (oldBlackListSet - blackListSet) + (blackListSet - oldBlackListSet);
- foreach(const auto &it, changes) {
+ foreach (const auto &it, changes) {
journal->avoidReadFromDbOnNextSync(it);
}
}
}
-int main(int argc, char **argv) {
+int main(int argc, char **argv)
+{
QCoreApplication app(argc, argv);
#ifdef Q_OS_WIN
// Ensure OpenSSL config file is only loaded from app directory
- QString opensslConf = QCoreApplication::applicationDirPath()+QString("/openssl.cnf");
+ QString opensslConf = QCoreApplication::applicationDirPath() + QString("/openssl.cnf");
qputenv("OPENSSL_CONF", opensslConf.toLocal8Bit());
#endif
options.downlimit = 0;
ClientProxy clientProxy;
- parseOptions( app.arguments(), &options );
+ parseOptions(app.arguments(), &options);
csync_set_log_level(options.silent ? 1 : 11);
if (options.silent) {
AccountPtr account = Account::create();
- if( !account ) {
+ if (!account) {
qFatal("Could not initialize account!");
return EXIT_FAILURE;
}
// check if the webDAV path was added to the url and append if not.
- if(!options.target_url.endsWith("/")) {
+ if (!options.target_url.endsWith("/")) {
options.target_url.append("/");
}
- if( options.nonShib ) {
+ if (options.nonShib) {
account->setNonShib(true);
}
- if(!options.davPath.isEmpty()) {
- account->setDavPath( options.davPath );
+ if (!options.davPath.isEmpty()) {
+ account->setDavPath(options.davPath);
}
- if( !options.target_url.contains( account->davPath() )) {
+ if (!options.target_url.contains(account->davPath())) {
options.target_url.append(account->davPath());
}
QString user = url.userName();
QString password = url.password();
- if (!options.user.isEmpty()) {
- user = options.user;
- }
-
- if (!options.password.isEmpty()) {
- password = options.password;
- }
-
- if (options.useNetrc) {
- NetrcParser parser;
- if (parser.parse()) {
- NetrcParser::LoginPair pair = parser.find(url.host());
- user = pair.first;
- password = pair.second;
- }
- }
-
- if (options.interactive) {
- if (user.isEmpty()) {
- std::cout << "Please enter user name: ";
- std::string s;
- std::getline(std::cin, s);
- user = QString::fromStdString(s);
- }
- if (password.isEmpty()) {
- password = queryPassword(user);
- }
- }
+ if (!options.user.isEmpty()) {
+ user = options.user;
+ }
+
+ if (!options.password.isEmpty()) {
+ password = options.password;
+ }
+
+ if (options.useNetrc) {
+ NetrcParser parser;
+ if (parser.parse()) {
+ NetrcParser::LoginPair pair = parser.find(url.host());
+ user = pair.first;
+ password = pair.second;
+ }
+ }
+
+ if (options.interactive) {
+ if (user.isEmpty()) {
+ std::cout << "Please enter user name: ";
+ std::string s;
+ std::getline(std::cin, s);
+ user = QString::fromStdString(s);
+ }
+ if (password.isEmpty()) {
+ password = queryPassword(user);
+ }
+ }
// take the unmodified url to pass to csync_create()
QByteArray remUrl = options.target_url.toUtf8();
HttpCredentialsText *cred = new HttpCredentialsText(user, password);
- if( options.trustSSL ) {
+ if (options.trustSSL) {
cred->setSSLTrusted(true);
}
account->setUrl(url);
opts = &options;
- if( !options.proxy.isNull() ) {
+ if (!options.proxy.isNull()) {
QString host;
int port = 0;
bool ok;
QStringList pList = options.proxy.split(':');
- if(pList.count() == 3) {
+ if (pList.count() == 3) {
// http: //192.168.178.23 : 8080
// 0 1 2
host = pList.at(1);
- if( host.startsWith("//") ) host.remove(0, 2);
+ if (host.startsWith("//"))
+ host.remove(0, 2);
port = pList.at(2).toInt(&ok);
}
} else {
clientProxy.setupQtProxyFromConfig();
- QString url( options.target_url );
- if( url.startsWith("owncloud")) {
+ QString url(options.target_url);
+ if (url.startsWith("owncloud")) {
url.remove(0, 8);
url = QString("http%1").arg(url);
}
engine.setNetworkLimits(options.uplimit, options.downlimit);
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
QObject::connect(&engine, &SyncEngine::finished,
- [&app](bool result) { app.exit(result ? EXIT_SUCCESS : EXIT_FAILURE); });
+ [&app](bool result) { app.exit(result ? EXIT_SUCCESS : EXIT_FAILURE); });
#else
QObject::connect(&engine, SIGNAL(finished(bool)), &app, SLOT(quit()));
#endif
QString systemExcludeFile = ConfigFile::excludeFileFromSystem();
// Always try to load the user-provided exclude list if one is specified
- if ( hasUserExcludeFile ) {
+ if (hasUserExcludeFile) {
engine.excludedFiles().addExcludeFilePath(options.exclude);
}
// Load the system list if available, or if there's no user-provided list
- if ( !hasUserExcludeFile || QFile::exists(systemExcludeFile) ) {
+ if (!hasUserExcludeFile || QFile::exists(systemExcludeFile)) {
engine.excludedFiles().addExcludeFilePath(systemExcludeFile);
}
return resultCode;
}
-
* @brief Helper class for command line client
* @ingroup cmd
*/
-class Cmd : public QObject {
+class Cmd : public QObject
+{
Q_OBJECT
public:
- Cmd() : QObject() { }
+ Cmd()
+ : QObject()
+ {
+ }
public slots:
- void transmissionProgressSlot() {
+ void transmissionProgressSlot()
+ {
}
};
namespace OCC {
namespace {
-QString defaultKeyword = QLatin1String("default");
-QString machineKeyword = QLatin1String("machine");
-QString loginKeyword = QLatin1String("login");
-QString passwordKeyword = QLatin1String("password");
-
+ QString defaultKeyword = QLatin1String("default");
+ QString machineKeyword = QLatin1String("machine");
+ QString loginKeyword = QLatin1String("login");
+ QString passwordKeyword = QLatin1String("password");
}
NetrcParser::NetrcParser(const QString &file)
{
_netrcLocation = file;
if (_netrcLocation.isEmpty()) {
- _netrcLocation = QDir::homePath()+QLatin1String("/.netrc");
+ _netrcLocation = QDir::homePath() + QLatin1String("/.netrc");
}
}
-void NetrcParser::tryAddEntryAndClear(QString& machine, LoginPair& pair, bool& isDefault) {
+void NetrcParser::tryAddEntryAndClear(QString &machine, LoginPair &pair, bool &isDefault)
+{
if (isDefault) {
_default = pair;
- } else if (!machine.isEmpty() && !pair.first.isEmpty()){
+ } else if (!machine.isEmpty() && !pair.first.isEmpty()) {
_entries.insert(machine, pair);
}
pair = qMakePair(QString(), QString());
} else if (key == passwordKeyword) {
pair.second = value;
} // ignore unsupported tokens
-
}
tryAddEntryAndClear(machine, pair, isDefault);
bool SimpleSslErrorHandler::handleErrors(QList<QSslError> errors, const QSslConfiguration &conf, QList<QSslCertificate> *certs, OCC::AccountPtr account)
{
- (void) account;
- (void) conf;
+ (void)account;
+ (void)conf;
if (!certs) {
qDebug() << "Certs parameter required but is NULL!";
return false;
}
- foreach( QSslError error, errors ) {
- certs->append( error.certificate() );
+ foreach (QSslError error, errors) {
+ certs->append(error.certificate());
}
return true;
}
-
}
* @brief The SimpleSslErrorHandler class
* @ingroup cmd
*/
-class SimpleSslErrorHandler : public OCC::AbstractSslErrorHandler {
+class SimpleSslErrorHandler : public OCC::AbstractSslErrorHandler
+{
public:
bool handleErrors(QList<QSslError> errors, const QSslConfiguration &conf, QList<QSslCertificate> *certs, OCC::AccountPtr) Q_DECL_OVERRIDE;
};
-
}
#endif // SIMPLESSLERRORHANDLER_H
#include <QApplication>
#include <QDebug>
-int main( int argc, char* argv[] )
+int main(int argc, char *argv[])
{
- QApplication app( argc, argv );
+ QApplication app(argc, argv);
- if ( app.arguments().size() != 2 )
- {
+ if (app.arguments().size() != 2) {
qDebug() << "You need to pass the .dmp file path as only argument";
return 1;
}
// TODO: install socorro ....
- CrashReporter reporter( QUrl( CRASHREPORTER_SUBMIT_URL ), app.arguments() );
+ CrashReporter reporter(QUrl(CRASHREPORTER_SUBMIT_URL), app.arguments());
#ifdef CRASHREPORTER_ICON
reporter.setLogo(QPixmap(CRASHREPORTER_ICON));
reporter.setWindowTitle(CRASHREPORTER_PRODUCT_NAME);
reporter.setText("<html><head/><body><p><span style=\" font-weight:600;\">Sorry!</span> " CRASHREPORTER_PRODUCT_NAME " crashed. Please tell us about it! " CRASHREPORTER_PRODUCT_NAME " has created an error report for you that can help improve the stability in the future. You can now send this report directly to the " CRASHREPORTER_PRODUCT_NAME " developers.</p></body></html>");
- reporter.setReportData( "BuildID", CRASHREPORTER_BUILD_ID );
- reporter.setReportData( "ProductName", CRASHREPORTER_PRODUCT_NAME );
- reporter.setReportData( "Version", CRASHREPORTER_VERSION_STRING );
- reporter.setReportData( "ReleaseChannel", CRASHREPORTER_RELEASE_CHANNEL);
+ reporter.setReportData("BuildID", CRASHREPORTER_BUILD_ID);
+ reporter.setReportData("ProductName", CRASHREPORTER_PRODUCT_NAME);
+ reporter.setReportData("Version", CRASHREPORTER_VERSION_STRING);
+ reporter.setReportData("ReleaseChannel", CRASHREPORTER_RELEASE_CHANNEL);
//reporter.setReportData( "timestamp", QByteArray::number( QDateTime::currentDateTime().toTime_t() ) );
- // add parameters
-
- // << Pair("InstallTime", "1357622062")
- // << Pair("Theme", "classic/1.0")
- // << Pair("Version", "30")
- // << Pair("id", "{ec8030f7-c20a-464f-9b0e-13a3a9e97384}")
- // << Pair("Vendor", "Mozilla")
- // << Pair("EMCheckCompatibility", "true")
- // << Pair("Throttleable", "0")
- // << Pair("URL", "http://code.google.com/p/crashme/")
- // << Pair("version", "20.0a1")
- // << Pair("CrashTime", "1357770042")
- // << Pair("submitted_timestamp", "2013-01-09T22:21:18.646733+00:00")
- // << Pair("buildid", "20130107030932")
- // << Pair("timestamp", "1357770078.646789")
- // << Pair("Notes", "OpenGL: NVIDIA Corporation -- GeForce 8600M GT/PCIe/SSE2 -- 3.3.0 NVIDIA 313.09 -- texture_from_pixmap\r\n")
- // << Pair("StartupTime", "1357769913")
- // << Pair("FramePoisonSize", "4096")
- // << Pair("FramePoisonBase", "7ffffffff0dea000")
- // << Pair("Add-ons", "%7B972ce4c6-7e08-4474-a285-3208198ce6fd%7D:20.0a1,crashme%40ted.mielczarek.org:0.4")
- // << Pair("SecondsSinceLastCrash", "1831736")
- // << Pair("ProductName", "WaterWolf")
- // << Pair("legacy_processing", "0")
- // << Pair("ProductID", "{ec8030f7-c20a-464f-9b0e-13a3a9e97384}")
-
- ;
+ // add parameters
+
+ // << Pair("InstallTime", "1357622062")
+ // << Pair("Theme", "classic/1.0")
+ // << Pair("Version", "30")
+ // << Pair("id", "{ec8030f7-c20a-464f-9b0e-13a3a9e97384}")
+ // << Pair("Vendor", "Mozilla")
+ // << Pair("EMCheckCompatibility", "true")
+ // << Pair("Throttleable", "0")
+ // << Pair("URL", "http://code.google.com/p/crashme/")
+ // << Pair("version", "20.0a1")
+ // << Pair("CrashTime", "1357770042")
+ // << Pair("submitted_timestamp", "2013-01-09T22:21:18.646733+00:00")
+ // << Pair("buildid", "20130107030932")
+ // << Pair("timestamp", "1357770078.646789")
+ // << Pair("Notes", "OpenGL: NVIDIA Corporation -- GeForce 8600M GT/PCIe/SSE2 -- 3.3.0 NVIDIA 313.09 -- texture_from_pixmap\r\n")
+ // << Pair("StartupTime", "1357769913")
+ // << Pair("FramePoisonSize", "4096")
+ // << Pair("FramePoisonBase", "7ffffffff0dea000")
+ // << Pair("Add-ons", "%7B972ce4c6-7e08-4474-a285-3208198ce6fd%7D:20.0a1,crashme%40ted.mielczarek.org:0.4")
+ // << Pair("SecondsSinceLastCrash", "1831736")
+ // << Pair("ProductName", "WaterWolf")
+ // << Pair("legacy_processing", "0")
+ // << Pair("ProductID", "{ec8030f7-c20a-464f-9b0e-13a3a9e97384}")
+
+ ;
// TODO:
// send log
-// QFile logFile( INSERT_FILE_PATH_HERE );
-// logFile.open( QFile::ReadOnly );
-// reporter.setReportData( "upload_file_miralllog", qCompress( logFile.readAll() ), "application/x-gzip", QFileInfo( INSERT_FILE_PATH_HERE ).fileName().toUtf8());
-// logFile.close();
+ // QFile logFile( INSERT_FILE_PATH_HERE );
+ // logFile.open( QFile::ReadOnly );
+ // reporter.setReportData( "upload_file_miralllog", qCompress( logFile.readAll() ), "application/x-gzip", QFileInfo( INSERT_FILE_PATH_HERE ).fileName().toUtf8());
+ // logFile.close();
reporter.show();
auto settings = Utility::settingsWithGroup(QLatin1String(accountsC));
if (settings->status() != QSettings::NoError) {
qCWarning(lcAccountManager) << "Could not read settings from" << settings->fileName()
- << settings->status();
+ << settings->status();
return false;
}
// If there are no accounts, check the old format.
if (settings->childGroups().isEmpty()
- && !settings->contains(QLatin1String(versionC))) {
+ && !settings->contains(QLatin1String(versionC))) {
restoreFromLegacySettings();
return true;
}
- foreach (const auto& accountId, settings->childGroups()) {
+ foreach (const auto &accountId, settings->childGroups()) {
settings->beginGroup(accountId);
if (auto acc = loadAccountHelper(*settings)) {
acc->_id = accountId;
bool AccountManager::restoreFromLegacySettings()
{
qCInfo(lcAccountManager) << "Migrate: restoreFromLegacySettings, checking settings group"
- << Theme::instance()->appName();
+ << Theme::instance()->appName();
// try to open the correctly themed settings
auto settings = Utility::settingsWithGroup(Theme::instance()->appName());
// if the settings file could not be opened, the childKeys list is empty
// then try to load settings from a very old place
- if( settings->childKeys().isEmpty() ) {
+ if (settings->childKeys().isEmpty()) {
// Now try to open the original ownCloud settings to see if they exist.
- QString oCCfgFile = QDir::fromNativeSeparators( settings->fileName() );
+ QString oCCfgFile = QDir::fromNativeSeparators(settings->fileName());
// replace the last two segments with ownCloud/owncloud.cfg
- oCCfgFile = oCCfgFile.left( oCCfgFile.lastIndexOf('/'));
- oCCfgFile = oCCfgFile.left( oCCfgFile.lastIndexOf('/'));
+ oCCfgFile = oCCfgFile.left(oCCfgFile.lastIndexOf('/'));
+ oCCfgFile = oCCfgFile.left(oCCfgFile.lastIndexOf('/'));
oCCfgFile += QLatin1String("/ownCloud/owncloud.cfg");
qCInfo(lcAccountManager) << "Migrate: checking old config " << oCCfgFile;
- QFileInfo fi( oCCfgFile );
- if( fi.isReadable() ) {
+ QFileInfo fi(oCCfgFile);
+ if (fi.isReadable()) {
std::unique_ptr<QSettings> oCSettings(new QSettings(oCCfgFile, QSettings::IniFormat));
oCSettings->beginGroup(QLatin1String("ownCloud"));
// Check the theme url to see if it is the same url that the oC config was for
QString overrideUrl = Theme::instance()->overrideServerUrl();
- if( !overrideUrl.isEmpty() ) {
- if (overrideUrl.endsWith('/')) { overrideUrl.chop(1); }
+ if (!overrideUrl.isEmpty()) {
+ if (overrideUrl.endsWith('/')) {
+ overrideUrl.chop(1);
+ }
QString oCUrl = oCSettings->value(QLatin1String(urlC)).toString();
- if (oCUrl.endsWith('/')) { oCUrl.chop(1); }
+ if (oCUrl.endsWith('/')) {
+ oCUrl.chop(1);
+ }
// in case the urls are equal reset the settings object to read from
// the ownCloud settings object
qCInfo(lcAccountManager) << "Migrate oC config if " << oCUrl << " == " << overrideUrl << ":"
- << (oCUrl == overrideUrl ? "Yes" : "No");
- if( oCUrl == overrideUrl ) {
+ << (oCUrl == overrideUrl ? "Yes" : "No");
+ if (oCUrl == overrideUrl) {
settings = std::move(oCSettings);
}
}
qCInfo(lcAccountManager) << "Saved all account settings, status:" << settings->status();
}
-void AccountManager::saveAccount(Account* a)
+void AccountManager::saveAccount(Account *a)
{
qCInfo(lcAccountManager) << "Saving account" << a->url().toString();
auto settings = Utility::settingsWithGroup(QLatin1String(accountsC));
qCInfo(lcAccountManager) << "Saved account settings, status:" << settings->status();
}
-void AccountManager::saveAccountState(AccountState* a)
+void AccountManager::saveAccountState(AccountState *a)
{
qCInfo(lcAccountManager) << "Saving account state" << a->account()->url().toString();
auto settings = Utility::settingsWithGroup(QLatin1String(accountsC));
qCInfo(lcAccountManager) << "Saved account state settings, status:" << settings->status();
}
-void AccountManager::saveAccountHelper(Account* acc, QSettings& settings, bool saveCredentials)
+void AccountManager::saveAccountHelper(Account *acc, QSettings &settings, bool saveCredentials)
{
settings.setValue(QLatin1String(urlC), acc->_url.toString());
settings.setValue(QLatin1String(serverVersionC), acc->_serverVersion);
// re-persisting them)
acc->_credentials->persist();
}
- Q_FOREACH(QString key, acc->_settingsMap.keys()) {
+ Q_FOREACH (QString key, acc->_settingsMap.keys()) {
settings.setValue(key, acc->_settingsMap.value(key));
}
settings.setValue(QLatin1String(authTypeC), acc->_credentials->authType());
settings.beginGroup(QLatin1String("General"));
qCInfo(lcAccountManager) << "Saving " << acc->approvedCerts().count() << " unknown certs.";
QByteArray certs;
- Q_FOREACH( const QSslCertificate& cert, acc->approvedCerts() ) {
+ Q_FOREACH (const QSslCertificate &cert, acc->approvedCerts()) {
certs += cert.toPem() + '\n';
}
if (!certs.isEmpty()) {
- settings.setValue( QLatin1String(caCertsKeyC), certs );
+ settings.setValue(QLatin1String(caCertsKeyC), certs);
}
settings.endGroup();
// Save cookies.
if (acc->_am) {
- CookieJar* jar = qobject_cast<CookieJar*>(acc->_am->cookieJar());
+ CookieJar *jar = qobject_cast<CookieJar *>(acc->_am->cookieJar());
if (jar) {
qCInfo(lcAccountManager) << "Saving cookies." << acc->cookieJarPath();
jar->save(acc->cookieJarPath());
}
}
-AccountPtr AccountManager::loadAccountHelper(QSettings& settings)
+AccountPtr AccountManager::loadAccountHelper(QSettings &settings)
{
auto urlConfig = settings.value(QLatin1String(urlC));
if (!urlConfig.isValid()) {
QString overrideUrl = Theme::instance()->overrideServerUrl();
QString forceAuth = Theme::instance()->forceConfigAuthType();
- if(!forceAuth.isEmpty() && !overrideUrl.isEmpty() ) {
+ if (!forceAuth.isEmpty() && !overrideUrl.isEmpty()) {
// If forceAuth is set, this might also mean the overrideURL has changed.
// See enterprise issues #1126
acc->setUrl(overrideUrl);
// We want to only restore settings for that auth type and the user value
acc->_settingsMap.insert(QLatin1String(userC), settings.value(userC));
QString authTypePrefix = authType + "_";
- Q_FOREACH(QString key, settings.childKeys()) {
+ Q_FOREACH (QString key, settings.childKeys()) {
if (!key.startsWith(authTypePrefix))
continue;
acc->_settingsMap.insert(key, settings.value(key));
return acc;
}
-AccountStatePtr AccountManager::account(const QString& name)
+AccountStatePtr AccountManager::account(const QString &name)
{
- foreach (const auto& acc, _accounts) {
+ foreach (const auto &acc, _accounts) {
if (acc->account()->displayName() == name) {
return acc;
}
return AccountStatePtr();
}
-AccountState *AccountManager::addAccount(const AccountPtr& newAccount)
+AccountState *AccountManager::addAccount(const AccountPtr &newAccount)
{
auto id = newAccount->id();
if (id.isEmpty() || !isAccountIdAvailable(id)) {
return newAccountState;
}
-void AccountManager::deleteAccount(AccountState* account)
+void AccountManager::deleteAccount(AccountState *account)
{
auto it = std::find(_accounts.begin(), _accounts.end(), account);
- if (it == _accounts.end()) { return; }
+ if (it == _accounts.end()) {
+ return;
+ }
auto copy = *it; // keep a reference to the shared pointer so it does not delete it just yet
_accounts.erase(it);
{
AccountPtr acc = Account::create();
acc->setSslErrorHandler(new SslDialogErrorHandler);
- connect(acc.data(), SIGNAL(proxyAuthenticationRequired(QNetworkProxy, QAuthenticator*)),
- ProxyAuthHandler::instance(), SLOT(handleProxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)));
+ connect(acc.data(), SIGNAL(proxyAuthenticationRequired(QNetworkProxy, QAuthenticator *)),
+ ProxyAuthHandler::instance(), SLOT(handleProxyAuthenticationRequired(QNetworkProxy, QAuthenticator *)));
return acc;
}
}
}
-bool AccountManager::isAccountIdAvailable(const QString& id) const
+bool AccountManager::isAccountIdAvailable(const QString &id) const
{
- foreach (const auto& acc, _accounts) {
+ foreach (const auto &acc, _accounts) {
if (acc->account()->id() == id) {
return false;
}
}
}
-void AccountManager::addAccountState(AccountState* accountState)
+void AccountManager::addAccountState(AccountState *accountState)
{
QObject::connect(accountState->account().data(),
- SIGNAL(wantsAccountSaved(Account*)),
- SLOT(saveAccount(Account*)));
+ SIGNAL(wantsAccountSaved(Account *)),
+ SLOT(saveAccount(Account *)));
AccountStatePtr ptr(accountState);
_accounts << ptr;
emit accountAdded(accountState);
}
-
}
@brief The AccountManager class
@ingroup gui
*/
-class AccountManager : public QObject {
+class AccountManager : public QObject
+{
Q_OBJECT
public:
static AccountManager *instance();
/**
* Return the account state pointer for an account identified by its display name
*/
- AccountStatePtr account(const QString& name);
+ AccountStatePtr account(const QString &name);
/**
* Delete the AccountState
private:
// saving and loading Account to settings
- void saveAccountHelper(Account* account, QSettings& settings, bool saveCredentials = true);
- AccountPtr loadAccountHelper(QSettings& settings);
+ void saveAccountHelper(Account *account, QSettings &settings, bool saveCredentials = true);
+ AccountPtr loadAccountHelper(QSettings &settings);
bool restoreFromLegacySettings();
- bool isAccountIdAvailable(const QString& id) const;
+ bool isAccountIdAvailable(const QString &id) const;
QString generateFreeAccountId() const;
// Adds an account to the tracked list, emitting accountAdded()
- void addAccountState(AccountState* accountState);
+ void addAccountState(AccountState *accountState);
public slots:
/// Saves account data, not including the credentials
- void saveAccount(Account* a);
+ void saveAccount(Account *a);
/// Saves account state data, not including the account
- void saveAccountState(AccountState* a);
+ void saveAccountState(AccountState *a);
Q_SIGNALS:
AccountManager() {}
QList<AccountStatePtr> _accounts;
};
-
}
Q_LOGGING_CATEGORY(lcAccountSettings, "gui.account.settings", QtInfoMsg)
static const char progressBarStyleC[] =
- "QProgressBar {"
- "border: 1px solid grey;"
- "border-radius: 5px;"
- "text-align: center;"
- "}"
- "QProgressBar::chunk {"
- "background-color: %1; width: 1px;"
- "}";
-
-AccountSettings::AccountSettings(AccountState *accountState, QWidget *parent) :
- QWidget(parent),
- ui(new Ui::AccountSettings),
- _wasDisabledBefore(false),
- _accountState(accountState),
- _quotaInfo(accountState)
+ "QProgressBar {"
+ "border: 1px solid grey;"
+ "border-radius: 5px;"
+ "text-align: center;"
+ "}"
+ "QProgressBar::chunk {"
+ "background-color: %1; width: 1px;"
+ "}";
+
+AccountSettings::AccountSettings(AccountState *accountState, QWidget *parent)
+ : QWidget(parent)
+ , ui(new Ui::AccountSettings)
+ , _wasDisabledBefore(false)
+ , _accountState(accountState)
+ , _quotaInfo(accountState)
{
ui->setupUi(this);
delegate->setParent(this);
ui->_folderList->header()->hide();
- ui->_folderList->setItemDelegate( delegate );
- ui->_folderList->setModel( _model );
+ ui->_folderList->setItemDelegate(delegate);
+ ui->_folderList->setModel(_model);
#if defined(Q_OS_MAC)
- ui->_folderList->setMinimumWidth( 400 );
+ ui->_folderList->setMinimumWidth(400);
#else
- ui->_folderList->setMinimumWidth( 300 );
+ ui->_folderList->setMinimumWidth(300);
#endif
new ToolTipUpdater(ui->_folderList);
createAccountToolbox();
- connect(AccountManager::instance(), SIGNAL(accountAdded(AccountState*)),
- SLOT(slotAccountAdded(AccountState*)));
+ connect(AccountManager::instance(), SIGNAL(accountAdded(AccountState *)),
+ SLOT(slotAccountAdded(AccountState *)));
connect(ui->_folderList, SIGNAL(customContextMenuRequested(QPoint)),
- this, SLOT(slotCustomContextMenuRequested(QPoint)));
+ this, SLOT(slotCustomContextMenuRequested(QPoint)));
connect(ui->_folderList, SIGNAL(clicked(const QModelIndex &)),
- this, SLOT(slotFolderListClicked(const QModelIndex&)));
- connect(ui->_folderList, SIGNAL(expanded(QModelIndex)) , this, SLOT(refreshSelectiveSyncStatus()));
- connect(ui->_folderList, SIGNAL(collapsed(QModelIndex)) , this, SLOT(refreshSelectiveSyncStatus()));
+ this, SLOT(slotFolderListClicked(const QModelIndex &)));
+ connect(ui->_folderList, SIGNAL(expanded(QModelIndex)), this, SLOT(refreshSelectiveSyncStatus()));
+ connect(ui->_folderList, SIGNAL(collapsed(QModelIndex)), this, SLOT(refreshSelectiveSyncStatus()));
connect(ui->selectiveSyncNotification, SIGNAL(linkActivated(QString)),
- this, SLOT(slotLinkActivated(QString)));
+ this, SLOT(slotLinkActivated(QString)));
connect(_model, SIGNAL(suggestExpand(QModelIndex)), ui->_folderList, SLOT(expand(QModelIndex)));
connect(_model, SIGNAL(dirtyChanged()), this, SLOT(refreshSelectiveSyncStatus()));
refreshSelectiveSyncStatus();
- connect(_model, SIGNAL(rowsInserted(QModelIndex,int,int)),
- this, SLOT(refreshSelectiveSyncStatus()));
+ connect(_model, SIGNAL(rowsInserted(QModelIndex, int, int)),
+ this, SLOT(refreshSelectiveSyncStatus()));
QAction *syncNowAction = new QAction(this);
syncNowAction->setShortcut(QKeySequence(Qt::Key_F6));
addAction(syncNowWithRemoteDiscovery);
-
connect(ui->selectiveSyncApply, SIGNAL(clicked()), _model, SLOT(slotApplySelectiveSync()));
connect(ui->selectiveSyncCancel, SIGNAL(clicked()), _model, SLOT(resetFolders()));
connect(ui->bigFolderApply, SIGNAL(clicked(bool)), _model, SLOT(slotApplySelectiveSync()));
connect(_accountState, SIGNAL(stateChanged(int)), SLOT(slotAccountStateChanged(int)));
slotAccountStateChanged(_accountState->state());
- connect( &_quotaInfo, SIGNAL(quotaUpdated(qint64,qint64)),
- this, SLOT(slotUpdateQuota(qint64,qint64)));
-
+ connect(&_quotaInfo, SIGNAL(quotaUpdated(qint64, qint64)),
+ this, SLOT(slotUpdateQuota(qint64, qint64)));
}
QAction *action = new QAction(tr("Remove"), this);
menu->addAction(action);
- connect( action, SIGNAL(triggered(bool)), SLOT(slotDeleteAccount()));
+ connect(action, SIGNAL(triggered(bool)), SLOT(slotDeleteAccount()));
ui->_accountToolbox->setText(tr("Account") + QLatin1Char(' '));
ui->_accountToolbox->setMenu(menu);
QString AccountSettings::selectedFolderAlias() const
{
QModelIndex selected = ui->_folderList->selectionModel()->currentIndex();
- if( !selected.isValid() )
+ if (!selected.isValid())
return "";
- return _model->data( selected, FolderStatusDelegate::FolderAliasRole ).toString();
+ return _model->data(selected, FolderStatusDelegate::FolderAliasRole).toString();
}
void AccountSettings::slotOpenAccountWizard()
{
if (
#if QT_VERSION > QT_VERSION_CHECK(5, 0, 0)
- qgetenv("QT_QPA_PLATFORMTHEME") == "appmenu-qt5" ||
- // We can't call isSystemTrayAvailable with appmenu-qt5 because it breaks the systemtray
- // (issue #4693, #4944)
+ qgetenv("QT_QPA_PLATFORMTHEME") == "appmenu-qt5" ||
+// We can't call isSystemTrayAvailable with appmenu-qt5 because it breaks the systemtray
+// (issue #4693, #4944)
#endif
- QSystemTrayIcon::isSystemTrayAvailable()) {
+ QSystemTrayIcon::isSystemTrayAvailable()) {
topLevelWidget()->close();
}
#ifdef Q_OS_MAC
qCDebug(lcAccountSettings) << parent() << topLevelWidget();
- SettingsDialogMac *sd = qobject_cast<SettingsDialogMac*>(topLevelWidget());
+ SettingsDialogMac *sd = qobject_cast<SettingsDialogMac *>(topLevelWidget());
if (sd) {
sd->showActivityPage();
QAction *ac = menu->addAction(tr("Open folder"));
connect(ac, SIGNAL(triggered(bool)), this, SLOT(slotOpenCurrentLocalSubFolder()));
- QString fileName = _model->data( index, FolderStatusDelegate::FolderPathRole ).toString();
+ QString fileName = _model->data(index, FolderStatusDelegate::FolderPathRole).toString();
if (!QFile::exists(fileName)) {
ac->setEnabled(false);
}
}
tv->setCurrentIndex(index);
- QString alias = _model->data( index, FolderStatusDelegate::FolderAliasRole ).toString();
- bool folderPaused = _model->data( index, FolderStatusDelegate::FolderSyncPaused).toBool();
- bool folderConnected = _model->data( index, FolderStatusDelegate::FolderAccountConnected ).toBool();
+ QString alias = _model->data(index, FolderStatusDelegate::FolderAliasRole).toString();
+ bool folderPaused = _model->data(index, FolderStatusDelegate::FolderSyncPaused).toBool();
+ bool folderConnected = _model->data(index, FolderStatusDelegate::FolderAccountConnected).toBool();
auto folderMan = FolderMan::instance();
QMenu *menu = new QMenu(tv);
menu->exec(tv->mapToGlobal(pos));
}
-void AccountSettings::slotFolderListClicked(const QModelIndex& indx)
+void AccountSettings::slotFolderListClicked(const QModelIndex &indx)
{
if (indx.data(FolderStatusDelegate::AddButton).toBool()) {
// "Add Folder Sync Connection"
slotAddFolder();
} else {
QToolTip::showText(
- QCursor::pos(),
- _model->data(indx, Qt::ToolTipRole).toString(),
- this);
+ QCursor::pos(),
+ _model->data(indx, Qt::ToolTipRole).toString(),
+ this);
}
return;
}
}
// Expand root items on single click
- if(_accountState && _accountState->state() == AccountState::Connected ) {
- bool expanded = ! (ui->_folderList->isExpanded(indx));
+ if (_accountState && _accountState->state() == AccountState::Connected) {
+ bool expanded = !(ui->_folderList->isExpanded(indx));
ui->_folderList->setExpanded(indx, expanded);
}
}
void AccountSettings::slotFolderWizardAccepted()
{
- FolderWizard *folderWizard = qobject_cast<FolderWizard*>(sender());
+ FolderWizard *folderWizard = qobject_cast<FolderWizard *>(sender());
FolderMan *folderMan = FolderMan::instance();
qCInfo(lcAccountSettings) << "Folder wizard completed";
FolderDefinition definition;
- definition.localPath = FolderDefinition::prepareLocalPath(
- folderWizard->field(QLatin1String("sourceFolder")).toString());
- definition.targetPath = FolderDefinition::prepareTargetPath(
- folderWizard->property("targetPath").toString());
+ definition.localPath = FolderDefinition::prepareLocalPath(
+ folderWizard->field(QLatin1String("sourceFolder")).toString());
+ definition.targetPath = FolderDefinition::prepareTargetPath(
+ folderWizard->property("targetPath").toString());
{
QDir dir(definition.localPath);
qCInfo(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>.")
- .arg(QDir::toNativeSeparators(definition.localPath)));
+ tr("<p>Could not create local folder <i>%1</i>.")
+ .arg(QDir::toNativeSeparators(definition.localPath)));
return;
}
}
folderMan->setSyncEnabled(true);
Folder *f = folderMan->addFolder(_accountState, definition);
- if( f ) {
+ if (f) {
f->journalDb()->setSelectiveSyncList(SyncJournalDb::SelectiveSyncBlackList, selectiveSyncBlackList);
// The user already accepted the selective sync dialog. everything is in the white list
f->journalDb()->setSelectiveSyncList(SyncJournalDb::SelectiveSyncWhiteList,
- QStringList() << QLatin1String("/"));
+ QStringList() << QLatin1String("/"));
folderMan->scheduleAllFolders();
emit folderChanged();
}
FolderMan *folderMan = FolderMan::instance();
auto folder = folderMan->folder(selectedFolderAlias());
QModelIndex selected = ui->_folderList->selectionModel()->currentIndex();
- if( selected.isValid() && folder ) {
+ if (selected.isValid() && folder) {
int row = selected.row();
qCInfo(lcAccountSettings) << "Remove Folder alias " << folder->alias();
QString shortGuiLocalPath = folder->shortGuiLocalPath();
QMessageBox messageBox(QMessageBox::Question,
- tr("Confirm Folder Sync Connection Removal"),
- tr("<p>Do you really want to stop syncing the folder <i>%1</i>?</p>"
- "<p><b>Note:</b> This will <b>not</b> delete any files.</p>").arg(shortGuiLocalPath),
- QMessageBox::NoButton,
- this);
- QPushButton* yesButton =
- messageBox.addButton(tr("Remove Folder Sync Connection"), QMessageBox::YesRole);
+ tr("Confirm Folder Sync Connection Removal"),
+ tr("<p>Do you really want to stop syncing the folder <i>%1</i>?</p>"
+ "<p><b>Note:</b> This will <b>not</b> delete any files.</p>")
+ .arg(shortGuiLocalPath),
+ QMessageBox::NoButton,
+ this);
+ QPushButton *yesButton =
+ messageBox.addButton(tr("Remove Folder Sync Connection"), QMessageBox::YesRole);
messageBox.addButton(tr("Cancel"), QMessageBox::NoRole);
messageBox.exec();
return;
}
- folderMan->removeFolder( folder );
+ folderMan->removeFolder(folder);
_model->removeRow(row);
// single folder fix to show add-button and hide remove-button
void AccountSettings::slotOpenCurrentFolder()
{
auto alias = selectedFolderAlias();
- if( !alias.isEmpty() ) {
+ if (!alias.isEmpty()) {
emit openFolderAlias(alias);
}
}
void AccountSettings::slotOpenCurrentLocalSubFolder()
{
QModelIndex selected = ui->_folderList->selectionModel()->currentIndex();
- if( !selected.isValid() || _model->classify(selected) != FolderStatusModel::SubFolder)
+ if (!selected.isValid() || _model->classify(selected) != FolderStatusModel::SubFolder)
return;
- QString fileName = _model->data( selected, FolderStatusDelegate::FolderPathRole ).toString();
+ QString fileName = _model->data(selected, FolderStatusDelegate::FolderPathRole).toString();
QUrl url = QUrl::fromLocalFile(fileName);
QDesktopServices::openUrl(url);
}
-void AccountSettings::showConnectionLabel( const QString& message, QStringList errors )
+void AccountSettings::showConnectionLabel(const QString &message, QStringList errors)
{
const QString errStyle = QLatin1String("color:#ffffff; background-color:#bb4d4d;padding:5px;"
"border-width: 1px; border-style: solid; border-color: #aaaaaa;"
"border-radius:5px;");
- if( errors.isEmpty() ) {
- ui->connectLabel->setText( message );
+ if (errors.isEmpty()) {
+ ui->connectLabel->setText(message);
ui->connectLabel->setToolTip(QString());
ui->connectLabel->setStyleSheet(QString());
} else {
errors.prepend(message);
const QString msg = errors.join(QLatin1String("\n"));
qCDebug(lcAccountSettings) << msg;
- ui->connectLabel->setText( msg );
+ ui->connectLabel->setText(msg);
ui->connectLabel->setToolTip(QString());
ui->connectLabel->setStyleSheet(errStyle);
}
{
auto alias = selectedFolderAlias();
- if( !alias.isEmpty() ) {
+ if (!alias.isEmpty()) {
FolderMan *folderMan = FolderMan::instance();
qCInfo(lcAccountSettings) << "Application: enable folder with alias " << alias;
bool currentlyPaused = false;
// this sets the folder status to disabled but does not interrupt it.
- Folder *f = folderMan->folder( alias );
+ Folder *f = folderMan->folder(alias);
if (!f) {
return;
}
currentlyPaused = f->syncPaused();
- if( ! currentlyPaused ) {
+ if (!currentlyPaused) {
// check if a sync is still running and if so, ask if we should terminate.
- if( f->isBusy() ) { // its still running
+ if (f->isBusy()) { // its still running
#if defined(Q_OS_MAC)
QWidget *parent = this;
Qt::WindowFlags flags = Qt::Sheet;
Qt::WindowFlags flags = Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint; // default flags
#endif
QMessageBox msgbox(QMessageBox::Question, tr("Sync Running"),
- tr("The syncing operation is running.<br/>Do you want to terminate it?"),
- QMessageBox::Yes | QMessageBox::No, parent, flags);
+ tr("The syncing operation is running.<br/>Do you want to terminate it?"),
+ QMessageBox::Yes | QMessageBox::No, parent, flags);
msgbox.setDefaultButton(QMessageBox::Yes);
int reply = msgbox.exec();
- if ( reply == QMessageBox::Yes )
+ if (reply == QMessageBox::Yes)
terminate = true;
else
return; // do nothing
// message box can return at any time while the thread keeps running,
// so better check again after the user has responded.
- if ( f->isBusy() && terminate ) {
+ if (f->isBusy() && terminate) {
f->slotTerminateSync();
}
f->setSyncPaused(!currentlyPaused);
// keep state for the icon setting.
- if( currentlyPaused ) _wasDisabledBefore = true;
+ if (currentlyPaused)
+ _wasDisabledBefore = true;
- _model->slotUpdateFolderState (f);
+ _model->slotUpdateFolderState(f);
}
}
FolderMan *folderMan = FolderMan::instance();
if (auto selectedFolder = folderMan->folder(selectedFolderAlias())) {
// Terminate and reschedule any running sync
- if (Folder* current = folderMan->currentSyncFolder()) {
+ if (Folder *current = folderMan->currentSyncFolder()) {
folderMan->terminateSyncProcess();
folderMan->scheduleFolder(current);
}
void AccountSettings::slotOpenOC()
{
- if( _OCUrl.isValid() )
- QDesktopServices::openUrl( _OCUrl );
+ if (_OCUrl.isValid())
+ QDesktopServices::openUrl(_OCUrl);
}
void AccountSettings::slotUpdateQuota(qint64 total, qint64 used)
{
- if( total > 0 ) {
+ if (total > 0) {
ui->quotaProgressBar->setVisible(true);
ui->quotaProgressBar->setEnabled(true);
// workaround the label only accepting ints (which may be only 32 bit wide)
- const double percent = used/(double)total*100;
+ const double percent = used / (double)total * 100;
const int percentInt = qMin(qRound(percent), 100);
ui->quotaProgressBar->setValue(percentInt);
QString usedStr = Utility::octetsToString(used);
QString server = QString::fromLatin1("<a href=\"%1\">%2</a>")
.arg(Utility::escape(account->url().toString()),
- Utility::escape(safeUrl.toString()));
+ Utility::escape(safeUrl.toString()));
QString serverWithUser = server;
if (AbstractCredentials *cred = account->credentials()) {
serverWithUser = tr("%1 as <i>%2</i>").arg(server, Utility::escape(cred->user()));
if (account->serverVersionUnsupported()) {
errors << tr("The server version %1 is old and unsupported! Proceed at your own risk.").arg(account->serverVersion());
}
- showConnectionLabel( tr("Connected to %1.").arg(serverWithUser), errors );
+ showConnectionLabel(tr("Connected to %1.").arg(serverWithUser), errors);
} else if (state == AccountState::ServiceUnavailable) {
- showConnectionLabel( tr("Server %1 is temporarily unavailable.").arg(server) );
+ showConnectionLabel(tr("Server %1 is temporarily unavailable.").arg(server));
} else if (state == AccountState::MaintenanceMode) {
- showConnectionLabel( tr("Server %1 is currently in maintenance mode.").arg(server) );
+ showConnectionLabel(tr("Server %1 is currently in maintenance mode.").arg(server));
} else if (state == AccountState::SignedOut) {
- showConnectionLabel( tr("Signed out from %1.").arg(serverWithUser) );
+ showConnectionLabel(tr("Signed out from %1.").arg(serverWithUser));
} else {
showConnectionLabel(tr("No connection to %1 at %2.")
.arg(Utility::escape(Theme::instance()->appNameGUI()), server),
- _accountState->connectionErrors());
+ _accountState->connectionErrors());
}
} else {
// ownCloud is not yet configured.
}
/* Allow to expand the item if the account is connected. */
- ui->_folderList->setItemsExpandable( state == AccountState::Connected );
+ ui->_folderList->setItemsExpandable(state == AccountState::Connected);
/* check if there are expanded root items, if so, close them, if the state is different from being Connected. */
- if( state != AccountState::Connected ) {
+ if (state != AccountState::Connected) {
int i;
for (i = 0; i < _model->rowCount(); ++i) {
if (ui->_folderList->isExpanded(_model->index(i)))
}
}
/* set the correct label for the Account toolbox button */
- if( _accountState ) {
- if( _accountState->isSignedOut() ) {
+ if (_accountState) {
+ if (_accountState->isSignedOut()) {
_toggleSignInOutAction->setText(tr("Log in"));
} else {
_toggleSignInOutAction->setText(tr("Log out"));
}
}
-void AccountSettings::slotLinkActivated(const QString& link)
+void AccountSettings::slotLinkActivated(const QString &link)
{
// Parse folder alias and filename from the link, calculate the index
// and select it if it exists.
const QStringList li = link.split(QLatin1String("?folder="));
- if( li.count() > 1) {
+ if (li.count() > 1) {
QString myFolder = li[0];
const QString alias = li[1];
- if(myFolder.endsWith(QLatin1Char('/'))) myFolder.chop(1);
+ if (myFolder.endsWith(QLatin1Char('/')))
+ myFolder.chop(1);
// Make sure the folder itself is expanded
Folder *f = FolderMan::instance()->folder(alias);
QModelIndex folderIndx = _model->indexForPath(f, QString());
- if( !ui->_folderList->isExpanded(folderIndx)) {
+ if (!ui->_folderList->isExpanded(folderIndx)) {
ui->_folderList->setExpanded(folderIndx, true);
}
QModelIndex indx = _model->indexForPath(f, myFolder);
- if( indx.isValid() ) {
+ if (indx.isValid()) {
// make sure all the parents are expanded
for (auto i = indx.parent(); i.isValid(); i = i.parent()) {
- if( !ui->_folderList->isExpanded(i)) {
+ if (!ui->_folderList->isExpanded(i)) {
ui->_folderList->setExpanded(i, true);
}
}
}
bool ok;
- auto undecidedList = folder->journalDb()->getSelectiveSyncList(SyncJournalDb::SelectiveSyncUndecidedList, &ok);
+ auto undecidedList = folder->journalDb()->getSelectiveSyncList(SyncJournalDb::SelectiveSyncUndecidedList, &ok);
QString p;
- foreach(const auto &it, undecidedList) {
+ foreach (const auto &it, undecidedList) {
// FIXME: add the folder alias in a hoover hint.
// folder->alias() + QLatin1String("/")
- if( cnt++ ) {
+ if (cnt++) {
msg += QLatin1String(", ");
}
QString myFolder = (it);
- if( myFolder.endsWith('/')) {
+ if (myFolder.endsWith('/')) {
myFolder.chop(1);
}
QModelIndex theIndx = _model->indexForPath(folder, myFolder);
- if(theIndx.isValid()) {
+ if (theIndx.isValid()) {
msg += QString::fromLatin1("<a href=\"%1?folder=%2\">%1</a>")
.arg(Utility::escape(myFolder), Utility::escape(folder->alias()));
} else {
} else {
ConfigFile cfg;
QString info = !cfg.confirmExternalStorage()
- ? tr("There are folders that were not synchronized because they are too big: ")
- : !cfg.newBigFolderSizeLimit().first
- ? tr("There are folders that were not synchronized because they are external storages: ")
- : tr("There are folders that were not synchronized because they are too big or external storages: ");
+ ? tr("There are folders that were not synchronized because they are too big: ")
+ : !cfg.newBigFolderSizeLimit().first
+ ? tr("There are folders that were not synchronized because they are external storages: ")
+ : tr("There are folders that were not synchronized because they are too big or external storages: ");
ui->selectiveSyncNotification->setText(info + msg);
ui->selectiveSyncButtons->setVisible(false);
}
}
-void AccountSettings::slotAccountAdded(AccountState*)
+void AccountSettings::slotAccountAdded(AccountState *)
{
// if the theme is limited to single account, the button must hide if
// there is already one account.
int s = AccountManager::instance()->accounts().size();
- if( s > 0 && !Theme::instance()->multiAccount() ) {
+ if (s > 0 && !Theme::instance()->multiAccount()) {
_addAccountAction->setVisible(false);
} else {
_addAccountAction->setVisible(true);
// the QMessageBox should be destroyed before that happens.
{
QMessageBox messageBox(QMessageBox::Question,
- tr("Confirm Account Removal"),
- tr("<p>Do you really want to remove the connection to the account <i>%1</i>?</p>"
- "<p><b>Note:</b> This will <b>not</b> delete any files.</p>")
- .arg(_accountState->account()->displayName()),
- QMessageBox::NoButton,
- this);
- QPushButton* yesButton =
- messageBox.addButton(tr("Remove connection"), QMessageBox::YesRole);
+ tr("Confirm Account Removal"),
+ tr("<p>Do you really want to remove the connection to the account <i>%1</i>?</p>"
+ "<p><b>Note:</b> This will <b>not</b> delete any files.</p>")
+ .arg(_accountState->account()->displayName()),
+ QMessageBox::NoButton,
+ this);
+ QPushButton *yesButton =
+ messageBox.addButton(tr("Remove connection"), QMessageBox::YesRole);
messageBox.addButton(tr("Cancel"), QMessageBox::NoRole);
messageBox.exec();
// .exec() QMessageBox magic above as it recurses into the event loop.
}
-bool AccountSettings::event(QEvent* e)
+bool AccountSettings::event(QEvent *e)
{
if (e->type() == QEvent::Hide || e->type() == QEvent::Show) {
_quotaInfo.setActive(isVisible());
namespace OCC {
namespace Ui {
-class AccountSettings;
+ class AccountSettings;
}
class FolderMan;
signals:
void folderChanged();
- void openFolderAlias( const QString& );
+ void openFolderAlias(const QString &);
public slots:
void slotOpenOC();
- void slotUpdateQuota( qint64,qint64 );
+ void slotUpdateQuota(qint64, qint64);
void slotAccountStateChanged(int state);
- AccountState* accountsState() { return _accountState; }
+ AccountState *accountsState() { return _accountState; }
protected slots:
void slotAddFolder();
void slotOpenAccountWizard();
void slotAccountAdded(AccountState *);
void refreshSelectiveSyncStatus();
- void slotCustomContextMenuRequested(const QPoint&);
- void slotFolderListClicked( const QModelIndex& indx );
+ void slotCustomContextMenuRequested(const QPoint &);
+ void slotFolderListClicked(const QModelIndex &indx);
void doExpand();
void slotLinkActivated(const QString &link);
private:
- void showConnectionLabel(const QString& message,
- QStringList errors = QStringList());
- bool event(QEvent*) Q_DECL_OVERRIDE;
+ void showConnectionLabel(const QString &message,
+ QStringList errors = QStringList());
+ bool event(QEvent *) Q_DECL_OVERRIDE;
void createAccountToolbox();
/// Returns the alias of the selected folder, empty string if none
Ui::AccountSettings *ui;
FolderStatusModel *_model;
- QUrl _OCUrl;
+ QUrl _OCUrl;
bool _wasDisabledBefore;
AccountState *_accountState;
QuotaInfo _quotaInfo;
, _connectionStatus(ConnectionValidator::Undefined)
, _waitingForNewCredentials(false)
{
- qRegisterMetaType<AccountState*>("AccountState*");
+ qRegisterMetaType<AccountState *>("AccountState*");
connect(account.data(), SIGNAL(invalidCredentials()),
- SLOT(slotInvalidCredentials()));
- connect(account.data(), SIGNAL(credentialsFetched(AbstractCredentials*)),
- SLOT(slotCredentialsFetched(AbstractCredentials*)));
- connect(account.data(), SIGNAL(credentialsAsked(AbstractCredentials*)),
- SLOT(slotCredentialsAsked(AbstractCredentials*)));
+ SLOT(slotInvalidCredentials()));
+ connect(account.data(), SIGNAL(credentialsFetched(AbstractCredentials *)),
+ SLOT(slotCredentialsFetched(AbstractCredentials *)));
+ connect(account.data(), SIGNAL(credentialsAsked(AbstractCredentials *)),
+ SLOT(slotCredentialsAsked(AbstractCredentials *)));
_timeSinceLastETagCheck.invalidate();
}
{
}
-AccountState *AccountState::loadFromSettings(AccountPtr account, QSettings& /*settings*/)
+AccountState *AccountState::loadFromSettings(AccountPtr account, QSettings & /*settings*/)
{
auto accountState = new AccountState(account);
return accountState;
}
-void AccountState::writeToSettings(QSettings& /*settings*/)
+void AccountState::writeToSettings(QSettings & /*settings*/)
{
}
{
if (_state != state) {
qCInfo(lcAccountState) << "AccountState state change: "
- << stateString(_state) << "->" << stateString(state);
+ << stateString(_state) << "->" << stateString(state);
State oldState = _state;
_state = state;
QString AccountState::stateString(State state)
{
- switch (state)
- {
+ switch (state) {
case SignedOut:
return tr("Signed out");
case Disconnected:
int polltime = cfg.remotePollInterval();
if (isConnected() && _timeSinceLastETagCheck.isValid()
- && _timeSinceLastETagCheck.elapsed() < polltime) {
- qCDebug(lcAccountState) << account()->displayName() << "The last ETag check succeeded within the last " << polltime/1000 << " secs. No connection check needed!";
+ && _timeSinceLastETagCheck.elapsed() < polltime) {
+ qCDebug(lcAccountState) << account()->displayName() << "The last ETag check succeeded within the last " << polltime / 1000 << " secs. No connection check needed!";
return;
}
- ConnectionValidator * conValidator = new ConnectionValidator(account());
+ ConnectionValidator *conValidator = new ConnectionValidator(account());
_connectionValidator = conValidator;
- connect(conValidator, SIGNAL(connectionResult(ConnectionValidator::Status,QStringList)),
- SLOT(slotConnectionValidatorResult(ConnectionValidator::Status,QStringList)));
+ connect(conValidator, SIGNAL(connectionResult(ConnectionValidator::Status, QStringList)),
+ SLOT(slotConnectionValidatorResult(ConnectionValidator::Status, QStringList)));
if (isConnected()) {
// Use a small authed propfind as a minimal ping when we're
// already connected.
} else {
// Check the server and then the auth.
-// Let's try this for all OS and see if it fixes the Qt issues we have on Linux #4720 #3888 #4051
-//#ifdef Q_OS_WIN
+ // Let's try this for all OS and see if it fixes the Qt issues we have on Linux #4720 #3888 #4051
+ //#ifdef Q_OS_WIN
// There seems to be a bug in Qt on Windows where QNAM sometimes stops
// working correctly after the computer woke up from sleep. See #2895 #2899
// and #2973.
// If we don't reset the ssl config a second CheckServerJob can produce a
// ssl config that does not have a sensible certificate chain.
account()->setSslConfiguration(QSslConfiguration());
-//#endif
+ //#endif
conValidator->checkServerAndAuth();
}
}
-void AccountState::slotConnectionValidatorResult(ConnectionValidator::Status status, const QStringList& errors)
+void AccountState::slotConnectionValidatorResult(ConnectionValidator::Status status, const QStringList &errors)
{
if (isSignedOut()) {
qCWarning(lcAccountState) << "Signed out, ignoring" << connectionStatusString(status) << _account->url().toString();
if (_connectionStatus != status) {
qCInfo(lcAccountState) << "AccountState connection status change: "
- << connectionStatusString(_connectionStatus) << "->"
- << connectionStatusString(status);
+ << connectionStatusString(_connectionStatus) << "->"
+ << connectionStatusString(status);
_connectionStatus = status;
}
_connectionErrors = errors;
- switch (status)
- {
+ switch (status) {
case ConnectionValidator::Connected:
if (_state != Connected) {
setState(Connected);
_waitingForNewCredentials = true;
}
-void AccountState::slotCredentialsFetched(AbstractCredentials* credentials)
+void AccountState::slotCredentialsFetched(AbstractCredentials *credentials)
{
if (!credentials->ready()) {
// No exiting credentials found in the keychain
checkConnectivity();
}
-void AccountState::slotCredentialsAsked(AbstractCredentials* credentials)
+void AccountState::slotCredentialsAsked(AbstractCredentials *credentials)
{
_waitingForNewCredentials = false;
}
-
} // namespace OCC
* @brief Extra info about an ownCloud server account.
* @ingroup gui
*/
-class AccountState : public QObject, public QSharedData {
+class AccountState : public QObject, public QSharedData
+{
Q_OBJECT
public:
enum State {
*
* Use from AccountManager with a prepared QSettings object only.
*/
- static AccountState* loadFromSettings(AccountPtr account, QSettings& settings);
+ static AccountState *loadFromSettings(AccountPtr account, QSettings &settings);
/** Writes account state information to settings.
*
* It does not write the Account data.
*/
- void writeToSettings(QSettings& settings);
+ void writeToSettings(QSettings &settings);
AccountPtr account() const;
void isConnectedChanged();
protected Q_SLOTS:
- void slotConnectionValidatorResult(ConnectionValidator::Status status, const QStringList& errors);
+ void slotConnectionValidatorResult(ConnectionValidator::Status status, const QStringList &errors);
void slotInvalidCredentials();
- void slotCredentialsFetched(AbstractCredentials* creds);
- void slotCredentialsAsked(AbstractCredentials* creds);
+ void slotCredentialsFetched(AbstractCredentials *creds);
+ void slotCredentialsAsked(AbstractCredentials *creds);
private:
AccountPtr _account;
QElapsedTimer _timeSinceLastETagCheck;
QPointer<ConnectionValidator> _connectionValidator;
};
-
}
-Q_DECLARE_METATYPE(OCC::AccountState*)
+Q_DECLARE_METATYPE(OCC::AccountState *)
Q_DECLARE_METATYPE(OCC::AccountStatePtr)
#endif //ACCOUNTINFO_H
#include "activitydata.h"
-namespace OCC
-{
+namespace OCC {
-bool operator<( const Activity& rhs, const Activity& lhs ) {
+bool operator<(const Activity &rhs, const Activity &lhs)
+{
return rhs._dateTime.toMSecsSinceEpoch() > lhs._dateTime.toMSecsSinceEpoch();
}
-bool operator==( const Activity& rhs, const Activity& lhs ) {
- return (rhs._type == lhs._type && rhs._id== lhs._id && rhs._accName == lhs._accName);
+bool operator==(const Activity &rhs, const Activity &lhs)
+{
+ return (rhs._type == lhs._type && rhs._id == lhs._id && rhs._accName == lhs._accName);
}
-Activity::Identifier Activity::ident() const {
- return Identifier( _id, _accName );
+Activity::Identifier Activity::ident() const
+{
+ return Identifier(_id, _accName);
}
-
-
}
class ActivityLink
{
public:
- QString _label;
- QString _link;
+ QString _label;
+ QString _link;
QByteArray _verb;
- bool _isPrimary;
+ bool _isPrimary;
};
/* ==================================================================== */
NotificationType
};
- Type _type;
+ Type _type;
qlonglong _id;
- QString _subject;
- QString _message;
- QString _file;
- QUrl _link;
+ QString _subject;
+ QString _message;
+ QString _file;
+ QUrl _link;
QDateTime _dateTime;
- QString _accName;
+ QString _accName;
- QVector <ActivityLink> _links;
+ QVector<ActivityLink> _links;
/**
* @brief Sort operator to sort the list youngest first.
* @param val
Identifier ident() const;
};
-bool operator==( const Activity& rhs, const Activity& lhs );
-bool operator<( const Activity& rhs, const Activity& lhs );
+bool operator==(const Activity &rhs, const Activity &lhs);
+bool operator<(const Activity &rhs, const Activity &lhs);
/* ==================================================================== */
/**
*/
typedef QList<Activity> ActivityList;
-
-
}
#endif // ACTIVITYDATA_H
int ActivityItemDelegate::iconHeight()
{
- if( _iconHeight == 0 ) {
+ if (_iconHeight == 0) {
QStyleOptionViewItem option;
QFont font = option.font;
int ActivityItemDelegate::rowHeight()
{
- if( _margin == 0 ) {
- QStyleOptionViewItem opt;
+ if (_margin == 0) {
+ QStyleOptionViewItem opt;
- QFont f = opt.font;
- QFontMetrics fm(f);
+ QFont f = opt.font;
+ QFontMetrics fm(f);
- _margin = fm.height()/4;
+ _margin = fm.height() / 4;
}
return iconHeight() + 2 * _margin;
}
-QSize ActivityItemDelegate::sizeHint(const QStyleOptionViewItem & option ,
- const QModelIndex & /* index */) const
+QSize ActivityItemDelegate::sizeHint(const QStyleOptionViewItem &option,
+ const QModelIndex & /* index */) const
{
QFont font = option.font;
- return QSize( 0, rowHeight() );
+ return QSize(0, rowHeight());
}
void ActivityItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
- const QModelIndex &index) const
+ const QModelIndex &index) const
{
- QStyledItemDelegate::paint(painter,option,index);
+ QStyledItemDelegate::paint(painter, option, index);
QFont font = option.font;
- QFontMetrics fm( font );
- int margin = fm.height()/4;
+ QFontMetrics fm(font);
+ int margin = fm.height() / 4;
painter->save();
- QIcon actionIcon = qvariant_cast<QIcon>(index.data(ActionIconRole));
- QIcon userIcon = qvariant_cast<QIcon>(index.data(UserIconRole));
- QString actionText = qvariant_cast<QString>(index.data(ActionTextRole));
- QString pathText = qvariant_cast<QString>(index.data(PathRole));
+ QIcon actionIcon = qvariant_cast<QIcon>(index.data(ActionIconRole));
+ QIcon userIcon = qvariant_cast<QIcon>(index.data(UserIconRole));
+ QString actionText = qvariant_cast<QString>(index.data(ActionTextRole));
+ QString pathText = qvariant_cast<QString>(index.data(PathRole));
- QString remoteLink = qvariant_cast<QString>(index.data(LinkRole));
- QString timeText = qvariant_cast<QString>(index.data(PointInTimeRole));
- QString accountRole = qvariant_cast<QString>(index.data(AccountRole));
- bool accountOnline = qvariant_cast<bool> (index.data(AccountConnectedRole));
+ QString remoteLink = qvariant_cast<QString>(index.data(LinkRole));
+ QString timeText = qvariant_cast<QString>(index.data(PointInTimeRole));
+ QString accountRole = qvariant_cast<QString>(index.data(AccountRole));
+ bool accountOnline = qvariant_cast<bool>(index.data(AccountConnectedRole));
QRect actionIconRect = option.rect;
- QRect userIconRect = option.rect;
+ QRect userIconRect = option.rect;
int iconHeight = qRound(fm.height() / 5.0 * 8.0);
int iconWidth = iconHeight;
- actionIconRect.setLeft( option.rect.left() + margin );
- actionIconRect.setWidth( iconWidth );
- actionIconRect.setHeight( iconHeight );
- actionIconRect.setTop( actionIconRect.top() + margin );
- userIconRect.setLeft( actionIconRect.right() + margin );
- userIconRect.setWidth( iconWidth );
- userIconRect.setHeight( iconHeight );
- userIconRect.setTop( actionIconRect.top() );
+ actionIconRect.setLeft(option.rect.left() + margin);
+ actionIconRect.setWidth(iconWidth);
+ actionIconRect.setHeight(iconHeight);
+ actionIconRect.setTop(actionIconRect.top() + margin);
+ userIconRect.setLeft(actionIconRect.right() + margin);
+ userIconRect.setWidth(iconWidth);
+ userIconRect.setHeight(iconHeight);
+ userIconRect.setTop(actionIconRect.top());
- int textTopOffset = qRound( (iconHeight - fm.height())/ 2.0 );
+ int textTopOffset = qRound((iconHeight - fm.height()) / 2.0);
// time rect
QRect timeBox;
int timeBoxWidth = fm.boundingRect(QLatin1String("4 hour(s) ago on longlongdomain.org")).width(); // FIXME.
- timeBox.setTop( actionIconRect.top()+textTopOffset);
- timeBox.setLeft( option.rect.right() - timeBoxWidth- margin );
- timeBox.setWidth( timeBoxWidth);
- timeBox.setHeight( fm.height() );
+ timeBox.setTop(actionIconRect.top() + textTopOffset);
+ timeBox.setLeft(option.rect.right() - timeBoxWidth - margin);
+ timeBox.setWidth(timeBoxWidth);
+ timeBox.setHeight(fm.height());
QRect actionTextBox = timeBox;
- actionTextBox.setLeft( userIconRect.right()+margin );
- actionTextBox.setRight( timeBox.left()-margin );
+ actionTextBox.setLeft(userIconRect.right() + margin);
+ actionTextBox.setRight(timeBox.left() - margin);
/* === start drawing === */
QPixmap pm = actionIcon.pixmap(iconWidth, iconHeight, QIcon::Normal);
painter->drawPixmap(QPoint(userIconRect.left(), userIconRect.top()), pm);
QPalette::ColorGroup cg = option.state & QStyle::State_Enabled
- ? QPalette::Normal : QPalette::Disabled;
+ ? QPalette::Normal
+ : QPalette::Disabled;
if (cg == QPalette::Normal && !(option.state & QStyle::State_Active))
cg = QPalette::Inactive;
if (option.state & QStyle::State_Selected) {
painter->drawText(actionTextBox, elidedAction);
int atPos = accountRole.indexOf(QLatin1Char('@'));
- if( atPos > -1 ) {
- accountRole.remove(0, atPos+1);
+ if (atPos > -1) {
+ accountRole.remove(0, atPos + 1);
}
QString timeStr;
- if ( accountOnline ) {
+ if (accountOnline) {
timeStr = tr("%1 on %2").arg(timeText, accountRole);
} else {
timeStr = tr("%1 on %2 (disconnected)").arg(timeText, accountRole);
painter->drawText(timeBox, elidedTime);
painter->restore();
-
}
-bool ActivityItemDelegate::editorEvent ( QEvent * event, QAbstractItemModel * model,
- const QStyleOptionViewItem & option, const QModelIndex & index )
+bool ActivityItemDelegate::editorEvent(QEvent *event, QAbstractItemModel *model,
+ const QStyleOptionViewItem &option, const QModelIndex &index)
{
return QStyledItemDelegate::editorEvent(event, model, option, index);
}
{
Q_OBJECT
public:
-
enum datarole { ActionIconRole = Qt::UserRole + 1,
- UserIconRole,
- AccountRole,
- ActionTextRole,
- PathRole,
- LinkRole,
- PointInTimeRole,
- AccountConnectedRole };
-
- void paint( QPainter*, const QStyleOptionViewItem&, const QModelIndex& ) const Q_DECL_OVERRIDE;
- QSize sizeHint( const QStyleOptionViewItem&, const QModelIndex& ) const Q_DECL_OVERRIDE;
- bool editorEvent( QEvent* event, QAbstractItemModel* model, const QStyleOptionViewItem& option,
- const QModelIndex& index ) Q_DECL_OVERRIDE;
+ UserIconRole,
+ AccountRole,
+ ActionTextRole,
+ PathRole,
+ LinkRole,
+ PointInTimeRole,
+ AccountConnectedRole };
+
+ void paint(QPainter *, const QStyleOptionViewItem &, const QModelIndex &) const Q_DECL_OVERRIDE;
+ QSize sizeHint(const QStyleOptionViewItem &, const QModelIndex &) const Q_DECL_OVERRIDE;
+ bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option,
+ const QModelIndex &index) Q_DECL_OVERRIDE;
static int rowHeight();
static int iconHeight();
};
} // namespace OCC
-
Q_LOGGING_CATEGORY(lcActivity, "gui.activity", QtInfoMsg)
ActivityListModel::ActivityListModel(QWidget *parent)
- :QAbstractListModel(parent)
+ : QAbstractListModel(parent)
{
}
switch (role) {
case ActivityItemDelegate::PathRole:
list = FolderMan::instance()->findFileInLocalFolders(a._file, ast->account());
- if( list.count() > 0 ) {
+ if (list.count() > 0) {
return QVariant(list.at(0));
}
// File does not exist anymore? Let's try to open its path
list = FolderMan::instance()->findFileInLocalFolders(QFileInfo(a._file).path(), ast->account());
- if( list.count() > 0 ) {
+ if (list.count() > 0) {
return QVariant(list.at(0));
}
return QVariant();
break;
default:
return QVariant();
-
}
return QVariant();
-
}
-int ActivityListModel::rowCount(const QModelIndex&) const
+int ActivityListModel::rowCount(const QModelIndex &) const
{
return _finalList.count();
}
// current strategy: Fetch 100 items per Account
// ATTENTION: This method is const and thus it is not possible to modify
// the _activityLists hash or so. Doesn't make it easier...
-bool ActivityListModel::canFetchMore(const QModelIndex& ) const
+bool ActivityListModel::canFetchMore(const QModelIndex &) const
{
- if( _activityLists.count() == 0 ) return true;
+ if (_activityLists.count() == 0)
+ return true;
- for(auto i = _activityLists.begin() ; i != _activityLists.end(); ++i) {
+ for (auto i = _activityLists.begin(); i != _activityLists.end(); ++i) {
AccountState *ast = i.key();
- if( ast && ast->isConnected() ) {
+ if (ast && ast->isConnected()) {
ActivityList activities = i.value();
- if( activities.count() == 0 &&
- ! _currentlyFetching.contains(ast) ) {
+ if (activities.count() == 0 && !_currentlyFetching.contains(ast)) {
return true;
}
}
return false;
}
-void ActivityListModel::startFetchJob(AccountState* s)
+void ActivityListModel::startFetchJob(AccountState *s)
{
- if( !s->isConnected() ) {
+ if (!s->isConnected()) {
return;
}
JsonApiJob *job = new JsonApiJob(s->account(), QLatin1String("ocs/v1.php/cloud/activity"), this);
QObject::connect(job, SIGNAL(jsonReceived(QJsonDocument, int)),
- this, SLOT(slotActivitiesReceived(QJsonDocument, int)));
+ this, SLOT(slotActivitiesReceived(QJsonDocument, int)));
job->setProperty("AccountStatePtr", QVariant::fromValue<QPointer<AccountState>>(s));
- QList< QPair<QString,QString> > params;
- params.append(qMakePair(QString::fromLatin1("page"), QString::fromLatin1("0")));
+ QList<QPair<QString, QString>> params;
+ params.append(qMakePair(QString::fromLatin1("page"), QString::fromLatin1("0")));
params.append(qMakePair(QString::fromLatin1("pagesize"), QString::fromLatin1("100")));
job->addQueryParams(params);
job->start();
}
-void ActivityListModel::slotActivitiesReceived(const QJsonDocument& json, int statusCode)
+void ActivityListModel::slotActivitiesReceived(const QJsonDocument &json, int statusCode)
{
auto activities = json.object().value("ocs").toObject().value("data").toArray();
_currentlyFetching.remove(ast);
- foreach( auto activ, activities ) {
+ foreach (auto activ, activities) {
auto json = activ.toObject();
Activity a;
a._type = Activity::ActivityType;
- a._accName = ast->account()->displayName();
- a._id = json.value("id").toInt();
- a._subject = json.value("subject").toString();
- a._message = json.value("message").toString();
- a._file = json.value("file").toString();
- a._link = QUrl(json.value("link").toString());
+ a._accName = ast->account()->displayName();
+ a._id = json.value("id").toInt();
+ a._subject = json.value("subject").toString();
+ a._message = json.value("message").toString();
+ a._file = json.value("file").toString();
+ a._link = QUrl(json.value("link").toString());
a._dateTime = QDateTime::fromString(json.value("date").toString(), Qt::ISODate);
list.append(a);
}
{
ActivityList resultList;
- foreach( ActivityList list, _activityLists.values() ) {
+ foreach (ActivityList list, _activityLists.values()) {
resultList.append(list);
}
- std::sort( resultList.begin(), resultList.end() );
+ std::sort(resultList.begin(), resultList.end());
beginResetModel();
_finalList.clear();
{
QList<AccountStatePtr> accounts = AccountManager::instance()->accounts();
- foreach (const AccountStatePtr& asp, accounts) {
-
- if( !_activityLists.contains(asp.data()) && asp->isConnected() ) {
+ foreach (const AccountStatePtr &asp, accounts) {
+ if (!_activityLists.contains(asp.data()) && asp->isConnected()) {
_activityLists[asp.data()] = ActivityList();
startFetchJob(asp.data());
}
void ActivityListModel::slotRefreshActivity(AccountState *ast)
{
- if(ast && _activityLists.contains(ast)) {
+ if (ast && _activityLists.contains(ast)) {
_activityLists.remove(ast);
}
startFetchJob(ast);
}
-void ActivityListModel::slotRemoveAccount(AccountState *ast )
+void ActivityListModel::slotRemoveAccount(AccountState *ast)
{
- if( _activityLists.contains(ast) ) {
+ if (_activityLists.contains(ast)) {
int i = 0;
const QString accountToRemove = ast->account()->displayName();
while (it.hasNext()) {
Activity activity = it.next();
- if( activity._accName == accountToRemove ) {
- beginRemoveRows(QModelIndex(), i, i+1);
+ if (activity._accName == accountToRemove) {
+ beginRemoveRows(QModelIndex(), i, i + 1);
it.remove();
endRemoveRows();
}
_currentlyFetching.remove(ast);
}
}
-
}
{
Q_OBJECT
public:
- explicit ActivityListModel(QWidget *parent=0);
+ explicit ActivityListModel(QWidget *parent = 0);
QVariant data(const QModelIndex &index, int role) const Q_DECL_OVERRIDE;
- int rowCount(const QModelIndex& parent = QModelIndex()) const Q_DECL_OVERRIDE;
+ int rowCount(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE;
- bool canFetchMore(const QModelIndex& ) const Q_DECL_OVERRIDE;
- void fetchMore(const QModelIndex&) Q_DECL_OVERRIDE;
+ bool canFetchMore(const QModelIndex &) const Q_DECL_OVERRIDE;
+ void fetchMore(const QModelIndex &) Q_DECL_OVERRIDE;
ActivityList activityList() { return _finalList; }
public slots:
- void slotRefreshActivity(AccountState* ast);
- void slotRemoveAccount( AccountState *ast );
+ void slotRefreshActivity(AccountState *ast);
+ void slotRemoveAccount(AccountState *ast);
private slots:
- void slotActivitiesReceived(const QJsonDocument& json, int statusCode);
+ void slotActivitiesReceived(const QJsonDocument &json, int statusCode);
signals:
- void activityJobStatusCode(AccountState* ast, int statusCode);
+ void activityJobStatusCode(AccountState *ast, int statusCode);
private:
- void startFetchJob(AccountState* s);
+ void startFetchJob(AccountState *s);
void combineActivityLists();
- QMap<AccountState*, ActivityList> _activityLists;
+ QMap<AccountState *, ActivityList> _activityLists;
ActivityList _finalList;
- QSet<AccountState*> _currentlyFetching;
+ QSet<AccountState *> _currentlyFetching;
};
-
-
}
#endif // ACTIVITYLISTMODEL_H
namespace OCC {
-ActivityWidget::ActivityWidget(QWidget *parent) :
- QWidget(parent),
- _ui(new Ui::ActivityWidget),
- _notificationRequestsRunning(0)
+ActivityWidget::ActivityWidget(QWidget *parent)
+ : QWidget(parent)
+ , _ui(new Ui::ActivityWidget)
+ , _notificationRequestsRunning(0)
{
_ui->setupUi(this);
- // Adjust copyToClipboard() when making changes here!
+// Adjust copyToClipboard() when making changes here!
#if defined(Q_OS_MAC)
_ui->_activityList->setMinimumWidth(400);
#endif
showLabels();
- connect(_model, SIGNAL(activityJobStatusCode(AccountState*,int)),
- this, SLOT(slotAccountActivityStatus(AccountState*,int)));
+ connect(_model, SIGNAL(activityJobStatusCode(AccountState *, int)),
+ this, SLOT(slotAccountActivityStatus(AccountState *, int)));
_copyBtn = _ui->_dialogButtonBox->addButton(tr("Copy"), QDialogButtonBox::ActionRole);
- _copyBtn->setToolTip( tr("Copy the activity list to the clipboard."));
+ _copyBtn->setToolTip(tr("Copy the activity list to the clipboard."));
connect(_copyBtn, SIGNAL(clicked()), SIGNAL(copyToClipboard()));
- connect(_model, SIGNAL(rowsInserted(QModelIndex,int,int)), SIGNAL(rowsInserted()));
+ connect(_model, SIGNAL(rowsInserted(QModelIndex, int, int)), SIGNAL(rowsInserted()));
- connect( _ui->_activityList, SIGNAL(activated(QModelIndex)), this,
- SLOT(slotOpenFile(QModelIndex)));
+ connect(_ui->_activityList, SIGNAL(activated(QModelIndex)), this,
+ SLOT(slotOpenFile(QModelIndex)));
- connect( &_removeTimer, SIGNAL(timeout()), this, SLOT(slotCheckToCleanWidgets()) );
+ connect(&_removeTimer, SIGNAL(timeout()), this, SLOT(slotCheckToCleanWidgets()));
_removeTimer.setInterval(1000);
}
{
// start a server notification handler if no notification requests
// are running
- if( _notificationRequestsRunning == 0 ) {
+ if (_notificationRequestsRunning == 0) {
ServerNotificationHandler *snh = new ServerNotificationHandler;
connect(snh, SIGNAL(newNotificationList(ActivityList)), this,
- SLOT(slotBuildNotificationDisplay(ActivityList)));
+ SLOT(slotBuildNotificationDisplay(ActivityList)));
snh->slotFetchNotifications(ptr);
} else {
}
}
-void ActivityWidget::slotRemoveAccount( AccountState *ptr )
+void ActivityWidget::slotRemoveAccount(AccountState *ptr)
{
_model->slotRemoveAccount(ptr);
}
t.clear();
QSetIterator<QString> i(_accountsWithoutActivities);
- while (i.hasNext() ) {
- t.append( tr("<br/>Account %1 does not have activities enabled.").arg(i.next()));
+ while (i.hasNext()) {
+ t.append(tr("<br/>Account %1 does not have activities enabled.").arg(i.next()));
}
_ui->_bottomLabel->setTextFormat(Qt::RichText);
_ui->_bottomLabel->setText(t);
void ActivityWidget::slotAccountActivityStatus(AccountState *ast, int statusCode)
{
- if( !(ast && ast->account()) ) {
+ if (!(ast && ast->account())) {
return;
}
- if( statusCode == 999 ) {
+ if (statusCode == 999) {
_accountsWithoutActivities.insert(ast->account()->displayName());
} else {
_accountsWithoutActivities.remove(ast->account()->displayName());
return loc.toString(dt, dtFormat);
}
-void ActivityWidget::storeActivityList( QTextStream& ts )
+void ActivityWidget::storeActivityList(QTextStream &ts)
{
ActivityList activities = _model->activityList();
- foreach( Activity activity, activities ) {
+ foreach (Activity activity, activities) {
ts << right
- // account name
+ // account name
<< qSetFieldWidth(30)
<< activity._accName
- // separator
+ // separator
<< qSetFieldWidth(0) << ","
- // date and time
+ // date and time
<< qSetFieldWidth(34)
<< activity._dateTime.toString()
- // separator
+ // separator
<< qSetFieldWidth(0) << ","
- // file
+ // file
<< qSetFieldWidth(30)
<< activity._file
- // separator
+ // separator
<< qSetFieldWidth(0) << ","
- // subject
+ // subject
<< qSetFieldWidth(100)
<< activity._subject
- // separator
+ // separator
<< qSetFieldWidth(0) << ","
- // message (mostly empty)
+ // message (mostly empty)
<< qSetFieldWidth(55)
<< activity._message
- //
+ //
<< qSetFieldWidth(0)
<< endl;
}
{
int accountCount = AccountManager::instance()->accounts().count();
bool hasAccountsWithActivity =
- _accountsWithoutActivities.count() != accountCount;
+ _accountsWithoutActivities.count() != accountCount;
bool hasNotifications = !_widgetForNotifId.isEmpty();
- _ui->_headerLabel->setVisible( hasAccountsWithActivity );
- _ui->_activityList->setVisible( hasAccountsWithActivity );
+ _ui->_headerLabel->setVisible(hasAccountsWithActivity);
+ _ui->_activityList->setVisible(hasAccountsWithActivity);
- _ui->_notifyLabel->setVisible( hasNotifications );
- _ui->_notifyScroll->setVisible( hasNotifications );
+ _ui->_notifyLabel->setVisible(hasNotifications);
+ _ui->_notifyScroll->setVisible(hasNotifications);
emit hideActivityTab(!hasAccountsWithActivity && !hasNotifications);
}
void ActivityWidget::slotOpenFile(QModelIndex indx)
{
qCDebug(lcActivity) << indx.isValid() << indx.data(ActivityItemDelegate::PathRole).toString() << QFile::exists(indx.data(ActivityItemDelegate::PathRole).toString());
- if( indx.isValid() ) {
+ if (indx.isValid()) {
QString fullPath = indx.data(ActivityItemDelegate::PathRole).toString();
if (QFile::exists(fullPath)) {
// All notifications in list are coming from the same account
// but in the _widgetForNotifId hash widgets for all accounts are
// collected.
-void ActivityWidget::slotBuildNotificationDisplay(const ActivityList& list)
+void ActivityWidget::slotBuildNotificationDisplay(const ActivityList &list)
{
QHash<QString, int> accNotified;
QString listAccountName;
// Whether a new notification widget was added to the notificationLayout.
bool newNotificationShown = false;
- foreach( auto activity, list ) {
- if( _blacklistedNotifications.contains(activity)) {
+ foreach (auto activity, list) {
+ if (_blacklistedNotifications.contains(activity)) {
qCInfo(lcActivity) << "Activity in blacklist, skip";
continue;
}
NotificationWidget *widget = 0;
- if( _widgetForNotifId.contains( activity.ident()) ) {
+ if (_widgetForNotifId.contains(activity.ident())) {
widget = _widgetForNotifId[activity.ident()];
} else {
widget = new NotificationWidget(this);
connect(widget, SIGNAL(sendNotificationRequest(QString, QString, QByteArray)),
- this, SLOT(slotSendNotificationRequest(QString, QString, QByteArray)));
+ this, SLOT(slotSendNotificationRequest(QString, QString, QByteArray)));
connect(widget, SIGNAL(requestCleanupAndBlacklist(Activity)),
- this, SLOT(slotRequestCleanupAndBlacklist(Activity)));
+ this, SLOT(slotRequestCleanupAndBlacklist(Activity)));
_notificationsLayout->addWidget(widget);
- // _ui->_notifyScroll->setMinimumHeight( widget->height());
+// _ui->_notifyScroll->setMinimumHeight( widget->height());
#if QT_VERSION >= QT_VERSION_CHECK(5, 2, 0)
_ui->_notifyScroll->setSizeAdjustPolicy(QAbstractScrollArea::AdjustToContentsOnFirstShow);
#endif
newNotificationShown = true;
}
- widget->setActivity( activity );
+ widget->setActivity(activity);
// remember the list account name for the strayCat handling below.
listAccountName = activity._accName;
// will repeat the gui log.
// after one hour, clear the gui log notification store
- if( _guiLogTimer.elapsed() > 60*60*1000 ) {
+ if (_guiLogTimer.elapsed() > 60 * 60 * 1000) {
_guiLoggedNotifications.clear();
}
- if( !_guiLoggedNotifications.contains(activity._id)) {
+ if (!_guiLoggedNotifications.contains(activity._id)) {
QString host = activity._accName;
// store the name of the account that sends the notification to be
// able to add it to the tray notification
// remove the user name from the account as that is not accurate here.
int indx = host.indexOf(QChar('@'));
- if( indx>-1 ) {
- host.remove(0, 1+indx);
+ if (indx > -1) {
+ host.remove(0, 1 + indx);
}
- if( !host.isEmpty() ) {
- if( accNotified.contains(host)) {
- accNotified[host] = accNotified[host]+1;
+ if (!host.isEmpty()) {
+ if (accNotified.contains(host)) {
+ accNotified[host] = accNotified[host] + 1;
} else {
accNotified[host] = 1;
}
// check if there are widgets that have no corresponding activity from
// the server any more. Collect them in a list
- QList< Activity::Identifier > strayCats;
- foreach( auto id, _widgetForNotifId.keys() ) {
+ QList<Activity::Identifier> strayCats;
+ foreach (auto id, _widgetForNotifId.keys()) {
NotificationWidget *widget = _widgetForNotifId[id];
bool found = false;
// do not mark widgets of other accounts to delete.
- if( widget->activity()._accName != listAccountName ) {
+ if (widget->activity()._accName != listAccountName) {
continue;
}
- foreach( auto activity, list ) {
- if( activity.ident() == id ) {
+ foreach (auto activity, list) {
+ if (activity.ident() == id) {
// found an activity
found = true;
break;
}
}
- if( ! found ) {
+ if (!found) {
// the activity does not exist any more.
strayCats.append(id);
}
}
// .. and now delete all these stray cat widgets.
- foreach( auto strayCatId, strayCats ) {
+ foreach (auto strayCatId, strayCats) {
NotificationWidget *widgetToGo = _widgetForNotifId[strayCatId];
scheduleWidgetToRemove(widgetToGo, 0);
}
int newGuiLogCount = accNotified.count();
- if( newGuiLogCount > 0 ) {
+ if (newGuiLogCount > 0) {
// restart the gui log timer now that we show a notification
_guiLogTimer.restart();
// Assemble a tray notification
- QString msg = tr("You received %n new notification(s) from %2.", "", accNotified[accNotified.keys().at(0)]).
- arg(accNotified.keys().at(0));
+ QString msg = tr("You received %n new notification(s) from %2.", "", accNotified[accNotified.keys().at(0)]).arg(accNotified.keys().at(0));
- if( newGuiLogCount >= 2 ) {
+ if (newGuiLogCount >= 2) {
QString acc1 = accNotified.keys().at(0);
QString acc2 = accNotified.keys().at(1);
- if( newGuiLogCount == 2 ) {
- int notiCount = accNotified[ acc1 ] + accNotified[ acc2 ];
+ if (newGuiLogCount == 2) {
+ int notiCount = accNotified[acc1] + accNotified[acc2];
msg = tr("You received %n new notification(s) from %1 and %2.", "", notiCount).arg(acc1, acc2);
} else {
msg = tr("You received new notifications from %1, %2 and other accounts.").arg(acc1, acc2);
}
const QString log = tr("%1 Notifications - Action Required").arg(Theme::instance()->appNameGUI());
- emit guiLog( log, msg);
+ emit guiLog(log, msg);
}
if (newNotificationShown) {
}
}
-void ActivityWidget::slotSendNotificationRequest(const QString& accountName, const QString& link, const QByteArray& verb)
+void ActivityWidget::slotSendNotificationRequest(const QString &accountName, const QString &link, const QByteArray &verb)
{
qCInfo(lcActivity) << "Server Notification Request " << verb << link << "on account" << accountName;
- NotificationWidget *theSender = qobject_cast<NotificationWidget*>(sender());
+ NotificationWidget *theSender = qobject_cast<NotificationWidget *>(sender());
- const QStringList validVerbs = QStringList() << "GET" << "PUT" << "POST" << "DELETE";
+ const QStringList validVerbs = QStringList() << "GET"
+ << "PUT"
+ << "POST"
+ << "DELETE";
- if( validVerbs.contains(verb)) {
+ if (validVerbs.contains(verb)) {
AccountStatePtr acc = AccountManager::instance()->account(accountName);
- if( acc ) {
+ if (acc) {
NotificationConfirmJob *job = new NotificationConfirmJob(acc->account());
QUrl l(link);
job->setLinkAndVerb(l, verb);
job->setWidget(theSender);
- connect( job, SIGNAL( networkError(QNetworkReply*)),
- this, SLOT(slotNotifyNetworkError(QNetworkReply*)));
- connect( job, SIGNAL( jobFinished(QString, int)),
- this, SLOT(slotNotifyServerFinished(QString, int)) );
+ connect(job, SIGNAL(networkError(QNetworkReply *)),
+ this, SLOT(slotNotifyNetworkError(QNetworkReply *)));
+ connect(job, SIGNAL(jobFinished(QString, int)),
+ this, SLOT(slotNotifyServerFinished(QString, int)));
job->start();
// count the number of running notification requests. If this member var
}
}
-void ActivityWidget::endNotificationRequest( NotificationWidget *widget, int replyCode )
+void ActivityWidget::endNotificationRequest(NotificationWidget *widget, int replyCode)
{
_notificationRequestsRunning--;
- if( widget ) {
+ if (widget) {
widget->slotNotificationRequestFinished(replyCode);
}
}
-void ActivityWidget::slotNotifyNetworkError( QNetworkReply *reply)
+void ActivityWidget::slotNotifyNetworkError(QNetworkReply *reply)
{
- NotificationConfirmJob *job = qobject_cast<NotificationConfirmJob*>(sender());
- if( !job ) {
+ NotificationConfirmJob *job = qobject_cast<NotificationConfirmJob *>(sender());
+ if (!job) {
return;
}
endNotificationRequest(job->widget(), resultCode);
qCWarning(lcActivity) << "Server notify job failed with code " << resultCode;
-
}
-void ActivityWidget::slotNotifyServerFinished( const QString& reply, int replyCode )
+void ActivityWidget::slotNotifyServerFinished(const QString &reply, int replyCode)
{
- NotificationConfirmJob *job = qobject_cast<NotificationConfirmJob*>(sender());
- if( !job ) {
+ NotificationConfirmJob *job = qobject_cast<NotificationConfirmJob *>(sender());
+ if (!job) {
return;
}
endNotificationRequest(job->widget(), replyCode);
// FIXME: remove the widget after a couple of seconds
- qCInfo(lcActivity) << "Server Notification reply code"<< replyCode << reply;
+ qCInfo(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
// Add 200 millisecs to the predefined value to make sure that the timer in
// widget's method readyToClose() has elapsed.
- if( replyCode == OCS_SUCCESS_STATUS_CODE ) {
- scheduleWidgetToRemove( job->widget() );
+ if (replyCode == OCS_SUCCESS_STATUS_CODE) {
+ scheduleWidgetToRemove(job->widget());
}
}
// blacklist the activity coming in here.
-void ActivityWidget::slotRequestCleanupAndBlacklist(const Activity& blacklistActivity)
+void ActivityWidget::slotRequestCleanupAndBlacklist(const Activity &blacklistActivity)
{
- if ( ! _blacklistedNotifications.contains(blacklistActivity) ) {
+ if (!_blacklistedNotifications.contains(blacklistActivity)) {
_blacklistedNotifications.append(blacklistActivity);
}
- NotificationWidget *widget = _widgetForNotifId[ blacklistActivity.ident() ];
+ NotificationWidget *widget = _widgetForNotifId[blacklistActivity.ident()];
scheduleWidgetToRemove(widget);
}
void ActivityWidget::scheduleWidgetToRemove(NotificationWidget *widget, int milliseconds)
{
- if( !widget ) {
+ if (!widget) {
return;
}
// in five seconds from now, remove the widget.
if (!it.isValid() || it > removeTime) {
it = removeTime;
}
- if( !_removeTimer.isActive() ) {
+ if (!_removeTimer.isActive()) {
_removeTimer.start();
}
}
QDateTime t = it.value();
NotificationWidget *widget = it.key();
- if( currentTime > t ) {
+ if (currentTime > t) {
// found one to remove!
Activity::Identifier id = widget->activity().ident();
_widgetForNotifId.remove(id);
}
}
- if( _widgetsToRemove.isEmpty() ) {
+ if (_widgetsToRemove.isEmpty()) {
_removeTimer.stop();
}
// check to see if the whole notification pane should be hidden
- if( _widgetForNotifId.isEmpty() ) {
+ if (_widgetForNotifId.isEmpty()) {
_ui->_notifyLabel->setHidden(true);
_ui->_notifyScroll->setHidden(true);
}
/* ==================================================================== */
ActivitySettings::ActivitySettings(QWidget *parent)
- :QWidget(parent)
+ : QWidget(parent)
{
QHBoxLayout *hbox = new QHBoxLayout(this);
setLayout(hbox);
_activityTabId = _tab->insertTab(0, _activityWidget, Theme::instance()->applicationIcon(), tr("Server Activity"));
connect(_activityWidget, SIGNAL(copyToClipboard()), this, SLOT(slotCopyToClipboard()));
connect(_activityWidget, SIGNAL(hideActivityTab(bool)), this, SLOT(setActivityTabHidden(bool)));
- connect(_activityWidget, SIGNAL(guiLog(QString,QString)), this, SIGNAL(guiLog(QString,QString)));
+ connect(_activityWidget, SIGNAL(guiLog(QString, QString)), this, SIGNAL(guiLog(QString, QString)));
connect(_activityWidget, SIGNAL(newNotification()), SLOT(slotShowActivityTab()));
_protocolWidget = new ProtocolWidget(this);
_tab->insertTab(1, _protocolWidget, Theme::instance()->syncStateIcon(SyncResult::Success), tr("Sync Protocol"));
connect(_protocolWidget, SIGNAL(copyToClipboard()), this, SLOT(slotCopyToClipboard()));
connect(_protocolWidget, SIGNAL(issueItemCountUpdated(int)),
- this, SLOT(slotShowIssueItemCount(int)));
+ this, SLOT(slotShowIssueItemCount(int)));
// Add the not-synced list into the tab
QWidget *w = new QWidget;
QDialogButtonBox *dlgButtonBox = new QDialogButtonBox(this);
vbox2->addWidget(dlgButtonBox);
QPushButton *_copyBtn = dlgButtonBox->addButton(tr("Copy"), QDialogButtonBox::ActionRole);
- _copyBtn->setToolTip( tr("Copy the activity list to the clipboard."));
+ _copyBtn->setToolTip(tr("Copy the activity list to the clipboard."));
_copyBtn->setEnabled(true);
connect(_copyBtn, SIGNAL(clicked()), this, SLOT(slotCopyToClipboard()));
_tab->setCornerWidget(_progressIndicator);
connect(&_notificationCheckTimer, SIGNAL(timeout()),
- this, SLOT(slotRegularNotificationCheck()));
+ this, SLOT(slotRegularNotificationCheck()));
// connect a model signal to stop the animation.
connect(_activityWidget, SIGNAL(rowsInserted()), _progressIndicator, SLOT(stopAnimation()));
_tab->setCurrentIndex(1);
}
-void ActivitySettings::setNotificationRefreshInterval( quint64 interval )
+void ActivitySettings::setNotificationRefreshInterval(quint64 interval)
{
- qCDebug(lcActivity) << "Starting Notification refresh timer with " << interval/1000 << " sec interval";
+ qCDebug(lcActivity) << "Starting Notification refresh timer with " << interval / 1000 << " sec interval";
_notificationCheckTimer.start(interval);
}
void ActivitySettings::setActivityTabHidden(bool hidden)
{
- if( hidden && _activityTabId > -1 ) {
+ if (hidden && _activityTabId > -1) {
_tab->removeTab(_activityTabId);
_activityTabId = -1;
}
- if( !hidden && _activityTabId == -1 ) {
+ if (!hidden && _activityTabId == -1) {
_activityTabId = _tab->insertTab(0, _activityWidget, Theme::instance()->applicationIcon(), tr("Server Activity"));
}
}
void ActivitySettings::slotShowIssueItemCount(int cnt)
{
QString cntText = tr("Not Synced");
- if( cnt ) {
+ if (cnt) {
//: %1 is the number of not synced files.
cntText = tr("Not Synced (%1)").arg(cnt);
}
int idx = _tab->currentIndex();
QString message;
- if( idx == 0 ) {
+ if (idx == 0) {
// the activity widget
_activityWidget->storeActivityList(ts);
message = tr("The server activity list has been copied to the clipboard.");
- } else if(idx == 1 ) {
+ } else if (idx == 1) {
// the protocol widget
_protocolWidget->storeSyncActivity(ts);
message = tr("The sync activity list has been copied to the clipboard.");
- } else if(idx == 2 ) {
+ } else if (idx == 2) {
// issues Widget
message = tr("The list of unsynced items has been copied to the clipboard.");
- _protocolWidget->storeSyncIssues(ts);
+ _protocolWidget->storeSyncIssues(ts);
}
QApplication::clipboard()->setText(text);
emit guiLog(tr("Copied to clipboard"), message);
}
-void ActivitySettings::slotRemoveAccount( AccountState *ptr )
+void ActivitySettings::slotRemoveAccount(AccountState *ptr)
{
_activityWidget->slotRemoveAccount(ptr);
}
-void ActivitySettings::slotRefresh( AccountState* ptr )
+void ActivitySettings::slotRefresh(AccountState *ptr)
{
// QElapsedTimer isn't actually constructed as invalid.
- if ( !_timeSinceLastCheck.contains(ptr) ) {
+ if (!_timeSinceLastCheck.contains(ptr)) {
_timeSinceLastCheck[ptr].invalidate();
}
- QElapsedTimer & timer = _timeSinceLastCheck[ptr];
+ QElapsedTimer &timer = _timeSinceLastCheck[ptr];
// Fetch Activities only if visible and if last check is longer than 15 secs ago
- if( timer.isValid() && timer.elapsed() < NOTIFICATION_REQUEST_FREE_PERIOD ) {
+ if (timer.isValid() && timer.elapsed() < NOTIFICATION_REQUEST_FREE_PERIOD) {
qCDebug(lcActivity) << "Do not check as last check is only secs ago: " << timer.elapsed() / 1000;
return;
}
- if( ptr && ptr->isConnected() ) {
- if( isVisible() || !timer.isValid() ) {
+ if (ptr && ptr->isConnected()) {
+ if (isVisible() || !timer.isValid()) {
_progressIndicator->startAnimation();
- _activityWidget->slotRefreshActivities( ptr);
+ _activityWidget->slotRefreshActivities(ptr);
}
_activityWidget->slotRefreshNotifications(ptr);
timer.start();
}
}
-bool ActivitySettings::event(QEvent* e)
+bool ActivitySettings::event(QEvent *e)
{
if (e->type() == QEvent::Show) {
AccountManager *am = AccountManager::instance();
ActivitySettings::~ActivitySettings()
{
-
}
-
-
}
class ActivityListModel;
namespace Ui {
- class ActivityWidget;
+ class ActivityWidget;
}
class Application;
public slots:
void slotOpenFile(QModelIndex indx);
- void slotRefreshActivities(AccountState* ptr);
+ void slotRefreshActivities(AccountState *ptr);
void slotRefreshNotifications(AccountState *ptr);
- void slotRemoveAccount( AccountState *ptr );
+ void slotRemoveAccount(AccountState *ptr);
void slotAccountActivityStatus(AccountState *ast, int statusCode);
- void slotRequestCleanupAndBlacklist(const Activity& blacklistActivity);
+ void slotRequestCleanupAndBlacklist(const Activity &blacklistActivity);
signals:
- void guiLog(const QString&, const QString&);
+ void guiLog(const QString &, const QString &);
void copyToClipboard();
void rowsInserted();
void hideActivityTab(bool);
void newNotification();
private slots:
- void slotBuildNotificationDisplay(const ActivityList& list);
- void slotSendNotificationRequest(const QString &accountName, const QString& link, const QByteArray &verb);
- void slotNotifyNetworkError( QNetworkReply* );
- void slotNotifyServerFinished( const QString& reply, int replyCode );
- void endNotificationRequest(NotificationWidget *widget , int replyCode);
+ void slotBuildNotificationDisplay(const ActivityList &list);
+ void slotSendNotificationRequest(const QString &accountName, const QString &link, const QByteArray &verb);
+ void slotNotifyNetworkError(QNetworkReply *);
+ void slotNotifyServerFinished(const QString &reply, int replyCode);
+ void endNotificationRequest(NotificationWidget *widget, int replyCode);
void scheduleWidgetToRemove(NotificationWidget *widget, int milliseconds = 4500);
void slotCheckToCleanWidgets();
QPushButton *_copyBtn;
QSet<QString> _accountsWithoutActivities;
- QMap<Activity::Identifier, NotificationWidget*> _widgetForNotifId;
+ QMap<Activity::Identifier, NotificationWidget *> _widgetForNotifId;
QElapsedTimer _guiLogTimer;
QSet<int> _guiLoggedNotifications;
ActivityList _blacklistedNotifications;
- QHash<NotificationWidget*, QDateTime> _widgetsToRemove;
+ QHash<NotificationWidget *, QDateTime> _widgetsToRemove;
QTimer _removeTimer;
// number of currently running notification requests. If non zero,
ActivityListModel *_model;
QVBoxLayout *_notificationsLayout;
-
};
QSize sizeHint() const Q_DECL_OVERRIDE { return ownCloudGui::settingsDialogSize(); }
public slots:
- void slotRefresh( AccountState* ptr );
- void slotRemoveAccount( AccountState *ptr );
+ void slotRefresh(AccountState *ptr);
+ void slotRemoveAccount(AccountState *ptr);
- void setNotificationRefreshInterval( quint64 interval );
+ void setNotificationRefreshInterval(quint64 interval);
private slots:
void slotCopyToClipboard();
void slotShowActivityTab();
signals:
- void guiLog(const QString&, const QString&);
+ void guiLog(const QString &, const QString &);
private:
- bool event(QEvent* e) Q_DECL_OVERRIDE;
+ bool event(QEvent *e) Q_DECL_OVERRIDE;
QTabWidget *_tab;
int _activityTabId;
ActivityWidget *_activityWidget;
ProtocolWidget *_protocolWidget;
QProgressIndicator *_progressIndicator;
- QTimer _notificationCheckTimer;
- QHash<AccountState*, QElapsedTimer> _timeSinceLastCheck;
+ QTimer _notificationCheckTimer;
+ QHash<AccountState *, QElapsedTimer> _timeSinceLastCheck;
};
-
}
#endif // ActivityWIDGET_H
namespace OCC {
-AddCertificateDialog::AddCertificateDialog(QWidget *parent) :
- QDialog(parent),
- ui(new Ui::AddCertificateDialog)
+AddCertificateDialog::AddCertificateDialog(QWidget *parent)
+ : QDialog(parent)
+ , ui(new Ui::AddCertificateDialog)
{
ui->setupUi(this);
ui->labelErrorCertif->setText("");
ui->lineEditCertificatePath->clear();
ui->lineEditPWDCertificate->clear();
}
-
}
namespace OCC {
namespace Ui {
-class AddCertificateDialog;
+ class AddCertificateDialog;
}
/**
private:
Ui::AddCertificateDialog *ui;
-
};
-}//End namespace OCC
+} //End namespace OCC
#endif // ADDCERTIFICATEDIALOG_H
namespace {
-static const char optionsC[] =
+ static const char optionsC[] =
"Options:\n"
" -h --help : show this help screen.\n"
" --logwindow : open a window to show log output.\n"
" (to be used with --logdir)\n"
" --logflush : flush the log file after every write.\n"
" --logdebug : also output debug-level messages in the log (equivalent to setting the env var QT_LOGGING_RULES=\"qt.*=true;*.debug=true\").\n"
- " --confdir <dirname> : Use the given configuration folder.\n"
- ;
+ " --confdir <dirname> : Use the given configuration folder.\n";
-QString applicationTrPath()
-{
- QString devTrPath = qApp->applicationDirPath() + QString::fromLatin1("/../src/gui/");
- if (QDir(devTrPath).exists()) {
- // might miss Qt, QtKeyChain, etc.
- qCWarning(lcApplication) << "Running from build location! Translations may be incomplete!";
- return devTrPath;
- }
+ QString applicationTrPath()
+ {
+ QString devTrPath = qApp->applicationDirPath() + QString::fromLatin1("/../src/gui/");
+ if (QDir(devTrPath).exists()) {
+ // might miss Qt, QtKeyChain, etc.
+ qCWarning(lcApplication) << "Running from build location! Translations may be incomplete!";
+ return devTrPath;
+ }
#if defined(Q_OS_WIN)
- return QApplication::applicationDirPath();
+ return QApplication::applicationDirPath();
#elif defined(Q_OS_MAC)
- return QApplication::applicationDirPath()+QLatin1String("/../Resources/Translations"); // path defaults to app dir.
+ return QApplication::applicationDirPath() + QLatin1String("/../Resources/Translations"); // path defaults to app dir.
#elif defined(Q_OS_UNIX)
- return QString::fromLatin1(SHAREDIR "/" APPLICATION_EXECUTABLE "/i18n/");
+ return QString::fromLatin1(SHAREDIR "/" APPLICATION_EXECUTABLE "/i18n/");
#endif
-}
+ }
}
// ----------------------------------------------------------------------------------
-Application::Application(int &argc, char **argv) :
- SharedTools::QtSingleApplication(Theme::instance()->appName() ,argc, argv),
- _gui(0),
- _theme(Theme::instance()),
- _helpOnly(false),
- _versionOnly(false),
- _showLogWindow(false),
- _logExpire(0),
- _logFlush(false),
- _logDebug(false),
- _userTriggeredConnect(false),
- _debugMode(false)
+Application::Application(int &argc, char **argv)
+ : SharedTools::QtSingleApplication(Theme::instance()->appName(), argc, argv)
+ , _gui(0)
+ , _theme(Theme::instance())
+ , _helpOnly(false)
+ , _versionOnly(false)
+ , _showLogWindow(false)
+ , _logExpire(0)
+ , _logFlush(false)
+ , _logDebug(false)
+ , _userTriggeredConnect(false)
+ , _debugMode(false)
{
_startedAt.start();
#ifdef Q_OS_WIN
// Ensure OpenSSL config file is only loaded from app directory
- QString opensslConf = QCoreApplication::applicationDirPath()+QString("/openssl.cnf");
+ QString opensslConf = QCoreApplication::applicationDirPath() + QString("/openssl.cnf");
qputenv("OPENSSL_CONF", opensslConf.toLocal8Bit());
#endif
-// TODO: Can't set this without breaking current config paths
-// setOrganizationName(QLatin1String(APPLICATION_VENDOR));
+ // TODO: Can't set this without breaking current config paths
+ // setOrganizationName(QLatin1String(APPLICATION_VENDOR));
setOrganizationDomain(QLatin1String(APPLICATION_REV_DOMAIN));
- setApplicationName( _theme->appNameGUI() );
- setWindowIcon( _theme->applicationIcon() );
+ setApplicationName(_theme->appNameGUI());
+ setWindowIcon(_theme->applicationIcon());
#if QT_VERSION > QT_VERSION_CHECK(5, 0, 0)
setAttribute(Qt::AA_UseHighDpiPixmaps, true);
#endif
parseOptions(arguments());
//no need to waste time;
- if ( _helpOnly || _versionOnly ) return;
+ if (_helpOnly || _versionOnly)
+ return;
if (isRunning())
return;
#if defined(WITH_CRASHREPORTER)
if (ConfigFile().crashReporter())
- _crashHandler.reset(new CrashReporter::Handler( QDir::tempPath(), true, CRASHREPORTER_EXECUTABLE ));
+ _crashHandler.reset(new CrashReporter::Handler(QDir::tempPath(), true, CRASHREPORTER_EXECUTABLE));
#endif
setupLogging();
// Setup global excludes
qCInfo(lcApplication) << "Loading global exclude list";
ConfigFile cfg;
- ExcludedFiles& excludes = ExcludedFiles::instance();
- excludes.addExcludeFilePath( cfg.excludeFile(ConfigFile::SystemScope) );
- excludes.addExcludeFilePath( cfg.excludeFile(ConfigFile::UserScope) );
+ ExcludedFiles &excludes = ExcludedFiles::instance();
+ excludes.addExcludeFilePath(cfg.excludeFile(ConfigFile::SystemScope));
+ excludes.addExcludeFilePath(cfg.excludeFile(ConfigFile::UserScope));
excludes.reloadExcludes();
_folderManager.reset(new FolderMan);
- connect(this, SIGNAL(messageReceived(QString, QObject*)), SLOT(slotParseMessage(QString, QObject*)));
+ connect(this, SIGNAL(messageReceived(QString, QObject *)), SLOT(slotParseMessage(QString, QObject *)));
if (!AccountManager::instance()->restore()) {
// If there is an error reading the account settings, try again
if (!AccountManager::instance()->restore()) {
qCCritical(lcApplication) << "Could not read the account settings, quitting";
QMessageBox::critical(
- 0,
- tr("Error accessing the configuration file"),
- tr("There was an error while accessing the configuration "
- "file at %1.").arg(ConfigFile().configFile()),
- tr("Quit ownCloud"));
+ 0,
+ tr("Error accessing the configuration file"),
+ tr("There was an error while accessing the configuration "
+ "file at %1.")
+ .arg(ConfigFile().configFile()),
+ tr("Quit ownCloud"));
QTimer::singleShot(0, qApp, SLOT(quit()));
return;
}
setQuitOnLastWindowClosed(false);
_theme->setSystrayUseMonoIcons(cfg.monoIcons());
- connect (_theme, SIGNAL(systrayUseMonoIconsChanged(bool)), SLOT(slotUseMonoIconsChanged(bool)));
+ connect(_theme, SIGNAL(systrayUseMonoIconsChanged(bool)), SLOT(slotUseMonoIconsChanged(bool)));
FolderMan::instance()->setupFolders();
_proxy.setupQtProxyFromConfig(); // folders have to be defined first, than we set up the Qt proxy.
_gui = new ownCloudGui(this);
- if( _showLogWindow ) {
+ if (_showLogWindow) {
_gui->slotToggleLogBrowser(); // _showLogWindow is set in parseOptions.
}
// Enable word wrapping of QInputDialog (#4197)
setStyleSheet("QInputDialog QLabel { qproperty-wordWrap:1; }");
- connect(AccountManager::instance(), SIGNAL(accountAdded(AccountState*)),
- SLOT(slotAccountStateAdded(AccountState*)));
- connect(AccountManager::instance(), SIGNAL(accountRemoved(AccountState*)),
- SLOT(slotAccountStateRemoved(AccountState*)));
- foreach (auto ai , AccountManager::instance()->accounts()) {
+ connect(AccountManager::instance(), SIGNAL(accountAdded(AccountState *)),
+ SLOT(slotAccountStateAdded(AccountState *)));
+ connect(AccountManager::instance(), SIGNAL(accountRemoved(AccountState *)),
+ SLOT(slotAccountStateRemoved(AccountState *)));
+ foreach (auto ai, AccountManager::instance()->accounts()) {
slotAccountStateAdded(ai.data());
}
connect(FolderMan::instance()->socketApi(), SIGNAL(shareCommandReceived(QString, QString, bool)),
- _gui, SLOT(slotShowShareDialog(QString, QString, bool)));
+ _gui, SLOT(slotShowShareDialog(QString, QString, bool)));
// startup procedure.
connect(&_checkConnectionTimer, SIGNAL(timeout()), this, SLOT(slotCheckConnection()));
_checkConnectionTimer.setInterval(ConnectionValidator::DefaultCallingIntervalMsec); // check for connection every 32 seconds.
_checkConnectionTimer.start();
// Also check immediately
- QTimer::singleShot( 0, this, SLOT( slotCheckConnection() ));
+ QTimer::singleShot(0, this, SLOT(slotCheckConnection()));
// Can't use onlineStateChanged because it is always true on modern systems because of many interfaces
connect(&_networkConfigurationManager, SIGNAL(configurationChanged(QNetworkConfiguration)),
- this, SLOT(slotSystemOnlineConfigurationChanged(QNetworkConfiguration)));
+ this, SLOT(slotSystemOnlineConfigurationChanged(QNetworkConfiguration)));
// Update checks
UpdaterScheduler *updaterScheduler = new UpdaterScheduler(this);
connect(updaterScheduler, SIGNAL(updaterAnnouncement(QString, QString)),
- _gui, SLOT(slotShowTrayMessage(QString, QString)));
+ _gui, SLOT(slotShowTrayMessage(QString, QString)));
connect(updaterScheduler, SIGNAL(requestRestart()),
- _folderManager.data(), SLOT(slotScheduleAppRestart()));
+ _folderManager.data(), SLOT(slotScheduleAppRestart()));
// Cleanup at Quit.
- connect (this, SIGNAL(aboutToQuit()), SLOT(slotCleanup()));
+ connect(this, SIGNAL(aboutToQuit()), SLOT(slotCleanup()));
}
Application::~Application()
{
if (_gui) {
disconnect(accountState, SIGNAL(stateChanged(int)),
- _gui, SLOT(slotAccountStateChanged()));
- disconnect(accountState->account().data(), SIGNAL(serverVersionChanged(Account*,QString,QString)),
- _gui, SLOT(slotTrayMessageIfServerUnsupported(Account*)));
+ _gui, SLOT(slotAccountStateChanged()));
+ disconnect(accountState->account().data(), SIGNAL(serverVersionChanged(Account *, QString, QString)),
+ _gui, SLOT(slotTrayMessageIfServerUnsupported(Account *)));
}
if (_folderManager) {
disconnect(accountState, SIGNAL(stateChanged(int)),
- _folderManager.data(), SLOT(slotAccountStateChanged()));
- disconnect(accountState->account().data(), SIGNAL(serverVersionChanged(Account*,QString,QString)),
- _folderManager.data(), SLOT(slotServerVersionChanged(Account*)));
+ _folderManager.data(), SLOT(slotAccountStateChanged()));
+ disconnect(accountState->account().data(), SIGNAL(serverVersionChanged(Account *, QString, QString)),
+ _folderManager.data(), SLOT(slotServerVersionChanged(Account *)));
}
// if there is no more account, show the wizard.
- if( AccountManager::instance()->accounts().isEmpty() ) {
+ if (AccountManager::instance()->accounts().isEmpty()) {
// allow to add a new account if there is non any more. Always think
// about single account theming!
OwncloudSetupWizard::runWizard(this, SLOT(slotownCloudWizardDone(int)));
void Application::slotAccountStateAdded(AccountState *accountState)
{
connect(accountState, SIGNAL(stateChanged(int)),
- _gui, SLOT(slotAccountStateChanged()));
- connect(accountState->account().data(), SIGNAL(serverVersionChanged(Account*,QString,QString)),
- _gui, SLOT(slotTrayMessageIfServerUnsupported(Account*)));
+ _gui, SLOT(slotAccountStateChanged()));
+ connect(accountState->account().data(), SIGNAL(serverVersionChanged(Account *, QString, QString)),
+ _gui, SLOT(slotTrayMessageIfServerUnsupported(Account *)));
connect(accountState, SIGNAL(stateChanged(int)),
- _folderManager.data(), SLOT(slotAccountStateChanged()));
- connect(accountState->account().data(), SIGNAL(serverVersionChanged(Account*,QString,QString)),
- _folderManager.data(), SLOT(slotServerVersionChanged(Account*)));
+ _folderManager.data(), SLOT(slotAccountStateChanged()));
+ connect(accountState->account().data(), SIGNAL(serverVersionChanged(Account *, QString, QString)),
+ _folderManager.data(), SLOT(slotServerVersionChanged(Account *)));
_gui->slotTrayMessageIfServerUnsupported(accountState->account().data());
}
void Application::slotCheckConnection()
{
auto list = AccountManager::instance()->accounts();
- foreach (const auto &accountState , list) {
+ foreach (const auto &accountState, list) {
AccountState::State state = accountState->state();
// Don't check if we're manually signed out or
// when the error is permanent.
if (state != AccountState::SignedOut
- && state != AccountState::ConfigurationError) {
+ && state != AccountState::ConfigurationError) {
accountState->checkConnectivity();
}
}
Utility::crash();
}
-void Application::slotownCloudWizardDone( int res )
+void Application::slotownCloudWizardDone(int res)
{
AccountManager *accountMan = AccountManager::instance();
FolderMan *folderMan = FolderMan::instance();
// During the wizard, scheduling of new syncs is disabled
folderMan->setSyncEnabled(true);
- if( res == QDialog::Accepted ) {
+ if (res == QDialog::Accepted) {
// Check connectivity of the newly created account
_checkConnectionTimer.start();
slotCheckConnection();
#ifdef Q_OS_MAC
// Don't auto start when not being 'installed'
shouldSetAutoStart = shouldSetAutoStart
- && QCoreApplication::applicationDirPath().startsWith("/Applications/");
+ && QCoreApplication::applicationDirPath().startsWith("/Applications/");
#endif
Utility::setLaunchOnStartup(_theme->appName(), _theme->appNameGUI(), shouldSetAutoStart);
Logger::instance()->enterNextLogFile();
- qCInfo(lcApplication) << QString::fromLatin1( "################## %1 locale:[%2] ui_lang:[%3] version:[%4] os:[%5]").arg(_theme->appName())
- .arg( QLocale::system().name() )
- .arg(property("ui_lang").toString())
- .arg(_theme->version())
- .arg(Utility::platformName());
+ qCInfo(lcApplication) << QString::fromLatin1("################## %1 locale:[%2] ui_lang:[%3] version:[%4] os:[%5]").arg(_theme->appName()).arg(QLocale::system().name()).arg(property("ui_lang").toString()).arg(_theme->version()).arg(Utility::platformName());
}
void Application::slotUseMonoIconsChanged(bool)
_gui->slotComputeOverallSyncStatus();
}
-void Application::slotParseMessage(const QString &msg, QObject*)
+void Application::slotParseMessage(const QString &msg, QObject *)
{
if (msg.startsWith(QLatin1String("MSG_PARSEOPTIONS:"))) {
const int lengthOfMsgPrefix = 17;
parseOptions(options);
setupLogging();
} else if (msg.startsWith(QLatin1String("MSG_SHOWSETTINGS"))) {
- qCInfo(lcApplication) << "Running for" << _startedAt.elapsed()/1000.0 << "sec";
- if (_startedAt.elapsed() < 10*1000) {
+ qCInfo(lcApplication) << "Running for" << _startedAt.elapsed() / 1000.0 << "sec";
+ if (_startedAt.elapsed() < 10 * 1000) {
// This call is mirrored with the one in int main()
qCWarning(lcApplication) << "Ignoring MSG_SHOWSETTINGS, possibly double-invocation of client via session restore and auto start";
return;
{
QStringListIterator it(options);
// skip file name;
- if (it.hasNext()) it.next();
+ if (it.hasNext())
+ it.next();
//parse options; if help or bad option exit
while (it.hasNext()) {
if (option == QLatin1String("--help") || option == QLatin1String("-h")) {
setHelp();
break;
- } else if (option == QLatin1String("--logwindow") ||
- option == QLatin1String("-l")) {
+ } else if (option == QLatin1String("--logwindow") || option == QLatin1String("-l")) {
_showLogWindow = true;
} else if (option == QLatin1String("--logfile")) {
if (it.hasNext() && !it.peekNext().startsWith(QLatin1String("--"))) {
- _logFile = it.next();
+ _logFile = it.next();
} else {
showHint("Log file not specified");
}
} else if (option == QLatin1String("--logdir")) {
if (it.hasNext() && !it.peekNext().startsWith(QLatin1String("--"))) {
- _logDir = it.next();
+ _logDir = it.next();
} else {
showHint("Log dir not specified");
}
} else if (option == QLatin1String("--confdir")) {
if (it.hasNext() && !it.peekNext().startsWith(QLatin1String("--"))) {
QString confDir = it.next();
- if (!ConfigFile::setConfDir( confDir )) {
+ if (!ConfigFile::setConfDir(confDir)) {
showHint("Invalid path passed to --confdir");
}
} else {
<< QLatin1String(" version ")
<< _theme->version().toLatin1().constData() << endl;
- stream << QLatin1String("File synchronisation desktop utility.") << endl << endl
+ stream << QLatin1String("File synchronisation desktop utility.") << endl
+ << endl
<< QLatin1String(optionsC);
if (_theme->appName() == QLatin1String("ownCloud"))
- stream << endl << "For more information, see http://www.owncloud.org" << endl << endl;
+ stream << endl
+ << "For more information, see http://www.owncloud.org" << endl
+ << endl;
displayHelpText(helpText);
}
void Application::setupTranslations()
{
QStringList uiLanguages;
- // uiLanguages crashes on Windows with 4.8.0 release builds
- #if (QT_VERSION >= 0x040801) || (QT_VERSION >= 0x040800 && !defined(Q_OS_WIN))
- uiLanguages = QLocale::system().uiLanguages();
- #else
- // older versions need to fall back to the systems locale
- uiLanguages << QLocale::system().name();
- #endif
+// uiLanguages crashes on Windows with 4.8.0 release builds
+#if (QT_VERSION >= 0x040801) || (QT_VERSION >= 0x040800 && !defined(Q_OS_WIN))
+ uiLanguages = QLocale::system().uiLanguages();
+#else
+ // older versions need to fall back to the systems locale
+ uiLanguages << QLocale::system().name();
+#endif
QString enforcedLocale = Theme::instance()->enforcedLocale();
if (!enforcedLocale.isEmpty())
QTranslator *qtTranslator = new QTranslator(this);
QTranslator *qtkeychainTranslator = new QTranslator(this);
- foreach(QString lang, uiLanguages) {
+ foreach (QString lang, uiLanguages) {
lang.replace(QLatin1Char('-'), QLatin1Char('_')); // work around QTBUG-25973
lang = substLang(lang);
const QString trPath = applicationTrPath();
const QString trFile = QLatin1String("client_") + lang;
- if (translator->load(trFile, trPath) ||
- lang.startsWith(QLatin1String("en"))) {
+ if (translator->load(trFile, trPath) || lang.startsWith(QLatin1String("en"))) {
// Permissive approach: Qt and keychain translations
// may be missing, but Qt translations must be there in order
// for us to accept the language. Otherwise, we try with the next.
} // namespace OCC
-
void slotownCloudWizardDone(int);
protected:
- void parseOptions(const QStringList& );
+ void parseOptions(const QStringList &);
void setupTranslations();
void setupLogging();
void enterNextLogFile();
signals:
void folderRemoved();
- void folderStateChanged(Folder*);
+ void folderStateChanged(Folder *);
protected slots:
- void slotParseMessage(const QString&, QObject*);
+ void slotParseMessage(const QString &, QObject *);
void slotCheckConnection();
- void slotUseMonoIconsChanged( bool );
+ void slotUseMonoIconsChanged(bool);
void slotCleanup();
void slotAccountStateAdded(AccountState *accountState);
void slotAccountStateRemoved(AccountState *accountState);
bool _showLogWindow;
QString _logFile;
QString _logDir;
- int _logExpire;
- bool _logFlush;
- bool _logDebug;
- bool _userTriggeredConnect;
- bool _debugMode;
+ int _logExpire;
+ bool _logFlush;
+ bool _logDebug;
+ bool _userTriggeredConnect;
+ bool _debugMode;
ClientProxy _proxy;
lay->addLayout(form);
_password->setEchoMode(QLineEdit::Password);
- QDialogButtonBox *box = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel, Qt::Horizontal);
+ QDialogButtonBox *box = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal);
connect(box, SIGNAL(accepted()), this, SLOT(accept()));
connect(box, SIGNAL(rejected()), this, SLOT(reject()));
lay->addWidget(box);
* @brief Authenticate a user for a specific credential given his credentials
* @ingroup gui
*/
-class AuthenticationDialog : public QDialog {
+class AuthenticationDialog : public QDialog
+{
Q_OBJECT
public:
AuthenticationDialog(const QString &realm, const QString &domain, QWidget *parent = 0);
private:
QLineEdit *_user;
QLineEdit *_password;
-
};
namespace OCC {
namespace Mac {
-/**
+ /**
* @brief CocoaInitializer provides an AutoRelease Pool via RIIA for use in main()
* @ingroup gui
*/
-class CocoaInitializer {
-public:
- CocoaInitializer();
- ~CocoaInitializer();
-private:
- class Private;
- Private *d;
-};
+ class CocoaInitializer
+ {
+ public:
+ CocoaInitializer();
+ ~CocoaInitializer();
+
+ private:
+ class Private;
+ Private *d;
+ };
} // namespace Mac
} // namespace OCC
#include "creds/shibbolethcredentials.h"
#endif
-namespace OCC
-{
+namespace OCC {
Q_LOGGING_CATEGORY(lcGuiCredentials, "gui.credentials", QtInfoMsg)
-namespace CredentialsFactory
-{
+namespace CredentialsFactory {
-AbstractCredentials* create(const QString& type)
-{
- // empty string might happen for old version of configuration
- if (type == "http" || type == "") {
- return new HttpCredentialsGui;
- } else if (type == "dummy") {
- return new DummyCredentials;
+ AbstractCredentials *create(const QString &type)
+ {
+ // empty string might happen for old version of configuration
+ if (type == "http" || type == "") {
+ return new HttpCredentialsGui;
+ } else if (type == "dummy") {
+ return new DummyCredentials;
#ifndef NO_SHIBBOLETH
- } else if (type == "shibboleth") {
- return new ShibbolethCredentials;
+ } else if (type == "shibboleth") {
+ return new ShibbolethCredentials;
#endif
- } else {
- qCWarning(lcGuiCredentials, "Unknown credentials type: %s", qPrintable(type));
- return new DummyCredentials;
+ } else {
+ qCWarning(lcGuiCredentials, "Unknown credentials type: %s", qPrintable(type));
+ return new DummyCredentials;
+ }
}
-}
} // ns CredentialsFactory
class QString;
-namespace OCC
-{
+namespace OCC {
class AbstractCredentials;
* @brief The HttpCredentialsGui namespace
* @ingroup gui
*/
-namespace CredentialsFactory
-{
+namespace CredentialsFactory {
-AbstractCredentials* create(const QString& type);
+ AbstractCredentials *create(const QString &type);
} // ns CredentialsFactory
using namespace QKeychain;
-namespace OCC
-{
+namespace OCC {
void HttpCredentialsGui::askFromUser()
{
"<br>"
"User: %2<br>"
"Account: %3<br>")
- .arg(Utility::escape(Theme::instance()->appNameGUI()),
- Utility::escape(_user),
- Utility::escape(_account->displayName()));
+ .arg(Utility::escape(Theme::instance()->appNameGUI()),
+ Utility::escape(_user),
+ Utility::escape(_account->displayName()));
QString reqTxt = requestAppPasswordText(_account);
if (!reqTxt.isEmpty()) {
}
if (!_fetchErrorString.isEmpty()) {
msg += QLatin1String("<br>")
- + tr("Reading from keychain failed with error: '%1'")
- .arg(Utility::escape(_fetchErrorString)) + QLatin1String("<br>");
+ + tr("Reading from keychain failed with error: '%1'")
+ .arg(Utility::escape(_fetchErrorString))
+ + QLatin1String("<br>");
}
QInputDialog dialog;
emit asked();
}
-QString HttpCredentialsGui::requestAppPasswordText(const Account* account)
+QString HttpCredentialsGui::requestAppPasswordText(const Account *account)
{
int version = account->serverVersionInt();
QString path;
#pragma once
#include "creds/httpcredentials.h"
-namespace OCC
-{
+namespace OCC {
/**
* @brief The HttpCredentialsGui class
* @ingroup gui
*/
-class HttpCredentialsGui : public HttpCredentials {
+class HttpCredentialsGui : public HttpCredentials
+{
Q_OBJECT
public:
- explicit HttpCredentialsGui() : HttpCredentials() {}
- HttpCredentialsGui(const QString& user, const QString& password, const QSslCertificate& certificate, const QSslKey& key) : HttpCredentials(user, password, certificate, key) {}
+ explicit HttpCredentialsGui()
+ : HttpCredentials()
+ {
+ }
+ HttpCredentialsGui(const QString &user, const QString &password, const QSslCertificate &certificate, const QSslKey &key)
+ : HttpCredentials(user, password, certificate, key)
+ {
+ }
void askFromUser() Q_DECL_OVERRIDE;
Q_INVOKABLE void askFromUserAsync();
};
} // namespace OCC
-
Q_DECLARE_LOGGING_CATEGORY(lcShibboleth)
-ShibbolethUserJob::ShibbolethUserJob(AccountPtr account, QObject* parent)
+ShibbolethUserJob::ShibbolethUserJob(AccountPtr account, QObject *parent)
: JsonApiJob(account, QLatin1String("ocs/v1.php/cloud/user"), parent)
{
setIgnoreCredentialFailure(true);
void ShibbolethUserJob::slotJsonReceived(const QJsonDocument &json, int statusCode)
{
- if( statusCode != 100 ) {
+ if (statusCode != 100) {
qCWarning(lcShibboleth) << "JSON Api call resulted in status code != 100";
}
- QString user = json.object().value("ocs").toObject().value("data").toObject().value("id").toString();
+ QString user = json.object().value("ocs").toObject().value("data").toObject().value("id").toString();
emit userFetched(user);
}
-
}
class QJsonDocument;
-namespace OCC
-{
+namespace OCC {
/**
* @brief Fetch the user name of the shibboleth connection
* @ingroup gui
*/
-class ShibbolethUserJob : public JsonApiJob {
+class ShibbolethUserJob : public JsonApiJob
+{
Q_OBJECT
public:
- explicit ShibbolethUserJob(AccountPtr account, QObject* parent = 0);
+ explicit ShibbolethUserJob(AccountPtr account, QObject *parent = 0);
signals:
// is always emitted when the job is finished. user is empty in case of error.
} // namespace OCC
-
#include "configfile.h"
namespace {
- const char ShibbolethWebViewGeometryC[] = "ShibbolethWebView/Geometry";
+const char ShibbolethWebViewGeometryC[] = "ShibbolethWebView/Geometry";
}
-namespace OCC
-{
+namespace OCC {
-class UserAgentWebPage : public QWebPage {
- public:
- UserAgentWebPage(QObject *parent) : QWebPage(parent)
+class UserAgentWebPage : public QWebPage
+{
+public:
+ UserAgentWebPage(QObject *parent)
+ : QWebPage(parent)
{
if (!qgetenv("OWNCLOUD_SHIBBOLETH_DEBUG").isEmpty()) {
settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, true);
}
}
- QString userAgentForUrl(const QUrl &url ) const {
+ QString userAgentForUrl(const QUrl &url) const
+ {
return QWebPage::userAgentForUrl(url) + " " + Utility::userAgentString();
}
};
-ShibbolethWebView::ShibbolethWebView(AccountPtr account, QWidget* parent)
+ShibbolethWebView::ShibbolethWebView(AccountPtr account, QWidget *parent)
: QWebView(parent)
, _account(account)
, _accepted(false)
setWindowFlags(Qt::Dialog);
setAttribute(Qt::WA_DeleteOnClose);
- QWebPage* page = new UserAgentWebPage(this);
+ QWebPage *page = new UserAgentWebPage(this);
connect(page, SIGNAL(loadStarted()),
- this, SLOT(slotLoadStarted()));
+ this, SLOT(slotLoadStarted()));
connect(page, SIGNAL(loadFinished(bool)),
- this, SLOT(slotLoadFinished(bool)));
+ this, SLOT(slotLoadFinished(bool)));
// Make sure to accept the same SSL certificate issues as the regular QNAM we use for syncing
- QObject::connect(page->networkAccessManager(), SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)),
- _account.data(), SLOT(slotHandleSslErrors(QNetworkReply*,QList<QSslError>)));
+ QObject::connect(page->networkAccessManager(), SIGNAL(sslErrors(QNetworkReply *, QList<QSslError>)),
+ _account.data(), SLOT(slotHandleSslErrors(QNetworkReply *, QList<QSslError>)));
// The Account keeps ownership of the cookie jar, it must outlive this webview.
account->lendCookieJarTo(page->networkAccessManager());
connect(page->networkAccessManager()->cookieJar(),
- SIGNAL(newCookiesForUrl (QList<QNetworkCookie>, QUrl)),
- this, SLOT(onNewCookiesForUrl (QList<QNetworkCookie>, QUrl)));
+ SIGNAL(newCookiesForUrl(QList<QNetworkCookie>, QUrl)),
+ this, SLOT(onNewCookiesForUrl(QList<QNetworkCookie>, QUrl)));
page->mainFrame()->load(account->url());
this->setPage(page);
setWindowTitle(tr("%1 - Authenticate").arg(Theme::instance()->appNameGUI()));
// Debug view to display the cipher suite
- if( !qgetenv("OWNCLOUD_SHIBBOLETH_DEBUG").isEmpty() ) {
+ if (!qgetenv("OWNCLOUD_SHIBBOLETH_DEBUG").isEmpty()) {
// open an additional window to display some cipher debug info
QWebPage *debugPage = new UserAgentWebPage(this);
- debugPage->mainFrame()->load( QUrl("https://cc.dcsec.uni-hannover.de/"));
+ debugPage->mainFrame()->load(QUrl("https://cc.dcsec.uni-hannover.de/"));
QWebView *debugView = new QWebView(this);
debugView->setPage(debugPage);
QMainWindow *window = new QMainWindow(this);
settings.setValue(ShibbolethWebViewGeometryC, saveGeometry());
}
-void ShibbolethWebView::onNewCookiesForUrl (const QList<QNetworkCookie>& cookieList, const QUrl& url)
+void ShibbolethWebView::onNewCookiesForUrl(const QList<QNetworkCookie> &cookieList, const QUrl &url)
{
if (url.host() == _account->url().host()) {
QNetworkCookie shibCookie = ShibbolethCredentials::findShibCookie(_account.data(), cookieList);
class QNetworkCookie;
class QUrl;
-namespace OCC
-{
+namespace OCC {
class ShibbolethCookieJar;
*/
class ShibbolethWebView : public QWebView
{
- Q_OBJECT
+ Q_OBJECT
public:
- ShibbolethWebView(AccountPtr account, QWidget* parent = 0);
- ShibbolethWebView(AccountPtr account, ShibbolethCookieJar* jar, QWidget* parent = 0);
- ~ShibbolethWebView();
+ ShibbolethWebView(AccountPtr account, QWidget *parent = 0);
+ ShibbolethWebView(AccountPtr account, ShibbolethCookieJar *jar, QWidget *parent = 0);
+ ~ShibbolethWebView();
- void closeEvent(QCloseEvent *event) Q_DECL_OVERRIDE;
+ void closeEvent(QCloseEvent *event) Q_DECL_OVERRIDE;
Q_SIGNALS:
- void shibbolethCookieReceived(const QNetworkCookie &cookie);
- void rejected();
+ void shibbolethCookieReceived(const QNetworkCookie &cookie);
+ void rejected();
private Q_SLOTS:
- void onNewCookiesForUrl(const QList<QNetworkCookie>& cookieList, const QUrl& url);
- void slotLoadStarted();
- void slotLoadFinished(bool success);
+ void onNewCookiesForUrl(const QList<QNetworkCookie> &cookieList, const QUrl &url);
+ void slotLoadStarted();
+ void slotLoadFinished(bool success);
protected:
- void accept();
+ void accept();
private:
- void setup(AccountPtr account, ShibbolethCookieJar* jar);
- AccountPtr _account;
- bool _accepted;
- bool _cursorOverriden;
+ void setup(AccountPtr account, ShibbolethCookieJar *jar);
+ AccountPtr _account;
+ bool _accepted;
+ bool _cursorOverriden;
};
} // namespace OCC
using namespace QKeychain;
-namespace OCC
-{
+namespace OCC {
Q_LOGGING_CATEGORY(lcShibboleth, "gui.credentials.shibboleth", QtInfoMsg)
-namespace
-{
+namespace {
-// Not "user" because it has a special meaning for http
-const char userC[] = "shib_user";
-const char shibCookieNameC[] = "_shibsession_";
+ // Not "user" because it has a special meaning for http
+ const char userC[] = "shib_user";
+ const char shibCookieNameC[] = "_shibsession_";
} // ns
ShibbolethCredentials::ShibbolethCredentials()
- : AbstractCredentials(),
- _url(),
- _ready(false),
- _stillValid(false),
- _browser(0)
-{}
-
-ShibbolethCredentials::ShibbolethCredentials(const QNetworkCookie& cookie)
- : _ready(true),
- _stillValid(true),
- _browser(0),
- _shibCookie(cookie)
+ : AbstractCredentials()
+ , _url()
+ , _ready(false)
+ , _stillValid(false)
+ , _browser(0)
+{
+}
+
+ShibbolethCredentials::ShibbolethCredentials(const QNetworkCookie &cookie)
+ : _ready(true)
+ , _stillValid(true)
+ , _browser(0)
+ , _shibCookie(cookie)
{
}
-void ShibbolethCredentials::setAccount(Account* account)
+void ShibbolethCredentials::setAccount(Account *account)
{
AbstractCredentials::setAccount(account);
return _user;
}
-QNetworkAccessManager* ShibbolethCredentials::getQNAM() const
+QNetworkAccessManager *ShibbolethCredentials::getQNAM() const
{
- QNetworkAccessManager* qnam(new AccessManager);
- connect(qnam, SIGNAL(finished(QNetworkReply*)),
- this, SLOT(slotReplyFinished(QNetworkReply*)));
+ QNetworkAccessManager *qnam(new AccessManager);
+ connect(qnam, SIGNAL(finished(QNetworkReply *)),
+ this, SLOT(slotReplyFinished(QNetworkReply *)));
return qnam;
}
-void ShibbolethCredentials::slotReplyFinished(QNetworkReply* r)
+void ShibbolethCredentials::slotReplyFinished(QNetworkReply *r)
{
if (!_browser.isNull()) {
return;
job->setSettings(Utility::settingsWithGroup(Theme::instance()->appName(), job).release());
job->setInsecureFallback(false);
job->setKey(keychainKey(_account->url().toString(), user()));
- connect(job, SIGNAL(finished(QKeychain::Job*)), SLOT(slotReadJobDone(QKeychain::Job*)));
+ connect(job, SIGNAL(finished(QKeychain::Job *)), SLOT(slotReadJobDone(QKeychain::Job *)));
job->start();
}
}
{
_ready = false;
- CookieJar *jar = static_cast<CookieJar*>(_account->networkAccessManager()->cookieJar());
+ CookieJar *jar = static_cast<CookieJar *>(_account->networkAccessManager()->cookieJar());
// Remove the _shibCookie
auto cookies = jar->allCookies();
- for (auto it = cookies.begin(); it != cookies.end(); ) {
+ for (auto it = cookies.begin(); it != cookies.end();) {
if (it->name() == _shibCookie.name()) {
it = cookies.erase(it);
} else {
invalidateToken();
}
-void ShibbolethCredentials::onShibbolethCookieReceived(const QNetworkCookie& shibCookie)
+void ShibbolethCredentials::onShibbolethCookieReceived(const QNetworkCookie &shibCookie)
{
storeShibCookie(shibCookie);
_shibCookie = shibCookie;
{
// We must first do a request to webdav so the session is enabled.
// (because for some reason we can't access the API without that.. a bug in the server maybe?)
- EntityExistsJob* job = new EntityExistsJob(_account->sharedFromThis(), _account->davPath(), this);
- connect(job, SIGNAL(exists(QNetworkReply*)), this, SLOT(slotFetchUserHelper()));
+ EntityExistsJob *job = new EntityExistsJob(_account->sharedFromThis(), _account->davPath(), this);
+ connect(job, SIGNAL(exists(QNetworkReply *)), this, SLOT(slotFetchUserHelper()));
job->setIgnoreCredentialFailure(true);
job->start();
}
void ShibbolethCredentials::slotReadJobDone(QKeychain::Job *job)
{
if (job->error() == QKeychain::NoError) {
- ReadPasswordJob *readJob = static_cast<ReadPasswordJob*>(job);
+ ReadPasswordJob *readJob = static_cast<ReadPasswordJob *>(job);
delete readJob->settings();
QList<QNetworkCookie> cookies = QNetworkCookie::parseCookies(readJob->textData().toUtf8());
if (cookies.count() > 0) {
return;
}
- CookieJar *jar = static_cast<CookieJar*>(_account->networkAccessManager()->cookieJar());
+ CookieJar *jar = static_cast<CookieJar *>(_account->networkAccessManager()->cookieJar());
// When opening a new window clear all the session cookie that might keep the user from logging in
// (or the session may already be open in the server, and there will not be redirect asking for the
// real long term cookie we want to store)
_browser = new ShibbolethWebView(_account->sharedFromThis());
connect(_browser, SIGNAL(shibbolethCookieReceived(QNetworkCookie)),
- this, SLOT(onShibbolethCookieReceived(QNetworkCookie)), Qt::QueuedConnection);
+ this, SLOT(onShibbolethCookieReceived(QNetworkCookie)), Qt::QueuedConnection);
connect(_browser, SIGNAL(rejected()), this, SLOT(slotBrowserRejected()));
ownCloudGui::raiseDialog(_browser);
}
-QList<QNetworkCookie> ShibbolethCredentials::accountCookies(Account* account)
+QList<QNetworkCookie> ShibbolethCredentials::accountCookies(Account *account)
{
return account->networkAccessManager()->cookieJar()->cookiesForUrl(account->davUrl());
}
-QNetworkCookie ShibbolethCredentials::findShibCookie(Account* account, QList<QNetworkCookie> cookies)
+QNetworkCookie ShibbolethCredentials::findShibCookie(Account *account, QList<QNetworkCookie> cookies)
{
- if(cookies.isEmpty()) {
+ if (cookies.isEmpty()) {
cookies = accountCookies(account);
}
- Q_FOREACH(QNetworkCookie cookie, cookies) {
+ Q_FOREACH (QNetworkCookie cookie, cookies) {
if (cookie.name().startsWith(shibCookieNameC)) {
return cookie;
}
#include "creds/abstractcredentials.h"
namespace QKeychain {
- class Job;
+class Job;
}
class QAuthenticator;
-namespace OCC
-{
+namespace OCC {
Q_DECLARE_LOGGING_CATEGORY(lcShibboleth)
*/
class ShibbolethCredentials : public AbstractCredentials
{
-Q_OBJECT
+ Q_OBJECT
public:
ShibbolethCredentials();
/* create credentials for an already connected account */
ShibbolethCredentials(const QNetworkCookie &cookie);
- void setAccount(Account* account) Q_DECL_OVERRIDE;
+ void setAccount(Account *account) Q_DECL_OVERRIDE;
QString authType() const Q_DECL_OVERRIDE;
QString user() const Q_DECL_OVERRIDE;
- QNetworkAccessManager* getQNAM() const Q_DECL_OVERRIDE;
+ QNetworkAccessManager *getQNAM() const Q_DECL_OVERRIDE;
bool ready() const Q_DECL_OVERRIDE;
void fetchFromKeychain() Q_DECL_OVERRIDE;
void askFromUser() Q_DECL_OVERRIDE;
static QByteArray shibCookieName();
private Q_SLOTS:
- void onShibbolethCookieReceived(const QNetworkCookie&);
+ void onShibbolethCookieReceived(const QNetworkCookie &);
void slotBrowserRejected();
- void slotReadJobDone(QKeychain::Job*);
- void slotReplyFinished(QNetworkReply*);
- void slotUserFetched(const QString& user);
+ void slotReadJobDone(QKeychain::Job *);
+ void slotReplyFinished(QNetworkReply *);
+ void slotUserFetched(const QString &user);
void slotFetchUser();
void slotFetchUserHelper();
Q_SIGNALS:
- void newCookie(const QNetworkCookie& cookie);
+ void newCookie(const QNetworkCookie &cookie);
private:
void storeShibCookie(const QNetworkCookie &cookie);
Q_LOGGING_CATEGORY(lcFolder, "gui.folder", QtInfoMsg)
-Folder::Folder(const FolderDefinition& definition,
- AccountState* accountState,
- QObject* parent)
+Folder::Folder(const FolderDefinition &definition,
+ AccountState *accountState,
+ QObject *parent)
: QObject(parent)
- , _accountState(accountState)
- , _definition(definition)
- , _csyncUnavail(false)
- , _proxyDirty(true)
- , _lastSyncDuration(0)
- , _consecutiveFailingSyncs(0)
- , _consecutiveFollowUpSyncs(0)
- , _journal(_definition.absoluteJournalPath())
- , _fileLog(new SyncRunFileLog)
- , _saveBackwardsCompatible(false)
+ , _accountState(accountState)
+ , _definition(definition)
+ , _csyncUnavail(false)
+ , _proxyDirty(true)
+ , _lastSyncDuration(0)
+ , _consecutiveFailingSyncs(0)
+ , _consecutiveFollowUpSyncs(0)
+ , _journal(_definition.absoluteJournalPath())
+ , _fileLog(new SyncRunFileLog)
+ , _saveBackwardsCompatible(false)
{
qsrand(QTime::currentTime().msec());
_timeSinceLastSyncStart.start();
connect(_accountState.data(), SIGNAL(isConnectedChanged()), this, SIGNAL(canSyncChanged()));
connect(_engine.data(), SIGNAL(rootEtag(QString)), this, SLOT(etagRetreivedFromSyncEngine(QString)));
- connect(_engine.data(), SIGNAL(started()), SLOT(slotSyncStarted()), Qt::QueuedConnection);
+ connect(_engine.data(), SIGNAL(started()), SLOT(slotSyncStarted()), Qt::QueuedConnection);
connect(_engine.data(), SIGNAL(finished(bool)), SLOT(slotSyncFinished(bool)), Qt::QueuedConnection);
connect(_engine.data(), SIGNAL(csyncError(QString)), SLOT(slotSyncError(QString)), Qt::QueuedConnection);
connect(_engine.data(), SIGNAL(csyncUnavailable()), SLOT(slotCsyncUnavailable()), Qt::QueuedConnection);
//direct connection so the message box is blocking the sync.
- connect(_engine.data(), SIGNAL(aboutToRemoveAllFiles(SyncFileItem::Direction,bool*)),
- SLOT(slotAboutToRemoveAllFiles(SyncFileItem::Direction,bool*)));
- connect(_engine.data(), SIGNAL(aboutToRestoreBackup(bool*)),
- SLOT(slotAboutToRestoreBackup(bool*)));
- connect(_engine.data(), SIGNAL(folderDiscovered(bool,QString)), this, SLOT(slotFolderDiscovered(bool,QString)));
+ connect(_engine.data(), SIGNAL(aboutToRemoveAllFiles(SyncFileItem::Direction, bool *)),
+ SLOT(slotAboutToRemoveAllFiles(SyncFileItem::Direction, bool *)));
+ connect(_engine.data(), SIGNAL(aboutToRestoreBackup(bool *)),
+ SLOT(slotAboutToRestoreBackup(bool *)));
+ connect(_engine.data(), SIGNAL(folderDiscovered(bool, QString)), this, SLOT(slotFolderDiscovered(bool, QString)));
connect(_engine.data(), SIGNAL(transmissionProgress(ProgressInfo)), this, SLOT(slotTransmissionProgress(ProgressInfo)));
connect(_engine.data(), SIGNAL(itemCompleted(const SyncFileItemPtr &)),
- this, SLOT(slotItemCompleted(const SyncFileItemPtr &)));
- connect(_engine.data(), SIGNAL(newBigFolder(QString,bool)),
- this, SLOT(slotNewBigFolderDiscovered(QString,bool)));
+ this, SLOT(slotItemCompleted(const SyncFileItemPtr &)));
+ connect(_engine.data(), SIGNAL(newBigFolder(QString, bool)),
+ this, SLOT(slotNewBigFolderDiscovered(QString, bool)));
connect(_engine.data(), SIGNAL(seenLockedFile(QString)), FolderMan::instance(), SLOT(slotSyncOnceFileUnlocks(QString)));
- connect(_engine.data(), SIGNAL(aboutToPropagate(SyncFileItemVector&)),
- SLOT(slotLogPropagationStart()));
+ connect(_engine.data(), SIGNAL(aboutToPropagate(SyncFileItemVector &)),
+ SLOT(slotLogPropagationStart()));
_scheduleSelfTimer.setSingleShot(true);
_scheduleSelfTimer.setInterval(SyncEngine::minimumFileAgeForUpload);
connect(&_scheduleSelfTimer, SIGNAL(timeout()),
- SLOT(slotScheduleThisFolder()));
+ SLOT(slotScheduleThisFolder()));
}
Folder::~Folder()
if (_canonicalLocalPath.isEmpty()) {
qCWarning(lcFolder) << "Broken symlink:" << _definition.localPath;
_canonicalLocalPath = _definition.localPath;
- } else if( !_canonicalLocalPath.endsWith('/') ) {
+ } else if (!_canonicalLocalPath.endsWith('/')) {
_canonicalLocalPath.append('/');
}
- if( fi.isDir() && fi.isReadable() ) {
+ if (fi.isDir() && fi.isReadable()) {
qCDebug(lcFolder) << "Checked local path ok";
} else {
// Check directory again
- if( !FileSystem::fileExists(_definition.localPath, fi) ) {
+ if (!FileSystem::fileExists(_definition.localPath, fi)) {
_syncResult.appendErrorString(tr("Local folder %1 does not exist.").arg(_definition.localPath));
- _syncResult.setStatus( SyncResult::SetupError );
- } else if( !fi.isDir() ) {
+ _syncResult.setStatus(SyncResult::SetupError);
+ } else if (!fi.isDir()) {
_syncResult.appendErrorString(tr("%1 should be a folder but is not.").arg(_definition.localPath));
- _syncResult.setStatus( SyncResult::SetupError );
- } else if( !fi.isReadable() ) {
+ _syncResult.setStatus(SyncResult::SetupError);
+ } else if (!fi.isReadable()) {
_syncResult.appendErrorString(tr("%1 is not readable.").arg(_definition.localPath));
- _syncResult.setStatus( SyncResult::SetupError );
+ _syncResult.setStatus(SyncResult::SetupError);
}
}
}
{
QString p = _definition.localPath;
QString home = QDir::homePath();
- if( ! home.endsWith('/') ) {
+ if (!home.endsWith('/')) {
home.append('/');
}
if (p.startsWith(home)) {
{
QString cleanedPath = QDir::cleanPath(_canonicalLocalPath);
- if(cleanedPath.length() == 3 && cleanedPath.endsWith(":/"))
- cleanedPath.remove(2,1);
+ if (cleanedPath.length() == 3 && cleanedPath.endsWith(":/"))
+ cleanedPath.remove(2, 1);
return cleanedPath;
}
bool Folder::syncPaused() const
{
- return _definition.paused;
+ return _definition.paused;
}
bool Folder::canSync() const
return !syncPaused() && accountState()->isConnected();
}
-void Folder::setSyncPaused( bool paused )
+void Folder::setSyncPaused(bool paused)
{
if (paused == _definition.paused) {
return;
_definition.paused = paused;
saveToSettings();
- if( !paused ) {
+ if (!paused) {
setSyncState(SyncResult::NotYetStarted);
} else {
setSyncState(SyncResult::Paused);
SyncResult Folder::syncResult() const
{
- return _syncResult;
+ return _syncResult;
}
void Folder::prepareToSync()
{
_syncResult.reset();
- _syncResult.setStatus( SyncResult::NotYetStarted );
+ _syncResult.setStatus(SyncResult::NotYetStarted);
}
void Folder::slotRunEtagJob()
}
if (!canSync()) {
- qCInfo(lcFolder) << "Not syncing. :" << remoteUrl().toString() << _definition.paused << AccountState::stateString(_accountState->state());
+ qCInfo(lcFolder) << "Not syncing. :" << remoteUrl().toString() << _definition.paused << AccountState::stateString(_accountState->state());
return;
}
// sync if it's different.
_requestEtagJob = new RequestEtagJob(account, remotePath(), this);
- _requestEtagJob->setTimeout(60*1000);
+ _requestEtagJob->setTimeout(60 * 1000);
// check if the etag is different when retrieved
QObject::connect(_requestEtagJob, SIGNAL(etagRetreived(QString)), this, SLOT(etagRetreived(QString)));
FolderMan::instance()->slotScheduleETagJob(alias(), _requestEtagJob);
// The _requestEtagJob is auto deleting itself on finish. Our guard pointer _requestEtagJob will then be null.
}
-void Folder::etagRetreived(const QString& etag)
+void Folder::etagRetreived(const QString &etag)
{
// re-enable sync if it was disabled because network was down
FolderMan::instance()->setSyncEnabled(true);
_accountState->tagLastSuccessfullETagRequest();
}
-void Folder::etagRetreivedFromSyncEngine(const QString& etag)
+void Folder::etagRetreivedFromSyncEngine(const QString &etag)
{
qCInfo(lcFolder) << "Root etag from during sync:" << etag;
accountState()->tagLastSuccessfullETagRequest();
void Folder::showSyncResultPopup()
{
- if( _syncResult.firstItemNew() ) {
- createGuiLog( _syncResult.firstItemNew()->_file, LogStatusNew, _syncResult.numNewItems() );
+ if (_syncResult.firstItemNew()) {
+ createGuiLog(_syncResult.firstItemNew()->_file, LogStatusNew, _syncResult.numNewItems());
}
- if( _syncResult.firstItemDeleted() ) {
- createGuiLog( _syncResult.firstItemDeleted()->_file, LogStatusRemove, _syncResult.numRemovedItems() );
+ if (_syncResult.firstItemDeleted()) {
+ createGuiLog(_syncResult.firstItemDeleted()->_file, LogStatusRemove, _syncResult.numRemovedItems());
}
- if( _syncResult.firstItemUpdated() ) {
- createGuiLog( _syncResult.firstItemUpdated()->_file, LogStatusUpdated, _syncResult.numUpdatedItems() );
+ if (_syncResult.firstItemUpdated()) {
+ createGuiLog(_syncResult.firstItemUpdated()->_file, LogStatusUpdated, _syncResult.numUpdatedItems());
}
- if( _syncResult.firstItemRenamed() ) {
+ if (_syncResult.firstItemRenamed()) {
LogStatus status(LogStatusRename);
// if the path changes it's rather a move
QDir renTarget = QFileInfo(_syncResult.firstItemRenamed()->_renameTarget).dir();
QDir renSource = QFileInfo(_syncResult.firstItemRenamed()->_file).dir();
- if(renTarget != renSource) {
+ if (renTarget != renSource) {
status = LogStatusMove;
}
- createGuiLog( _syncResult.firstItemRenamed()->_originalFile, status,
- _syncResult.numRenamedItems(), _syncResult.firstItemRenamed()->_renameTarget );
+ createGuiLog(_syncResult.firstItemRenamed()->_originalFile, status,
+ _syncResult.numRenamedItems(), _syncResult.firstItemRenamed()->_renameTarget);
}
- if( _syncResult.firstConflictItem() ) {
- createGuiLog( _syncResult.firstConflictItem()->_file, LogStatusConflict, _syncResult.numConflictItems() );
+ if (_syncResult.firstConflictItem()) {
+ createGuiLog(_syncResult.firstConflictItem()->_file, LogStatusConflict, _syncResult.numConflictItems());
}
if (int errorCount = _syncResult.numErrorItems()) {
- createGuiLog( _syncResult.firstItemError()->_file, LogStatusError, errorCount );
+ createGuiLog(_syncResult.firstItemError()->_file, LogStatusError, errorCount);
}
qCInfo(lcFolder) << "Folder sync result: " << int(_syncResult.status());
}
-void Folder::createGuiLog( const QString& filename, LogStatus status, int count,
- const QString& renameTarget )
+void Folder::createGuiLog(const QString &filename, LogStatus status, int count,
+ const QString &renameTarget)
{
- if(count > 0) {
+ if (count > 0) {
Logger *logger = Logger::instance();
QString file = QDir::toNativeSeparators(filename);
switch (status) {
case LogStatusRemove:
- if( count > 1 ) {
- text = tr("%1 and %n other file(s) have been removed.", "", count-1).arg(file);
+ if (count > 1) {
+ text = tr("%1 and %n other file(s) have been removed.", "", count - 1).arg(file);
} else {
text = tr("%1 has been removed.", "%1 names a file.").arg(file);
}
break;
case LogStatusNew:
- if( count > 1 ) {
- text = tr("%1 and %n other file(s) have been downloaded.", "", count-1).arg(file);
+ if (count > 1) {
+ text = tr("%1 and %n other file(s) have been downloaded.", "", count - 1).arg(file);
} else {
text = tr("%1 has been downloaded.", "%1 names a file.").arg(file);
}
break;
case LogStatusUpdated:
- if( count > 1 ) {
- text = tr("%1 and %n other file(s) have been updated.", "", count-1).arg(file);
+ if (count > 1) {
+ text = tr("%1 and %n other file(s) have been updated.", "", count - 1).arg(file);
} else {
text = tr("%1 has been updated.", "%1 names a file.").arg(file);
}
break;
case LogStatusRename:
- if( count > 1 ) {
- text = tr("%1 has been renamed to %2 and %n other file(s) have been renamed.", "", count-1).arg(file, renameTarget);
+ if (count > 1) {
+ text = tr("%1 has been renamed to %2 and %n other file(s) have been renamed.", "", count - 1).arg(file, renameTarget);
} else {
text = tr("%1 has been renamed to %2.", "%1 and %2 name files.").arg(file, renameTarget);
}
break;
case LogStatusMove:
- if( count > 1 ) {
- text = tr("%1 has been moved to %2 and %n other file(s) have been moved.", "", count-1).arg(file, renameTarget);
+ if (count > 1) {
+ text = tr("%1 has been moved to %2 and %n other file(s) have been moved.", "", count - 1).arg(file, renameTarget);
} else {
text = tr("%1 has been moved to %2.").arg(file, renameTarget);
}
break;
case LogStatusConflict:
- if( count > 1 ) {
- text = tr("%1 has and %n other file(s) have sync conflicts.", "", count-1).arg(file);
+ if (count > 1) {
+ text = tr("%1 has and %n other file(s) have sync conflicts.", "", count - 1).arg(file);
} else {
text = tr("%1 has a sync conflict. Please check the conflict file!").arg(file);
}
break;
case LogStatusError:
- if( count > 1 ) {
- text = tr("%1 and %n other file(s) could not be synced due to errors. See the log for details.", "", count-1).arg(file);
+ if (count > 1) {
+ text = tr("%1 and %n other file(s) could not be synced due to errors. See the log for details.", "", count - 1).arg(file);
} else {
text = tr("%1 could not be synced due to an error. See the log for details.").arg(file);
}
break;
}
- if( !text.isEmpty() ) {
- logger->postOptionalGuiLog( tr("Sync Activity"), text );
+ if (!text.isEmpty()) {
+ logger->postOptionalGuiLog(tr("Sync Activity"), text);
}
}
}
QDir folderpath(_definition.localPath);
QSet<QString> keep_nothing;
const QVector<SyncJournalDb::DownloadInfo> deleted_infos =
- _journal.getAndDeleteStaleDownloadInfos(keep_nothing);
- foreach (const SyncJournalDb::DownloadInfo & deleted_info, deleted_infos) {
+ _journal.getAndDeleteStaleDownloadInfos(keep_nothing);
+ foreach (const SyncJournalDb::DownloadInfo &deleted_info, deleted_infos) {
const QString tmppath = folderpath.filePath(deleted_info._tmpfile);
qCInfo(lcFolder) << "Deleting temporary file: " << tmppath;
FileSystem::remove(tmppath);
return _journal.wipeErrorBlacklist();
}
-void Folder::slotWatchedPathChanged(const QString& path)
+void Folder::slotWatchedPathChanged(const QString &path)
{
- // The folder watcher fires a lot of bogus notifications during
- // a sync operation, both for actual user files and the database
- // and log. Therefore we check notifications against operations
- // the sync is doing to filter out our own changes.
+// The folder watcher fires a lot of bogus notifications during
+// a sync operation, both for actual user files and the database
+// and log. Therefore we check notifications against operations
+// the sync is doing to filter out our own changes.
#ifdef Q_OS_MAC
Q_UNUSED(path)
- // On OSX the folder watcher does not report changes done by our
- // own process. Therefore nothing needs to be done here!
+// On OSX the folder watcher does not report changes done by our
+// own process. Therefore nothing needs to be done here!
#else
// Use the path to figure out whether it was our own change
- const auto maxNotificationDelay = 15*1000;
+ const auto maxNotificationDelay = 15 * 1000;
qint64 time = _engine->timeSinceFileTouched(path);
if (time != -1 && time < maxNotificationDelay) {
return;
if (path.startsWith(this->path())) {
auto relativePath = path.mid(this->path().size());
auto record = _journal.getFileRecord(relativePath);
- if (record.isValid() && !FileSystem::fileChanged(path, record._fileSize,
- Utility::qDateTimeToTime_t(record._modtime))) {
+ if (record.isValid() && !FileSystem::fileChanged(path, record._fileSize, Utility::qDateTimeToTime_t(record._modtime))) {
qCInfo(lcFolder) << "Ignoring spurious notification for file" << relativePath;
- return; // probably a spurious notification
+ return; // probably a spurious notification
}
}
// where two folders for different accounts point at the same
// local folders.
bool oneAccountOnly = true;
- foreach (Folder* other, FolderMan::instance()->map()) {
+ foreach (Folder *other, FolderMan::instance()->map()) {
if (other != this && other->cleanPath() == this->cleanPath()) {
oneAccountOnly = false;
break;
settings->remove(FolderMan::escapeAlias(_definition.alias));
}
-bool Folder::isFileExcludedAbsolute(const QString& fullPath) const
+bool Folder::isFileExcludedAbsolute(const QString &fullPath) const
{
return _engine->excludedFiles().isExcluded(fullPath, path(), _definition.ignoreHiddenFiles);
}
-bool Folder::isFileExcludedRelative(const QString& relativePath) const
+bool Folder::isFileExcludedRelative(const QString &relativePath) const
{
return _engine->excludedFiles().isExcluded(path() + relativePath, path(), _definition.ignoreHiddenFiles);
}
{
qCInfo(lcFolder) << "folder " << alias() << " Terminating!";
- if( _engine->isSyncRunning() ) {
+ if (_engine->isSyncRunning()) {
_engine->abort();
setSyncState(SyncResult::SyncAbortRequested);
_journal.close(); // close the sync journal
QFile file(stateDbFile);
- if( file.exists() ) {
- if( !file.remove()) {
+ if (file.exists()) {
+ if (!file.remove()) {
qCWarning(lcFolder) << "Failed to remove existing csync StateDB " << stateDbFile;
} else {
qCInfo(lcFolder) << "wipe: Removed csync StateDB " << stateDbFile;
}
// Also remove other db related files
- QFile::remove( stateDbFile + ".ctmp" );
- QFile::remove( stateDbFile + "-shm" );
- QFile::remove( stateDbFile + "-wal" );
- QFile::remove( stateDbFile + "-journal" );
+ QFile::remove(stateDbFile + ".ctmp");
+ QFile::remove(stateDbFile + "-shm");
+ QFile::remove(stateDbFile + "-wal");
+ QFile::remove(stateDbFile + "-journal");
if (canSync())
FolderMan::instance()->socketApi()->slotRegisterPath(alias());
_engine->excludedFiles().addExcludeFilePath(systemList);
QString userList = cfg.excludeFile(ConfigFile::UserScope);
- if( QFile::exists(userList) ) {
+ if (QFile::exists(userList)) {
qCInfo(lcFolder) << "Adding user defined ignore list to csync:" << userList;
_engine->excludedFiles().addExcludeFilePath(userList);
}
_csyncUnavail = false;
_timeSinceLastSyncStart.restart();
- _syncResult.setStatus( SyncResult::SyncPrepare );
+ _syncResult.setStatus(SyncResult::SyncPrepare);
emit syncStateChange();
qCInfo(lcFolder) << "*** Start syncing " << remoteUrl().toString() << " - client version"
- << qPrintable(Theme::instance()->version());
+ << qPrintable(Theme::instance()->version());
_fileLog->start(path());
- if (!setIgnoredFiles())
- {
+ if (!setIgnoredFiles()) {
slotSyncError(tr("Could not read system exclude file"));
QMetaObject::invokeMethod(this, "slotSyncFinished", Qt::QueuedConnection, Q_ARG(bool, false));
return;
int uploadLimit = -75; // 75%
int useUpLimit = cfg.useUploadLimit();
- if ( useUpLimit >= 1) {
+ if (useUpLimit >= 1) {
uploadLimit = cfg.uploadLimit() * 1000;
} else if (useUpLimit == 0) {
uploadLimit = 0;
}
-void Folder::slotSyncError(const QString& err)
+void Folder::slotSyncError(const QString &err)
{
_syncResult.appendErrorString(err);
}
void Folder::slotSyncFinished(bool success)
{
qCInfo(lcFolder) << "Client version" << qPrintable(Theme::instance()->version())
- << " Qt" << qVersion()
-#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
- << " SSL " << QSslSocket::sslLibraryVersionString().toUtf8().data()
+ << " Qt" << qVersion()
+#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
+ << " SSL " << QSslSocket::sslLibraryVersionString().toUtf8().data()
#endif
- ;
+ ;
bool syncError = !_syncResult.errorStrings().isEmpty();
- if( syncError ) {
+ if (syncError) {
qCWarning(lcFolder) << "SyncEngine finished with ERROR";
} else {
qCInfo(lcFolder) << "SyncEngine finished without problem.";
} else if (_csyncUnavail) {
_syncResult.setStatus(SyncResult::Error);
qCWarning(lcFolder) << "csync not available.";
- } else if( _syncResult.foundFilesNotSynced() ) {
+ } else if (_syncResult.foundFilesNotSynced()) {
_syncResult.setStatus(SyncResult::Problem);
- } else if( _definition.paused ) {
+ } else if (_definition.paused) {
// Maybe the sync was terminated because the user paused the folder
_syncResult.setStatus(SyncResult::Paused);
} else {
// Count the number of syncs that have failed in a row.
if (_syncResult.status() == SyncResult::Success
- || _syncResult.status() == SyncResult::Problem)
- {
+ || _syncResult.status() == SyncResult::Problem) {
_consecutiveFailingSyncs = 0;
- }
- else
- {
+ } else {
_consecutiveFailingSyncs++;
qCInfo(lcFolder) << "the last" << _consecutiveFailingSyncs << "syncs failed";
}
// file system change notifications are ignored for that folder. And it takes
// some time under certain conditions to make the file system notifications
// all come in.
- QTimer::singleShot(200, this, SLOT(slotEmitFinishedDelayed() ));
+ QTimer::singleShot(200, this, SLOT(slotEmitFinishedDelayed()));
_lastSyncDuration = _timeSinceLastSyncStart.elapsed();
_timeSinceLastSyncDone.restart();
if (anotherSyncNeeded == ImmediateFollowUp) {
_consecutiveFollowUpSyncs++;
qCInfo(lcFolder) << "another sync was requested by the finished sync, this has"
- << "happened" << _consecutiveFollowUpSyncs << "times";
+ << "happened" << _consecutiveFollowUpSyncs << "times";
} else {
_consecutiveFollowUpSyncs = 0;
}
// Maybe force a follow-up sync to take place, but only a couple of times.
- if (anotherSyncNeeded == ImmediateFollowUp && _consecutiveFollowUpSyncs <= 3)
- {
+ if (anotherSyncNeeded == ImmediateFollowUp && _consecutiveFollowUpSyncs <= 3) {
// Sometimes another sync is requested because a local file is still
// changing, so wait at least a small amount of time before syncing
// the folder again.
void Folder::slotEmitFinishedDelayed()
{
- emit syncFinished( _syncResult );
+ emit syncFinished(_syncResult);
}
void Folder::slotItemCompleted(const SyncFileItemPtr &item)
{
// add new directories or remove gone away dirs to the watcher
- if (item->_isDirectory && item->_instruction == CSYNC_INSTRUCTION_NEW ) {
- FolderMan::instance()->addMonitorPath( alias(), path()+item->_file );
+ if (item->_isDirectory && item->_instruction == CSYNC_INSTRUCTION_NEW) {
+ FolderMan::instance()->addMonitorPath(alias(), path() + item->_file);
}
- if (item->_isDirectory && item->_instruction == CSYNC_INSTRUCTION_REMOVE ) {
- FolderMan::instance()->removeMonitorPath( alias(), path()+item->_file );
+ if (item->_isDirectory && item->_instruction == CSYNC_INSTRUCTION_REMOVE) {
+ FolderMan::instance()->removeMonitorPath(alias(), path() + item->_file);
}
_syncResult.processCompletedItem(item);
// And add the entry to the undecided list and signal the UI
auto undecidedList = journal->getSelectiveSyncList(SyncJournalDb::SelectiveSyncUndecidedList, &ok1);
- if( ok1 ) {
+ if (ok1) {
if (!undecidedList.contains(newFolder)) {
undecidedList.append(newFolder);
journal->setSelectiveSyncList(SyncJournalDb::SelectiveSyncUndecidedList, undecidedList);
emit newBigFolderDiscovered(newFolder);
}
- QString message = !isExternal ?
- (tr("A new folder larger than %1 MB has been added: %2.\n")
- .arg(ConfigFile().newBigFolderSizeLimit().second).arg(newF))
- : (tr("A folder from an external storage has been added.\n"));
+ QString message = !isExternal ? (tr("A new folder larger than %1 MB has been added: %2.\n")
+ .arg(ConfigFile().newBigFolderSizeLimit().second)
+ .arg(newF))
+ : (tr("A folder from an external storage has been added.\n"));
message += tr("Please go in the settings to select it if you wish to download it.");
auto logger = Logger::instance();
if (!cfgFile.promptDeleteFiles())
return;
- QString msg = dir == SyncFileItem::Down ?
- tr("All files in the sync folder '%1' folder were deleted on the server.\n"
- "These deletes will be synchronized to your local sync folder, making such files "
- "unavailable unless you have a right to restore. \n"
- "If you decide to keep the files, they will be re-synced with the server if you have rights to do so.\n"
- "If you decide to delete the files, they will be unavailable to you, unless you are the owner.") :
- tr("All the files in your local sync folder '%1' were deleted. These deletes will be "
- "synchronized with your server, making such files unavailable unless restored.\n"
- "Are you sure you want to sync those actions with the server?\n"
- "If this was an accident and you decide to keep your files, they will be re-synced from the server.");
+ QString msg = dir == SyncFileItem::Down ? tr("All files in the sync folder '%1' folder were deleted on the server.\n"
+ "These deletes will be synchronized to your local sync folder, making such files "
+ "unavailable unless you have a right to restore. \n"
+ "If you decide to keep the files, they will be re-synced with the server if you have rights to do so.\n"
+ "If you decide to delete the files, they will be unavailable to you, unless you are the owner.")
+ : tr("All the files in your local sync folder '%1' were deleted. These deletes will be "
+ "synchronized with your server, making such files unavailable unless restored.\n"
+ "Are you sure you want to sync those actions with the server?\n"
+ "If this was an accident and you decide to keep your files, they will be re-synced from the server.");
QMessageBox msgBox(QMessageBox::Warning, tr("Remove All Files?"),
- msg.arg(shortGuiLocalPath()));
+ msg.arg(shortGuiLocalPath()));
msgBox.setWindowFlags(msgBox.windowFlags() | Qt::WindowStaysOnTopHint);
msgBox.addButton(tr("Remove all files"), QMessageBox::DestructiveRole);
- QPushButton* keepBtn = msgBox.addButton(tr("Keep files"), QMessageBox::AcceptRole);
+ QPushButton *keepBtn = msgBox.addButton(tr("Keep files"), QMessageBox::AcceptRole);
if (msgBox.exec() == -1) {
*cancel = true;
return;
"file in an earlier state. "
"Do you want to keep your local most recent files as conflict files?");
QMessageBox msgBox(QMessageBox::Warning, tr("Backup detected"),
- msg.arg(shortGuiLocalPath()));
+ msg.arg(shortGuiLocalPath()));
msgBox.setWindowFlags(msgBox.windowFlags() | Qt::WindowStaysOnTopHint);
msgBox.addButton(tr("Normal Synchronisation"), QMessageBox::DestructiveRole);
- QPushButton* keepBtn = msgBox.addButton(tr("Keep Local Files as Conflict"), QMessageBox::AcceptRole);
+ QPushButton *keepBtn = msgBox.addButton(tr("Keep Local Files as Conflict"), QMessageBox::AcceptRole);
if (msgBox.exec() == -1) {
*restore = true;
}
-void FolderDefinition::save(QSettings& settings, const FolderDefinition& folder)
+void FolderDefinition::save(QSettings &settings, const FolderDefinition &folder)
{
settings.beginGroup(FolderMan::escapeAlias(folder.alias));
settings.setValue(QLatin1String("localPath"), folder.localPath);
settings.endGroup();
}
-bool FolderDefinition::load(QSettings& settings, const QString& alias,
- FolderDefinition* folder)
+bool FolderDefinition::load(QSettings &settings, const QString &alias,
+ FolderDefinition *folder)
{
settings.beginGroup(alias);
folder->alias = FolderMan::unescapeAlias(alias);
return true;
}
-QString FolderDefinition::prepareLocalPath(const QString& path)
+QString FolderDefinition::prepareLocalPath(const QString &path)
{
QString p = QDir::fromNativeSeparators(path);
if (!p.endsWith(QLatin1Char('/'))) {
}
} // namespace OCC
-
FolderDefinition()
: paused(false)
, ignoreHiddenFiles(true)
- {}
+ {
+ }
/// The name of the folder in the ui and internally
QString alias;
bool ignoreHiddenFiles;
/// Saves the folder definition, creating a new settings group.
- static void save(QSettings& settings, const FolderDefinition& folder);
+ static void save(QSettings &settings, const FolderDefinition &folder);
/// Reads a folder definition from a settings group with the name 'alias'.
- static bool load(QSettings& settings, const QString& alias,
- FolderDefinition* folder);
+ static bool load(QSettings &settings, const QString &alias,
+ FolderDefinition *folder);
/// Ensure / as separator and trailing /.
- static QString prepareLocalPath(const QString& path);
+ static QString prepareLocalPath(const QString &path);
/// Ensure starting / and no ending /.
- static QString prepareTargetPath(const QString& path);
+ static QString prepareTargetPath(const QString &path);
/// journalPath relative to localPath.
QString absoluteJournalPath() const;
Q_OBJECT
public:
- Folder(const FolderDefinition& definition, AccountState* accountState, QObject* parent = 0L);
+ Folder(const FolderDefinition &definition, AccountState *accountState, QObject *parent = 0L);
~Folder();
- typedef QMap<QString, Folder*> Map;
- typedef QMapIterator<QString, Folder*> MapIterator;
+ typedef QMap<QString, Folder *> Map;
+ typedef QMapIterator<QString, Folder *> MapIterator;
/**
* The account the folder is configured on.
*/
- AccountState* accountState() const { return _accountState.data(); }
+ AccountState *accountState() const { return _accountState.data(); }
/**
* alias or nickname
/**
* switch sync on or off
*/
- void setSyncPaused( bool );
+ void setSyncPaused(bool);
bool syncPaused() const;
/**
* return the last sync result with error message and status
*/
- SyncResult syncResult() const;
+ SyncResult syncResult() const;
- /**
+ /**
* set the config file name.
*/
- void setConfigFile( const QString& );
- QString configFile();
+ void setConfigFile(const QString &);
+ QString configFile();
- /**
+ /**
* This is called if the sync folder definition is removed. Do cleanups here.
*/
- virtual void wipe();
+ virtual void wipe();
- void setSyncState(SyncResult::Status state);
+ void setSyncState(SyncResult::Status state);
- void setDirtyNetworkLimits();
+ void setDirtyNetworkLimits();
- /**
+ /**
* Ignore syncing of hidden files or not. This is defined in the
* folder definition
*/
- bool ignoreHiddenFiles();
- void setIgnoreHiddenFiles(bool ignore);
+ bool ignoreHiddenFiles();
+ void setIgnoreHiddenFiles(bool ignore);
- // Used by the Socket API
- SyncJournalDb *journalDb() { return &_journal; }
- SyncEngine &syncEngine() { return *_engine; }
+ // Used by the Socket API
+ SyncJournalDb *journalDb() { return &_journal; }
+ SyncEngine &syncEngine() { return *_engine; }
- RequestEtagJob *etagJob() { return _requestEtagJob; }
- qint64 msecSinceLastSync() const { return _timeSinceLastSyncDone.elapsed(); }
- qint64 msecLastSyncDuration() const { return _lastSyncDuration; }
- int consecutiveFollowUpSyncs() const { return _consecutiveFollowUpSyncs; }
- int consecutiveFailingSyncs() const { return _consecutiveFailingSyncs; }
+ RequestEtagJob *etagJob() { return _requestEtagJob; }
+ qint64 msecSinceLastSync() const { return _timeSinceLastSyncDone.elapsed(); }
+ qint64 msecLastSyncDuration() const { return _lastSyncDuration; }
+ int consecutiveFollowUpSyncs() const { return _consecutiveFollowUpSyncs; }
+ int consecutiveFailingSyncs() const { return _consecutiveFailingSyncs; }
- /// Saves the folder data in the account's settings.
- void saveToSettings() const;
- /// Removes the folder from the account's settings.
- void removeFromSettings() const;
+ /// Saves the folder data in the account's settings.
+ void saveToSettings() const;
+ /// Removes the folder from the account's settings.
+ void removeFromSettings() const;
- /**
+ /**
* Returns whether a file inside this folder should be excluded.
*/
- bool isFileExcludedAbsolute(const QString& fullPath) const;
+ bool isFileExcludedAbsolute(const QString &fullPath) const;
- /**
+ /**
* Returns whether a file inside this folder should be excluded.
*/
- bool isFileExcludedRelative(const QString& relativePath) const;
+ bool isFileExcludedRelative(const QString &relativePath) const;
- /** Calls schedules this folder on the FolderMan after a short delay.
+ /** Calls schedules this folder on the FolderMan after a short delay.
*
* This should be used in situations where a sync should be triggered
* because a local file was modified. Syncs don't upload files that were
*
* The delay doesn't reset with subsequent calls.
*/
- void scheduleThisFolderSoon();
+ void scheduleThisFolderSoon();
- /**
+ /**
* Migration: When this flag is true, this folder will save to
* the backwards-compatible 'Folders' section in the config file.
*/
- void setSaveBackwardsCompatible(bool save);
+ void setSaveBackwardsCompatible(bool save);
signals:
void syncStateChange();
void syncStarted();
void syncFinished(const SyncResult &result);
- void progressInfo(const ProgressInfo& progress);
+ void progressInfo(const ProgressInfo &progress);
void newBigFolderDiscovered(const QString &); // A new folder bigger than the threshold was discovered
- void syncPausedChanged(Folder*, bool paused);
+ void syncPausedChanged(Folder *, bool paused);
void canSyncChanged();
/**
* Fires for each change inside this folder that wasn't caused
* by sync activity.
*/
- void watchedFileChangedExternally(const QString& path);
+ void watchedFileChangedExternally(const QString &path);
public slots:
- /**
+ /**
* terminate the current sync run
*/
- void slotTerminateSync();
+ void slotTerminateSync();
- // connected to the corresponding signals in the SyncEngine
- void slotAboutToRemoveAllFiles(SyncFileItem::Direction, bool*);
- void slotAboutToRestoreBackup(bool*);
+ // connected to the corresponding signals in the SyncEngine
+ void slotAboutToRemoveAllFiles(SyncFileItem::Direction, bool *);
+ void slotAboutToRestoreBackup(bool *);
- /**
+ /**
* Starts a sync operation
*
* If the list of changed files is known, it is passed.
*/
- void startSync(const QStringList &pathList = QStringList());
+ void startSync(const QStringList &pathList = QStringList());
- void setProxyDirty(bool value);
- bool proxyDirty();
+ void setProxyDirty(bool value);
+ bool proxyDirty();
- int slotDiscardDownloadProgress();
- int downloadInfoCount();
- int slotWipeErrorBlacklist();
- int errorBlackListEntryCount();
+ int slotDiscardDownloadProgress();
+ int downloadInfoCount();
+ int slotWipeErrorBlacklist();
+ int errorBlackListEntryCount();
- /**
+ /**
* Triggered by the folder watcher when a file/dir in this folder
* changes. Needs to check whether this change should trigger a new
* sync run to be scheduled.
*/
- void slotWatchedPathChanged(const QString& path);
+ void slotWatchedPathChanged(const QString &path);
private slots:
void slotSyncStarted();
- void slotSyncError(const QString& );
+ void slotSyncError(const QString &);
void slotCsyncUnavailable();
void slotSyncFinished(bool);
void slotFolderDiscovered(bool local, QString folderName);
- void slotTransmissionProgress(const ProgressInfo& pi);
- void slotItemCompleted(const SyncFileItemPtr&);
+ void slotTransmissionProgress(const ProgressInfo &pi);
+ void slotItemCompleted(const SyncFileItemPtr &);
void slotRunEtagJob();
void etagRetreived(const QString &);
LogStatusUpdated
};
- void createGuiLog(const QString& filename, LogStatus status, int count,
- const QString& renameTarget = QString::null );
+ void createGuiLog(const QString &filename, LogStatus status, int count,
+ const QString &renameTarget = QString::null);
AccountStatePtr _accountState;
FolderDefinition _definition;
SyncResult _syncResult;
QScopedPointer<SyncEngine> _engine;
- bool _csyncUnavail;
- bool _proxyDirty;
+ bool _csyncUnavail;
+ bool _proxyDirty;
QPointer<RequestEtagJob> _requestEtagJob;
- QString _lastEtag;
+ QString _lastEtag;
QElapsedTimer _timeSinceLastSyncDone;
QElapsedTimer _timeSinceLastSyncStart;
- qint64 _lastSyncDuration;
+ qint64 _lastSyncDuration;
/// The number of syncs that failed in a row.
/// Reset when a sync is successful.
- int _consecutiveFailingSyncs;
+ int _consecutiveFailingSyncs;
/// The number of requested follow-up syncs.
/// Reset when no follow-up is requested.
- int _consecutiveFollowUpSyncs;
+ int _consecutiveFollowUpSyncs;
SyncJournalDb _journal;
- ClientProxy _clientProxy;
+ ClientProxy _clientProxy;
QScopedPointer<SyncRunFileLog> _fileLog;
*/
bool _saveBackwardsCompatible;
};
-
}
#endif
Q_LOGGING_CATEGORY(lcFolderMan, "gui.folder.manager", QtInfoMsg)
-FolderMan* FolderMan::_instance = 0;
-
-FolderMan::FolderMan(QObject *parent) :
- QObject(parent),
- _currentSyncFolder(0),
- _syncEnabled( true ),
- _lockWatcher(new LockWatcher),
- _appRestartRequired(false)
+FolderMan *FolderMan::_instance = 0;
+
+FolderMan::FolderMan(QObject *parent)
+ : QObject(parent)
+ , _currentSyncFolder(0)
+ , _syncEnabled(true)
+ , _lockWatcher(new LockWatcher)
+ , _appRestartRequired(false)
{
ASSERT(!_instance);
_instance = this;
ConfigFile cfg;
int polltime = cfg.remotePollInterval();
qCInfo(lcFolderMan) << "setting remote poll timer interval to" << polltime << "msec";
- _etagPollTimer.setInterval( polltime );
+ _etagPollTimer.setInterval(polltime);
QObject::connect(&_etagPollTimer, SIGNAL(timeout()), this, SLOT(slotEtagPollTimerTimeout()));
_etagPollTimer.start();
_startScheduledSyncTimer.setSingleShot(true);
connect(&_startScheduledSyncTimer, SIGNAL(timeout()),
- SLOT(slotStartScheduledFolderSync()));
+ SLOT(slotStartScheduledFolderSync()));
_timeScheduler.setInterval(5000);
_timeScheduler.setSingleShot(false);
connect(&_timeScheduler, SIGNAL(timeout()),
- SLOT(slotScheduleFolderByTime()));
+ SLOT(slotScheduleFolderByTime()));
_timeScheduler.start();
- connect(AccountManager::instance(), SIGNAL(accountRemoved(AccountState*)),
- SLOT(slotRemoveFoldersForAccount(AccountState*)));
+ connect(AccountManager::instance(), SIGNAL(accountRemoved(AccountState *)),
+ SLOT(slotRemoveFoldersForAccount(AccountState *)));
connect(_lockWatcher.data(), SIGNAL(fileUnlocked(QString)),
- SLOT(slotWatchedFileUnlocked(QString)));
+ SLOT(slotWatchedFileUnlocked(QString)));
}
FolderMan *FolderMan::instance()
return _folderMap;
}
-void FolderMan::unloadFolder( Folder *f )
+void FolderMan::unloadFolder(Folder *f)
{
- if( !f ) {
+ if (!f) {
return;
}
_socketApi->slotUnregisterPath(f->alias());
- if( _folderWatchers.contains(f->alias())) {
+ if (_folderWatchers.contains(f->alias())) {
_folderWatchers.remove(f->alias());
}
- _folderMap.remove( f->alias() );
+ _folderMap.remove(f->alias());
disconnect(f, SIGNAL(syncStarted()),
- this, SLOT(slotFolderSyncStarted()));
+ this, SLOT(slotFolderSyncStarted()));
disconnect(f, SIGNAL(syncFinished(SyncResult)),
- this, SLOT(slotFolderSyncFinished(SyncResult)));
+ this, SLOT(slotFolderSyncFinished(SyncResult)));
disconnect(f, SIGNAL(syncStateChange()),
- this, SLOT(slotForwardFolderSyncStateChange()));
- disconnect(f, SIGNAL(syncPausedChanged(Folder*,bool)),
- this, SLOT(slotFolderSyncPaused(Folder*,bool)));
+ this, SLOT(slotForwardFolderSyncStateChange()));
+ disconnect(f, SIGNAL(syncPausedChanged(Folder *, bool)),
+ this, SLOT(slotFolderSyncPaused(Folder *, bool)));
disconnect(&f->syncEngine().syncFileStatusTracker(), SIGNAL(fileStatusChanged(const QString &, SyncFileStatus)),
- _socketApi.data(), SLOT(broadcastStatusPushMessage(const QString &, SyncFileStatus)));
+ _socketApi.data(), SLOT(broadcastStatusPushMessage(const QString &, SyncFileStatus)));
disconnect(f, SIGNAL(watchedFileChangedExternally(QString)),
- &f->syncEngine().syncFileStatusTracker(), SLOT(slotPathTouched(QString)));
+ &f->syncEngine().syncFileStatusTracker(), SLOT(slotPathTouched(QString)));
}
int FolderMan::unloadAndDeleteAllFolders()
Folder::MapIterator i(_folderMap);
while (i.hasNext()) {
i.next();
- Folder* f = i.value();
+ Folder *f = i.value();
unloadFolder(f);
delete f;
cnt++;
// add a monitor to the local file system. If there is a change in the
// file system, the method slotFolderMonitorFired is triggered through
// the SignalMapper
-void FolderMan::registerFolderMonitor( Folder *folder )
+void FolderMan::registerFolderMonitor(Folder *folder)
{
- if( !folder ) return;
- if( !QDir(folder->path()).exists() ) return;
+ if (!folder)
+ return;
+ if (!QDir(folder->path()).exists())
+ return;
- if( !_folderWatchers.contains(folder->alias() ) ) {
+ if (!_folderWatchers.contains(folder->alias())) {
FolderWatcher *fw = new FolderWatcher(folder->path(), folder);
// Connect the pathChanged signal, which comes with the changed path,
_socketApi->slotRegisterPath(folder->alias());
}
-void FolderMan::addMonitorPath( const QString& alias, const QString& path )
+void FolderMan::addMonitorPath(const QString &alias, const QString &path)
{
- if( !alias.isEmpty() && _folderWatchers.contains(alias) ) {
+ if (!alias.isEmpty() && _folderWatchers.contains(alias)) {
FolderWatcher *fw = _folderWatchers[alias];
- if( fw ) {
+ if (fw) {
fw->addPath(path);
}
}
}
-void FolderMan::removeMonitorPath( const QString& alias, const QString& path )
+void FolderMan::removeMonitorPath(const QString &alias, const QString &path)
{
- if( !alias.isEmpty() && _folderWatchers.contains(alias) ) {
+ if (!alias.isEmpty() && _folderWatchers.contains(alias)) {
FolderWatcher *fw = _folderWatchers[alias];
- if( fw ) {
+ if (fw) {
fw->removePath(path);
}
}
qCInfo(lcFolderMan) << "Setup folders from settings file";
- foreach (const auto& account, AccountManager::instance()->accounts()) {
+ foreach (const auto &account, AccountManager::instance()->accounts()) {
const auto id = account->account()->id();
if (!accountsWithSettings.contains(id)) {
continue;
void FolderMan::setupFoldersHelper(QSettings &settings, AccountStatePtr account, bool backwardsCompatible)
{
- foreach (const auto& folderAlias, settings.childGroups()) {
+ foreach (const auto &folderAlias, settings.childGroups()) {
FolderDefinition folderDefinition;
if (FolderDefinition::load(settings, folderAlias, &folderDefinition)) {
// Migration: Old settings don't have journalPath
SyncJournalDb::maybeMigrateDb(folderDefinition.localPath, folderDefinition.absoluteJournalPath());
}
- Folder* f = addFolderInternal(std::move(folderDefinition), account.data());
+ Folder *f = addFolderInternal(std::move(folderDefinition), account.data());
if (f) {
// Migration: Mark folders that shall be saved in a backwards-compatible way
if (backwardsCompatible) {
qCInfo(lcFolderMan) << "Setup folders from " << _folderConfigPath << "(migration)";
- QDir dir( _folderConfigPath );
+ QDir dir(_folderConfigPath);
//We need to include hidden files just in case the alias starts with '.'
dir.setFilter(QDir::Files | QDir::Hidden);
QStringList list = dir.entryList();
// Normally there should be only one account when migrating.
- AccountState* accountState = AccountManager::instance()->accounts().value(0).data();
- foreach ( const QString& alias, list ) {
- Folder *f = setupFolderFromOldConfigFile( alias, accountState );
- if( f ) {
+ AccountState *accountState = AccountManager::instance()->accounts().value(0).data();
+ foreach (const QString &alias, list) {
+ Folder *f = setupFolderFromOldConfigFile(alias, accountState);
+ if (f) {
scheduleFolder(f);
emit folderSyncStateChange(f);
}
return _folderMap.size();
}
-bool FolderMan::ensureJournalGone( const QString& journalDbFile )
+bool FolderMan::ensureJournalGone(const QString &journalDbFile)
{
// remove the old journal file
while (QFile::exists(journalDbFile) && !QFile::remove(journalDbFile)) {
qCWarning(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 "
- "that no application is currently using it.")
- .arg(QDir::fromNativeSeparators(QDir::cleanPath(journalDbFile))),
- QMessageBox::Retry|QMessageBox::Abort);
+ tr("An old sync journal '%1' was found, "
+ "but could not be removed. Please make sure "
+ "that no application is currently using it.")
+ .arg(QDir::fromNativeSeparators(QDir::cleanPath(journalDbFile))),
+ QMessageBox::Retry | QMessageBox::Abort);
if (ret == QMessageBox::Abort) {
return false;
}
return true;
}
-#define SLASH_TAG QLatin1String("__SLASH__")
-#define BSLASH_TAG QLatin1String("__BSLASH__")
-#define QMARK_TAG QLatin1String("__QMARK__")
+#define SLASH_TAG QLatin1String("__SLASH__")
+#define BSLASH_TAG QLatin1String("__BSLASH__")
+#define QMARK_TAG QLatin1String("__QMARK__")
#define PERCENT_TAG QLatin1String("__PERCENT__")
-#define STAR_TAG QLatin1String("__STAR__")
-#define COLON_TAG QLatin1String("__COLON__")
-#define PIPE_TAG QLatin1String("__PIPE__")
-#define QUOTE_TAG QLatin1String("__QUOTE__")
-#define LT_TAG QLatin1String("__LESS_THAN__")
-#define GT_TAG QLatin1String("__GREATER_THAN__")
-#define PAR_O_TAG QLatin1String("__PAR_OPEN__")
-#define PAR_C_TAG QLatin1String("__PAR_CLOSE__")
-
-QString FolderMan::escapeAlias( const QString& alias )
+#define STAR_TAG QLatin1String("__STAR__")
+#define COLON_TAG QLatin1String("__COLON__")
+#define PIPE_TAG QLatin1String("__PIPE__")
+#define QUOTE_TAG QLatin1String("__QUOTE__")
+#define LT_TAG QLatin1String("__LESS_THAN__")
+#define GT_TAG QLatin1String("__GREATER_THAN__")
+#define PAR_O_TAG QLatin1String("__PAR_OPEN__")
+#define PAR_C_TAG QLatin1String("__PAR_CLOSE__")
+
+QString FolderMan::escapeAlias(const QString &alias)
{
QString a(alias);
- a.replace( QLatin1Char('/'), SLASH_TAG );
- a.replace( QLatin1Char('\\'), BSLASH_TAG );
- a.replace( QLatin1Char('?'), QMARK_TAG );
- a.replace( QLatin1Char('%'), PERCENT_TAG );
- a.replace( QLatin1Char('*'), STAR_TAG );
- a.replace( QLatin1Char(':'), COLON_TAG );
- a.replace( QLatin1Char('|'), PIPE_TAG );
- a.replace( QLatin1Char('"'), QUOTE_TAG );
- a.replace( QLatin1Char('<'), LT_TAG );
- a.replace( QLatin1Char('>'), GT_TAG );
- a.replace( QLatin1Char('['), PAR_O_TAG );
- a.replace( QLatin1Char(']'), PAR_C_TAG );
+ a.replace(QLatin1Char('/'), SLASH_TAG);
+ a.replace(QLatin1Char('\\'), BSLASH_TAG);
+ a.replace(QLatin1Char('?'), QMARK_TAG);
+ a.replace(QLatin1Char('%'), PERCENT_TAG);
+ a.replace(QLatin1Char('*'), STAR_TAG);
+ a.replace(QLatin1Char(':'), COLON_TAG);
+ a.replace(QLatin1Char('|'), PIPE_TAG);
+ a.replace(QLatin1Char('"'), QUOTE_TAG);
+ a.replace(QLatin1Char('<'), LT_TAG);
+ a.replace(QLatin1Char('>'), GT_TAG);
+ a.replace(QLatin1Char('['), PAR_O_TAG);
+ a.replace(QLatin1Char(']'), PAR_C_TAG);
return a;
}
return this->_socketApi.data();
}
-QString FolderMan::unescapeAlias( const QString& alias )
+QString FolderMan::unescapeAlias(const QString &alias)
{
QString a(alias);
- a.replace( SLASH_TAG, QLatin1String("/") );
- a.replace( BSLASH_TAG, QLatin1String("\\") );
- a.replace( QMARK_TAG, QLatin1String("?") );
- a.replace( PERCENT_TAG, QLatin1String("%") );
- a.replace( STAR_TAG, QLatin1String("*") );
- a.replace( COLON_TAG, QLatin1String(":") );
- a.replace( PIPE_TAG, QLatin1String("|") );
- a.replace( QUOTE_TAG, QLatin1String("\"") );
- a.replace( LT_TAG, QLatin1String("<") );
- a.replace( GT_TAG, QLatin1String(">") );
- a.replace( PAR_O_TAG, QLatin1String("[") );
- a.replace( PAR_C_TAG, QLatin1String("]") );
+ a.replace(SLASH_TAG, QLatin1String("/"));
+ a.replace(BSLASH_TAG, QLatin1String("\\"));
+ a.replace(QMARK_TAG, QLatin1String("?"));
+ a.replace(PERCENT_TAG, QLatin1String("%"));
+ a.replace(STAR_TAG, QLatin1String("*"));
+ a.replace(COLON_TAG, QLatin1String(":"));
+ a.replace(PIPE_TAG, QLatin1String("|"));
+ a.replace(QUOTE_TAG, QLatin1String("\""));
+ a.replace(LT_TAG, QLatin1String("<"));
+ a.replace(GT_TAG, QLatin1String(">"));
+ a.replace(PAR_O_TAG, QLatin1String("["));
+ a.replace(PAR_C_TAG, QLatin1String("]"));
return a;
}
// filename is the name of the file only, it does not include
// the configuration directory path
// WARNING: Do not remove this code, it is used for predefined/automated deployments (2016)
-Folder* FolderMan::setupFolderFromOldConfigFile(const QString &file, AccountState *accountState )
+Folder *FolderMan::setupFolderFromOldConfigFile(const QString &file, AccountState *accountState)
{
Folder *folder = 0;
// check the unescaped variant (for the case when the filename comes out
// of the directory listing). If the file does not exist, escape the
// file and try again.
- QFileInfo cfgFile( _folderConfigPath, file);
+ QFileInfo cfgFile(_folderConfigPath, file);
- if( !cfgFile.exists() ) {
+ if (!cfgFile.exists()) {
// try the escaped variant.
escapedAlias = escapeAlias(file);
- cfgFile.setFile( _folderConfigPath, escapedAlias );
+ cfgFile.setFile(_folderConfigPath, escapedAlias);
}
- if( !cfgFile.isReadable() ) {
+ if (!cfgFile.isReadable()) {
qCWarning(lcFolderMan) << "Cannot read folder definition for alias " << cfgFile.filePath();
return folder;
}
- QSettings settings( _folderConfigPath + QLatin1Char('/') + escapedAlias, QSettings::IniFormat);
+ QSettings settings(_folderConfigPath + QLatin1Char('/') + escapedAlias, QSettings::IniFormat);
qCInfo(lcFolderMan) << " -> file path: " << settings.fileName();
// Check if the filename is equal to the group setting. If not, use the group
// name as an alias.
QStringList groups = settings.childGroups();
- if( ! groups.contains(escapedAlias) && groups.count() > 0 ) {
+ if (!groups.contains(escapedAlias) && groups.count() > 0) {
escapedAlias = groups.first();
}
- settings.beginGroup( escapedAlias ); // read the group with the same name as the file which is the folder alias
+ settings.beginGroup(escapedAlias); // read the group with the same name as the file which is the folder alias
QString path = settings.value(QLatin1String("localPath")).toString();
QString backend = settings.value(QLatin1String("backend")).toString();
- QString targetPath = settings.value( QLatin1String("targetPath")).toString();
- bool paused = settings.value( QLatin1String("paused"), false).toBool();
+ QString targetPath = settings.value(QLatin1String("targetPath")).toString();
+ bool paused = settings.value(QLatin1String("paused"), false).toBool();
// QString connection = settings.value( QLatin1String("connection") ).toString();
- QString alias = unescapeAlias( escapedAlias );
+ QString alias = unescapeAlias(escapedAlias);
if (backend.isEmpty() || backend != QLatin1String("owncloud")) {
qCWarning(lcFolderMan) << "obsolete configuration of type" << backend;
}
// cut off the leading slash, oCUrl always has a trailing.
- if( targetPath.startsWith(QLatin1Char('/')) ) {
- targetPath.remove(0,1);
+ if (targetPath.startsWith(QLatin1Char('/'))) {
+ targetPath.remove(0, 1);
}
if (!accountState) {
folder = addFolderInternal(folderDefinition, accountState);
if (folder) {
- QStringList blackList = settings.value( QLatin1String("blackList")).toStringList();
+ QStringList blackList = settings.value(QLatin1String("blackList")).toStringList();
if (!blackList.empty()) {
//migrate settings
folder->journalDb()->setSelectiveSyncList(SyncJournalDb::SelectiveSyncBlackList, blackList);
return folder;
}
-void FolderMan::slotFolderSyncPaused( Folder *f, bool paused )
+void FolderMan::slotFolderSyncPaused(Folder *f, bool paused)
{
- if( !f ) {
+ if (!f) {
qCCritical(lcFolderMan) << "slotFolderSyncPaused called with empty folder";
return;
}
void FolderMan::slotFolderCanSyncChanged()
{
- Folder *f = qobject_cast<Folder*>(sender());
+ Folder *f = qobject_cast<Folder *>(sender());
ASSERT(f);
if (f->canSync()) {
_socketApi->slotRegisterPath(f->alias());
void FolderMan::terminateSyncProcess()
{
Folder *f = _currentSyncFolder;
- if( f ) {
+ if (f) {
// This will, indirectly and eventually, call slotFolderSyncFinished
// and thereby clear _currentSyncFolder.
f->slotTerminateSync();
}
}
-Folder *FolderMan::folder( const QString& alias )
+Folder *FolderMan::folder(const QString &alias)
{
- if( !alias.isEmpty() ) {
- if( _folderMap.contains( alias )) {
+ if (!alias.isEmpty()) {
+ if (_folderMap.contains(alias)) {
return _folderMap[alias];
}
}
void FolderMan::scheduleAllFolders()
{
- foreach( Folder *f, _folderMap.values() ) {
+ foreach (Folder *f, _folderMap.values()) {
if (f && f->canSync()) {
- scheduleFolder( f );
+ scheduleFolder(f);
}
}
}
qCInfo(lcFolderMan) << "Application restart requested!";
}
-void FolderMan::slotSyncOnceFileUnlocks(const QString& path)
+void FolderMan::slotSyncOnceFileUnlocks(const QString &path)
{
_lockWatcher->addFile(path);
}
* if a folder wants to be synced, it calls this slot and is added
* to the queue. The slot to actually start a sync is called afterwards.
*/
-void FolderMan::scheduleFolder( Folder *f )
+void FolderMan::scheduleFolder(Folder *f)
{
- if( !f ) {
+ if (!f) {
qCCritical(lcFolderMan) << "slotScheduleSync called with null folder";
return;
}
qCInfo(lcFolderMan) << "Schedule folder " << alias << " to sync!";
- if( ! _scheduledFolders.contains(f) ) {
- if( !f->canSync() ) {
+ if (!_scheduledFolders.contains(f)) {
+ if (!f->canSync()) {
qCInfo(lcFolderMan) << "Folder is not ready to sync, not scheduled!";
_socketApi->slotUpdateFolderView(f);
return;
startScheduledSyncSoon();
}
-void FolderMan::scheduleFolderNext(Folder* f)
+void FolderMan::scheduleFolderNext(Folder *f)
{
auto alias = f->alias();
qCInfo(lcFolderMan) << "Schedule folder " << alias << " to sync! Front-of-queue.";
- if( !f->canSync() ) {
+ if (!f->canSync()) {
qCInfo(lcFolderMan) << "Folder is not ready to sync, not scheduled!";
return;
}
startScheduledSyncSoon();
}
-void FolderMan::slotScheduleETagJob(const QString &/*alias*/, RequestEtagJob *job)
+void FolderMan::slotScheduleETagJob(const QString & /*alias*/, RequestEtagJob *job)
{
- QObject::connect(job, SIGNAL(destroyed(QObject*)), this, SLOT(slotEtagJobDestroyed(QObject*)));
+ QObject::connect(job, SIGNAL(destroyed(QObject *)), this, SLOT(slotEtagJobDestroyed(QObject *)));
QMetaObject::invokeMethod(this, "slotRunOneEtagJob", Qt::QueuedConnection);
// maybe: add to queue
}
-void FolderMan::slotEtagJobDestroyed(QObject* /*o*/)
+void FolderMan::slotEtagJobDestroyed(QObject * /*o*/)
{
// _currentEtagJob is automatically cleared
// maybe: remove from queue
{
if (_currentEtagJob.isNull()) {
Folder *folder;
- foreach(Folder *f, _folderMap) {
+ foreach (Folder *f, _folderMap) {
if (f->etagJob()) {
// Caveat: always grabs the first folder with a job, but we think this is Ok for now and avoids us having a seperate queue.
_currentEtagJob = f->etagJob();
//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 ) {
+ if (_currentSyncFolder == NULL && _appRestartRequired) {
restartApplication();
}
} else {
void FolderMan::slotAccountStateChanged()
{
- AccountState * accountState = qobject_cast<AccountState*>(sender());
- if (! accountState) {
+ AccountState *accountState = qobject_cast<AccountState *>(sender());
+ if (!accountState) {
return;
}
QString accountName = accountState->account()->displayName();
foreach (Folder *f, _folderMap.values()) {
if (f
- && f->canSync()
- && f->accountState() == accountState) {
+ && f->canSync()
+ && f->accountState() == accountState) {
scheduleFolder(f);
}
}
} else {
qCInfo(lcFolderMan) << "Account" << accountName << "disconnected or paused, "
- "terminating or descheduling sync folders";
+ "terminating or descheduling sync folders";
if (_currentSyncFolder
- && _currentSyncFolder->accountState() == accountState) {
+ && _currentSyncFolder->accountState() == accountState) {
_currentSyncFolder->slotTerminateSync();
}
- QMutableListIterator<Folder*> it(_scheduledFolders);
+ QMutableListIterator<Folder *> it(_scheduledFolders);
while (it.hasNext()) {
- Folder* f = it.next();
+ Folder *f = it.next();
if (f->accountState() == accountState) {
it.remove();
}
// only enable or disable foldermans will schedule and do syncs.
// this is not the same as Pause and Resume of folders.
-void FolderMan::setSyncEnabled( bool enabled )
+void FolderMan::setSyncEnabled(bool enabled)
{
if (!_syncEnabled && enabled && !_scheduledFolders.isEmpty()) {
// We have things in our queue that were waiting for the connection to come back on.
}
_syncEnabled = enabled;
// force a redraw in case the network connect status changed
- emit( folderSyncStateChange(0) );
+ emit(folderSyncStateChange(0));
}
void FolderMan::startScheduledSyncSoon()
qint64 msSinceLastSync = 0;
// Require a pause based on the duration of the last sync run.
- if (Folder* lastFolder = _lastSyncFolder) {
+ if (Folder *lastFolder = _lastSyncFolder) {
msSinceLastSync = lastFolder->msecSinceLastSync();
// 1s -> 1.5s pause
// Delays beyond one minute seem too big, particularly since there
// could be things later in the queue that shouldn't be punished by a
// long delay!
- msDelay = qMin(msDelay, 60*1000ll);
+ msDelay = qMin(msDelay, 60 * 1000ll);
// Time since the last sync run counts against the delay
msDelay = qMax(1ll, msDelay - msSinceLastSync);
- qCInfo(lcFolderMan) << "Starting the next scheduled sync in" << (msDelay/1000) << "seconds";
+ qCInfo(lcFolderMan) << "Starting the next scheduled sync in" << (msDelay / 1000) << "seconds";
_startScheduledSyncTimer.start(msDelay);
}
*/
void FolderMan::slotStartScheduledFolderSync()
{
- if( _currentSyncFolder ) {
+ if (_currentSyncFolder) {
qCInfo(lcFolderMan) << "Currently folder " << _currentSyncFolder->remoteUrl().toString() << " is running, wait for finish!";
return;
}
- if( ! _syncEnabled ) {
+ if (!_syncEnabled) {
qCInfo(lcFolderMan) << "FolderMan: Syncing is disabled, no scheduling.";
return;
}
qCDebug(lcFolderMan) << "folderQueue size: " << _scheduledFolders.count();
- if( _scheduledFolders.isEmpty() ) {
+ if (_scheduledFolders.isEmpty()) {
return;
}
// Find the first folder in the queue that can be synced.
- Folder* folder = 0;
- while( !_scheduledFolders.isEmpty() ) {
- Folder* g = _scheduledFolders.dequeue();
- if( g->canSync() ) {
+ Folder *folder = 0;
+ while (!_scheduledFolders.isEmpty()) {
+ Folder *g = _scheduledFolders.dequeue();
+ if (g->canSync()) {
folder = g;
break;
}
emit scheduleQueueChanged();
// Start syncing this folder!
- if( folder ) {
+ if (folder) {
// Safe to call several times, and necessary to try again if
// the folder path didn't exist previously.
registerFolderMonitor(folder);
_currentSyncFolder = folder;
- folder->startSync( QStringList() );
+ folder->startSync(QStringList());
}
}
}
}
-void FolderMan::slotRemoveFoldersForAccount(AccountState* accountState)
+void FolderMan::slotRemoveFoldersForAccount(AccountState *accountState)
{
QVarLengthArray<Folder *, 16> foldersToRemove;
Folder::MapIterator i(_folderMap);
while (i.hasNext()) {
i.next();
- Folder* folder = i.value();
+ Folder *folder = i.value();
if (folder->accountState() == accountState) {
foldersToRemove.append(folder);
}
void FolderMan::slotForwardFolderSyncStateChange()
{
- if (Folder* f = qobject_cast<Folder*>(sender())) {
+ if (Folder *f = qobject_cast<Folder *>(sender())) {
emit folderSyncStateChange(f);
}
}
// Pause folders if the server version is unsupported
if (account->serverVersionUnsupported()) {
qCWarning(lcFolderMan) << "The server version is unsupported:" << account->serverVersion()
- << "pausing all folders on the account";
+ << "pausing all folders on the account";
- foreach (auto& f, _folderMap) {
+ foreach (auto &f, _folderMap) {
if (f->accountState()->account().data() == account) {
f->setSyncPaused(true);
}
}
}
-void FolderMan::slotWatchedFileUnlocked(const QString& path)
+void FolderMan::slotWatchedFileUnlocked(const QString &path)
{
- if (Folder* f = folderForPath(path)) {
+ if (Folder *f = folderForPath(path)) {
f->scheduleThisFolderSoon();
}
}
void FolderMan::slotScheduleFolderByTime()
{
- foreach (auto& f, _folderMap) {
+ foreach (auto &f, _folderMap) {
// Never schedule if syncing is disabled or when we're currently
// querying the server for etags
if (!f->canSync() || f->etagJob()) {
// Possibly it's just time for a new sync run
bool forceSyncIntervalExpired =
- quint64(msecsSinceSync) > ConfigFile().forceSyncInterval();
+ quint64(msecsSinceSync) > ConfigFile().forceSyncInterval();
if (forceSyncIntervalExpired) {
qCInfo(lcFolderMan) << "Scheduling folder" << f->alias()
- << "because it has been" << msecsSinceSync << "ms "
- << "since the last sync";
+ << "because it has been" << msecsSinceSync << "ms "
+ << "since the last sync";
scheduleFolder(f);
continue;
// Retry a couple of times after failure; or regularly if requested
bool syncAgain =
- (f->consecutiveFailingSyncs() > 0 && f->consecutiveFailingSyncs() < 3)
- || f->syncEngine().isAnotherSyncNeeded() == DelayedFollowUp;
+ (f->consecutiveFailingSyncs() > 0 && f->consecutiveFailingSyncs() < 3)
+ || f->syncEngine().isAnotherSyncNeeded() == DelayedFollowUp;
qint64 syncAgainDelay = 10 * 1000; // 10s for the first retry-after-fail
if (f->consecutiveFailingSyncs() > 1)
syncAgainDelay = 60 * 1000; // 60s for each further attempt
if (syncAgain
- && msecsSinceSync > syncAgainDelay) {
+ && msecsSinceSync > syncAgainDelay) {
qCInfo(lcFolderMan) << "Scheduling folder" << f->alias()
- << ", the last" << f->consecutiveFailingSyncs() << "syncs failed"
- << ", anotherSyncNeeded" << f->syncEngine().isAnotherSyncNeeded()
- << ", last status:" << f->syncResult().statusString()
- << ", time since last sync:" << msecsSinceSync;
+ << ", the last" << f->consecutiveFailingSyncs() << "syncs failed"
+ << ", anotherSyncNeeded" << f->syncEngine().isAnotherSyncNeeded()
+ << ", last status:" << f->syncResult().statusString()
+ << ", time since last sync:" << msecsSinceSync;
scheduleFolder(f);
continue;
}
}
-void FolderMan::slotFolderSyncStarted( )
+void FolderMan::slotFolderSyncStarted()
{
qCInfo(lcFolderMan) << ">===================================== sync started for " << _currentSyncFolder->remoteUrl().toString();
}
* This delay is particularly useful to avoid late file change notifications
* (that we caused ourselves by syncing) from triggering another spurious sync.
*/
-void FolderMan::slotFolderSyncFinished( const SyncResult& )
+void FolderMan::slotFolderSyncFinished(const SyncResult &)
{
qCInfo(lcFolderMan) << "<===================================== sync finished for " << _currentSyncFolder->remoteUrl().toString();
startScheduledSyncSoon();
}
-Folder* FolderMan::addFolder(AccountState* accountState, const FolderDefinition& folderDefinition)
+Folder *FolderMan::addFolder(AccountState *accountState, const FolderDefinition &folderDefinition)
{
// Choose a db filename
auto definition = folderDefinition;
// Migration: The first account that's configured for a local folder shall
// be saved in a backwards-compatible way.
bool oneAccountOnly = true;
- foreach (Folder* other, FolderMan::instance()->map()) {
+ foreach (Folder *other, FolderMan::instance()->map()) {
if (other != folder && other->cleanPath() == folder->cleanPath()) {
oneAccountOnly = false;
break;
}
folder->setSaveBackwardsCompatible(oneAccountOnly);
- if(folder) {
+ if (folder) {
folder->saveToSettings();
emit folderSyncStateChange(folder);
emit folderListChanged(_folderMap);
return folder;
}
-Folder* FolderMan::addFolderInternal(FolderDefinition folderDefinition,
- AccountState* accountState)
+Folder *FolderMan::addFolderInternal(FolderDefinition folderDefinition,
+ AccountState *accountState)
{
auto alias = folderDefinition.alias;
int count = 0;
folderDefinition.alias = alias + QString::number(++count);
}
- auto folder = new Folder(folderDefinition, accountState, this );
+ auto folder = new Folder(folderDefinition, accountState, this);
qCInfo(lcFolderMan) << "Adding folder to Folder Map " << folder << folder->alias();
_folderMap[folder->alias()] = folder;
connect(folder, SIGNAL(syncStarted()), SLOT(slotFolderSyncStarted()));
connect(folder, SIGNAL(syncFinished(SyncResult)), SLOT(slotFolderSyncFinished(SyncResult)));
connect(folder, SIGNAL(syncStateChange()), SLOT(slotForwardFolderSyncStateChange()));
- connect(folder, SIGNAL(syncPausedChanged(Folder*,bool)), SLOT(slotFolderSyncPaused(Folder*,bool)));
+ connect(folder, SIGNAL(syncPausedChanged(Folder *, bool)), SLOT(slotFolderSyncPaused(Folder *, bool)));
connect(folder, SIGNAL(canSyncChanged()), SLOT(slotFolderCanSyncChanged()));
connect(&folder->syncEngine().syncFileStatusTracker(), SIGNAL(fileStatusChanged(const QString &, SyncFileStatus)),
- _socketApi.data(), SLOT(broadcastStatusPushMessage(const QString &, SyncFileStatus)));
+ _socketApi.data(), SLOT(broadcastStatusPushMessage(const QString &, SyncFileStatus)));
connect(folder, SIGNAL(watchedFileChangedExternally(QString)),
- &folder->syncEngine().syncFileStatusTracker(), SLOT(slotPathTouched(QString)));
+ &folder->syncEngine().syncFileStatusTracker(), SLOT(slotPathTouched(QString)));
registerFolderMonitor(folder);
return folder;
Folder *FolderMan::folderForPath(const QString &path)
{
- QString absolutePath = QDir::cleanPath(path)+QLatin1Char('/');
+ QString absolutePath = QDir::cleanPath(path) + QLatin1Char('/');
- foreach(Folder* folder, this->map().values()) {
- const QString folderPath = folder->cleanPath()+QLatin1Char('/');
+ foreach (Folder *folder, this->map().values()) {
+ const QString folderPath = folder->cleanPath() + QLatin1Char('/');
- if(absolutePath.startsWith(folderPath, (Utility::isWindows() || Utility::isMac())?
- Qt::CaseInsensitive : Qt::CaseSensitive)) {
+ if (absolutePath.startsWith(folderPath, (Utility::isWindows() || Utility::isMac()) ? Qt::CaseInsensitive : Qt::CaseSensitive)) {
return folder;
}
}
return 0;
}
-QStringList FolderMan::findFileInLocalFolders( const QString& relPath, const AccountPtr acc )
+QStringList FolderMan::findFileInLocalFolders(const QString &relPath, const AccountPtr acc)
{
QStringList re;
- foreach(Folder* folder, this->map().values()) {
+ foreach (Folder *folder, this->map().values()) {
if (acc != 0 && folder->accountState()->account() != acc) {
continue;
}
remRelPath = relPath.mid(folder->remotePath().length());
path += "/";
path += remRelPath;
- if( QFile::exists(path) ) {
- re.append( path );
+ if (QFile::exists(path)) {
+ re.append(path);
}
}
return re;
}
-void FolderMan::removeFolder( Folder *f )
+void FolderMan::removeFolder(Folder *f)
{
- if( !f ) {
+ if (!f) {
qCCritical(lcFolderMan) << "Can not remove null folder";
return;
}
qCInfo(lcFolderMan) << "Removing " << f->alias();
const bool currentlyRunning = (_currentSyncFolder == f);
- if( currentlyRunning ) {
+ if (currentlyRunning) {
// abort the sync now
terminateSyncProcess();
}
// remove the folder configuration
f->removeFromSettings();
- unloadFolder( f);
- if( currentlyRunning ) {
+ unloadFolder(f);
+ if (currentlyRunning) {
// We want to schedule the next folder once this is done
connect(f, SIGNAL(syncFinished(SyncResult)),
- SLOT(slotFolderSyncFinished(SyncResult)));
+ SLOT(slotFolderSyncFinished(SyncResult)));
// Let the folder delete itself when done.
connect(f, SIGNAL(syncFinished(SyncResult)), f, SLOT(deleteLater()));
} else {
}
}
-QString FolderMan::getBackupName( QString fullPathName ) const
+QString FolderMan::getBackupName(QString fullPathName) const
{
if (fullPathName.endsWith("/"))
fullPathName.chop(1);
- if( fullPathName.isEmpty() ) return QString::null;
+ if (fullPathName.isEmpty())
+ return QString::null;
- QString newName = fullPathName + tr(" (backup)");
- QFileInfo fi( newName );
- int cnt = 2;
- do {
- if( fi.exists() ) {
- newName = fullPathName + tr(" (backup %1)").arg(cnt++);
- fi.setFile(newName);
- }
- } while( fi.exists() );
+ QString newName = fullPathName + tr(" (backup)");
+ QFileInfo fi(newName);
+ int cnt = 2;
+ do {
+ if (fi.exists()) {
+ newName = fullPathName + tr(" (backup %1)").arg(cnt++);
+ fi.setFile(newName);
+ }
+ } while (fi.exists());
- return newName;
+ return newName;
}
-bool FolderMan::startFromScratch( const QString& localFolder )
+bool FolderMan::startFromScratch(const QString &localFolder)
{
- if( localFolder.isEmpty() ) {
+ if (localFolder.isEmpty()) {
return false;
}
- QFileInfo fi( localFolder );
- QDir parentDir( fi.dir() );
+ QFileInfo fi(localFolder);
+ QDir parentDir(fi.dir());
QString folderName = fi.fileName();
// Adjust for case where localFolder ends with a /
- if ( fi.isDir() ) {
+ if (fi.isDir()) {
folderName = parentDir.dirName();
parentDir.cdUp();
}
- if( fi.exists() ) {
+ if (fi.exists()) {
// It exists, but is empty -> just reuse it.
- if( fi.isDir() && fi.dir().count() == 0 ) {
+ if (fi.isDir() && fi.dir().count() == 0) {
qCDebug(lcFolderMan) << "startFromScratch: Directory is empty!";
return true;
}
// Disconnect the socket api from the database to avoid that locking of the
// db file does not allow to move this dir.
Folder *f = folderForPath(localFolder);
- if(f) {
- if( localFolder.startsWith(f->path()) ) {
+ if (f) {
+ if (localFolder.startsWith(f->path())) {
_socketApi->slotUnregisterPath(f->alias());
}
f->journalDb()->close();
}
// Make a backup of the folder/file.
- QString newName = getBackupName( parentDir.absoluteFilePath( folderName ) );
+ QString newName = getBackupName(parentDir.absoluteFilePath(folderName));
QString renameError;
- if( !FileSystem::rename( fi.absoluteFilePath(), newName, &renameError ) ) {
+ if (!FileSystem::rename(fi.absoluteFilePath(), newName, &renameError)) {
qCWarning(lcFolderMan) << "startFromScratch: Could not rename" << fi.absoluteFilePath()
- << "to" << newName << "error:" << renameError;
+ << "to" << newName << "error:" << renameError;
return false;
}
}
- if( !parentDir.mkdir( fi.absoluteFilePath() ) ) {
+ if (!parentDir.mkdir(fi.absoluteFilePath())) {
qCWarning(lcFolderMan) << "startFromScratch: Could not mkdir" << fi.absoluteFilePath();
return false;
}
void FolderMan::setDirtyProxy(bool value)
{
- foreach( Folder *f, _folderMap.values() ) {
- if(f) {
+ foreach (Folder *f, _folderMap.values()) {
+ if (f) {
f->setProxyDirty(value);
if (f->accountState() && f->accountState()->account()
- && f->accountState()->account()->networkAccessManager()) {
+ && f->accountState()->account()->networkAccessManager()) {
// Need to do this so we do not use the old determined system proxy
f->accountState()->account()->networkAccessManager()->setProxy(
- QNetworkProxy(QNetworkProxy::DefaultProxy));
+ QNetworkProxy(QNetworkProxy::DefaultProxy));
}
}
}
void FolderMan::setDirtyNetworkLimits()
{
- foreach( Folder *f, _folderMap.values() ) {
+ foreach (Folder *f, _folderMap.values()) {
// set only in busy folders. Otherwise they read the config anyway.
- if(f && f->isBusy()) {
+ if (f && f->isBusy()) {
f->setDirtyNetworkLimits();
}
}
-
}
-SyncResult FolderMan::accountStatus(const QList<Folder*> &folders)
+SyncResult FolderMan::accountStatus(const QList<Folder *> &folders)
{
SyncResult overallResult;
// if one is paused, but others ok, show ok
// do not show "problem" in the tray
//
- if( cnt == 1 ) {
+ if (cnt == 1) {
Folder *folder = folders.at(0);
- if( folder ) {
- if( folder->syncPaused() ) {
+ if (folder) {
+ if (folder->syncPaused()) {
overallResult.setStatus(SyncResult::Paused);
} else {
SyncResult::Status syncStatus = folder->syncResult().status();
- switch( syncStatus ) {
+ switch (syncStatus) {
case SyncResult::Undefined:
overallResult.setStatus(SyncResult::Error);
break;
case SyncResult::NotYetStarted:
- overallResult.setStatus( SyncResult::NotYetStarted );
+ overallResult.setStatus(SyncResult::NotYetStarted);
break;
case SyncResult::SyncPrepare:
- overallResult.setStatus( SyncResult::SyncPrepare );
+ overallResult.setStatus(SyncResult::SyncPrepare);
break;
case SyncResult::SyncRunning:
- overallResult.setStatus( SyncResult::SyncRunning );
+ overallResult.setStatus(SyncResult::SyncRunning);
break;
case SyncResult::Problem: // don't show the problem icon in tray.
case SyncResult::Success:
- if( overallResult.status() == SyncResult::Undefined )
- overallResult.setStatus( SyncResult::Success );
+ if (overallResult.status() == SyncResult::Undefined)
+ overallResult.setStatus(SyncResult::Success);
break;
case SyncResult::Error:
- overallResult.setStatus( SyncResult::Error );
+ overallResult.setStatus(SyncResult::Error);
break;
case SyncResult::SetupError:
- if ( overallResult.status() != SyncResult::Error )
- overallResult.setStatus( SyncResult::SetupError );
+ if (overallResult.status() != SyncResult::Error)
+ overallResult.setStatus(SyncResult::SetupError);
break;
case SyncResult::SyncAbortRequested:
- overallResult.setStatus( SyncResult::SyncAbortRequested);
+ overallResult.setStatus(SyncResult::SyncAbortRequested);
break;
case SyncResult::Paused:
- overallResult.setStatus( SyncResult::Paused);
+ overallResult.setStatus(SyncResult::Paused);
break;
}
}
int runSeen = 0;
int various = 0;
- foreach ( Folder *folder, folders ) {
- if( folder->syncPaused() ) {
+ foreach (Folder *folder, folders) {
+ if (folder->syncPaused()) {
abortOrPausedSeen++;
} else {
SyncResult folderResult = folder->syncResult();
SyncResult::Status syncStatus = folderResult.status();
- switch( syncStatus ) {
+ switch (syncStatus) {
case SyncResult::Undefined:
case SyncResult::NotYetStarted:
various++;
}
}
bool set = false;
- if( errorsSeen > 0 ) {
+ if (errorsSeen > 0) {
overallResult.setStatus(SyncResult::Error);
set = true;
}
- if( !set && abortOrPausedSeen > 0 && abortOrPausedSeen == cnt ) {
+ if (!set && abortOrPausedSeen > 0 && abortOrPausedSeen == cnt) {
// only if all folders are paused
overallResult.setStatus(SyncResult::Paused);
set = true;
}
- if( !set && runSeen > 0 ) {
+ if (!set && runSeen > 0) {
overallResult.setStatus(SyncResult::SyncRunning);
set = true;
}
- if( !set && goodSeen > 0 ) {
+ if (!set && goodSeen > 0) {
overallResult.setStatus(SyncResult::Success);
set = true;
}
return overallResult;
}
-QString FolderMan::statusToString( SyncResult::Status syncStatus, bool paused ) const
+QString FolderMan::statusToString(SyncResult::Status syncStatus, bool paused) const
{
QString folderMessage;
- switch( syncStatus ) {
+ switch (syncStatus) {
case SyncResult::Undefined:
- folderMessage = tr( "Undefined State." );
+ folderMessage = tr("Undefined State.");
break;
case SyncResult::NotYetStarted:
- folderMessage = tr( "Waiting to start syncing." );
+ folderMessage = tr("Waiting to start syncing.");
break;
case SyncResult::SyncPrepare:
- folderMessage = tr( "Preparing for sync." );
+ folderMessage = tr("Preparing for sync.");
break;
case SyncResult::SyncRunning:
- folderMessage = tr( "Sync is running." );
+ folderMessage = tr("Sync is running.");
break;
case SyncResult::Success:
- folderMessage = tr( "Last Sync was successful." );
+ folderMessage = tr("Last Sync was successful.");
break;
case SyncResult::Error:
break;
case SyncResult::Problem:
- folderMessage = tr( "Last Sync was successful, but with warnings on individual files.");
+ folderMessage = tr("Last Sync was successful, but with warnings on individual files.");
break;
case SyncResult::SetupError:
- folderMessage = tr( "Setup Error." );
+ folderMessage = tr("Setup Error.");
break;
case SyncResult::SyncAbortRequested:
- folderMessage = tr( "User Abort." );
+ folderMessage = tr("User Abort.");
break;
case SyncResult::Paused:
folderMessage = tr("Sync is paused.");
break;
- // no default case on purpose, check compiler warnings
+ // no default case on purpose, check compiler warnings
}
- if( paused ) {
+ if (paused) {
// sync is disabled.
- folderMessage = tr( "%1 (Sync is paused)" ).arg(folderMessage);
+ folderMessage = tr("%1 (Sync is paused)").arg(folderMessage);
}
return folderMessage;
}
-QString FolderMan::checkPathValidityForNewFolder(const QString& path, const QUrl &serverUrl, bool forNewDirectory) const
+QString FolderMan::checkPathValidityForNewFolder(const QString &path, const QUrl &serverUrl, bool forNewDirectory) const
{
if (path.isEmpty()) {
return tr("No valid folder selected!");
}
- QFileInfo selFile( path );
+ QFileInfo selFile(path);
if (!selFile.exists()) {
return checkPathValidityForNewFolder(selFile.dir().path(), serverUrl, true);
}
- if( !selFile.isDir() ) {
+ if (!selFile.isDir()) {
return tr("The selected path is not a folder!");
}
- if ( !selFile.isWritable() ) {
+ if (!selFile.isWritable()) {
return tr("You have no permission to write to the selected folder!");
}
// check if the local directory isn't used yet in another ownCloud sync
Qt::CaseSensitivity cs = Qt::CaseSensitive;
- if( Utility::fsCasePreserving() ) {
+ if (Utility::fsCasePreserving()) {
cs = Qt::CaseInsensitive;
}
- for (auto i = _folderMap.constBegin(); i != _folderMap.constEnd(); ++i ) {
- Folder *f = static_cast<Folder*>(i.value());
- QString folderDir = QDir( f->path() ).canonicalPath();
- if( folderDir.isEmpty() ) {
+ for (auto i = _folderMap.constBegin(); i != _folderMap.constEnd(); ++i) {
+ Folder *f = static_cast<Folder *>(i.value());
+ QString folderDir = QDir(f->path()).canonicalPath();
+ if (folderDir.isEmpty()) {
continue;
}
- if( ! folderDir.endsWith(QLatin1Char('/'), cs) ) folderDir.append(QLatin1Char('/'));
+ if (!folderDir.endsWith(QLatin1Char('/'), cs))
+ folderDir.append(QLatin1Char('/'));
- const QString folderDirClean = QDir::cleanPath(folderDir)+'/';
- const QString userDirClean = QDir::cleanPath(path)+'/';
+ const QString folderDirClean = QDir::cleanPath(folderDir) + '/';
+ const QString userDirClean = QDir::cleanPath(path) + '/';
// folderDir follows sym links, path not.
bool differentPathes = !Utility::fileNamesEqual(QDir::cleanPath(folderDir), QDir::cleanPath(path));
- if (!forNewDirectory && differentPathes && folderDirClean.startsWith(userDirClean,cs)) {
+ if (!forNewDirectory && differentPathes && folderDirClean.startsWith(userDirClean, cs)) {
return tr("The local folder %1 already contains a folder used in a folder sync connection. "
"Please pick another one!")
- .arg(QDir::toNativeSeparators(path));
+ .arg(QDir::toNativeSeparators(path));
}
// QDir::cleanPath keeps links
// canonicalPath() remove symlinks and uses the symlink targets.
- QString absCleanUserFolder = QDir::cleanPath(QDir(path).canonicalPath())+'/';
+ QString absCleanUserFolder = QDir::cleanPath(QDir(path).canonicalPath()) + '/';
- if ( (forNewDirectory || differentPathes) && userDirClean.startsWith( folderDirClean, cs )) {
+ if ((forNewDirectory || differentPathes) && userDirClean.startsWith(folderDirClean, cs)) {
return tr("The local folder %1 is already contained in a folder used in a folder sync connection. "
"Please pick another one!")
- .arg(QDir::toNativeSeparators(path));
+ .arg(QDir::toNativeSeparators(path));
}
// both follow symlinks.
- bool cleanUserEqualsCleanFolder = Utility::fileNamesEqual(absCleanUserFolder, folderDirClean );
- if (differentPathes && absCleanUserFolder.startsWith( folderDirClean, cs ) &&
- ! cleanUserEqualsCleanFolder ) {
+ bool cleanUserEqualsCleanFolder = Utility::fileNamesEqual(absCleanUserFolder, folderDirClean);
+ if (differentPathes && absCleanUserFolder.startsWith(folderDirClean, cs) && !cleanUserEqualsCleanFolder) {
return tr("The local folder %1 is a symbolic link. "
"The link target is already contained in a folder used in a folder sync connection. "
"Please pick another one!")
- .arg(QDir::toNativeSeparators(path));
+ .arg(QDir::toNativeSeparators(path));
}
- if (differentPathes && folderDirClean.startsWith(absCleanUserFolder, cs) &&
- !cleanUserEqualsCleanFolder && !forNewDirectory ) {
+ if (differentPathes && folderDirClean.startsWith(absCleanUserFolder, cs) && !cleanUserEqualsCleanFolder && !forNewDirectory) {
return tr("The local folder %1 contains a symbolic link. "
"The link target contains an already synced folder "
"Please pick another one!")
- .arg(QDir::toNativeSeparators(path));
+ .arg(QDir::toNativeSeparators(path));
}
// if both pathes are equal, the server url needs to be different
// otherwise it would mean that a new connection from the same local folder
// to the same account is added which is not wanted. The account must differ.
- if( serverUrl.isValid() && Utility::fileNamesEqual(absCleanUserFolder,folderDir ) ) {
+ if (serverUrl.isValid() && Utility::fileNamesEqual(absCleanUserFolder, folderDir)) {
QUrl folderUrl = f->accountState()->account()->url();
QString user = f->accountState()->account()->credentials()->user();
folderUrl.setUserName(user);
- if( serverUrl == folderUrl ) {
+ if (serverUrl == folderUrl) {
return tr("There is already a sync from the server to this local folder. "
"Please pick another local folder!");
}
}
return QString();
-
}
QString FolderMan::findGoodPathForNewSyncFolder(const QString &basePath, const QUrl &serverUrl) const
int attempt = 1;
forever {
const bool isGood =
- !QFileInfo(folder).exists()
- && FolderMan::instance()->checkPathValidityForNewFolder(folder, serverUrl).isEmpty();
+ !QFileInfo(folder).exists()
+ && FolderMan::instance()->checkPathValidityForNewFolder(folder, serverUrl).isEmpty();
if (isGood) {
break;
}
{
// Note that the setting will revert to 'true' if all folders
// are deleted...
- foreach (Folder* folder, _folderMap) {
+ foreach (Folder *folder, _folderMap) {
folder->setIgnoreHiddenFiles(ignore);
folder->saveToSettings();
}
}
-QQueue<Folder*> FolderMan::scheduleQueue() const
+QQueue<Folder *> FolderMan::scheduleQueue() const
{
return _scheduledFolders;
}
void FolderMan::restartApplication()
{
- if( Utility::isLinux() ) {
+ if (Utility::isLinux()) {
// restart:
qCInfo(lcFolderMan) << "Restarting application NOW, PID" << qApp->applicationPid() << "is ending.";
qApp->quit();
Q_OBJECT
public:
~FolderMan();
- static FolderMan* instance();
+ static FolderMan *instance();
int setupFolders();
int setupFoldersMigration();
/** Adds a folder for an account, ensures the journal is gone and saves it in the settings.
*/
- Folder* addFolder(AccountState* accountState, const FolderDefinition& folderDefinition);
+ Folder *addFolder(AccountState *accountState, const FolderDefinition &folderDefinition);
/** Removes a folder */
- void removeFolder( Folder* );
+ void removeFolder(Folder *);
/** Returns the folder which the file or directory stored in path is in */
- Folder* folderForPath(const QString& path);
+ Folder *folderForPath(const QString &path);
/**
* returns a list of local files that exist on the local harddisk for an
* incoming relative server path. The method checks with all existing sync
* folders.
*/
- QStringList findFileInLocalFolders( const QString& relPath, const AccountPtr acc );
+ QStringList findFileInLocalFolders(const QString &relPath, const AccountPtr acc);
/** Returns the folder by alias or NULL if no folder with the alias exists. */
- Folder *folder( const QString& );
+ Folder *folder(const QString &);
/**
* Migrate accounts from owncloud < 2.0
* Creates a folder for a specific configuration, identified by alias.
*/
- Folder* setupFolderFromOldConfigFile(const QString &, AccountState *account );
+ Folder *setupFolderFromOldConfigFile(const QString &, AccountState *account);
/**
* Ensures that a given directory does not contain a sync journal file.
*
* @returns false if the journal could not be removed, true otherwise.
*/
- static bool ensureJournalGone(const QString& journalDbFile);
+ static bool ensureJournalGone(const QString &journalDbFile);
/** Creates a new and empty local directory. */
- bool startFromScratch( const QString& );
+ bool startFromScratch(const QString &);
- QString statusToString(SyncResult::Status, bool paused ) const;
+ QString statusToString(SyncResult::Status, bool paused) const;
- static SyncResult accountStatus( const QList<Folder*> &folders );
+ static SyncResult accountStatus(const QList<Folder *> &folders);
- void removeMonitorPath( const QString& alias, const QString& path );
- void addMonitorPath( const QString& alias, const QString& path );
+ void removeMonitorPath(const QString &alias, const QString &path);
+ void addMonitorPath(const QString &alias, const QString &path);
// Escaping of the alias which is used in QSettings AND the file
// system, thus need to be escaped.
- static QString escapeAlias( const QString& );
- static QString unescapeAlias( const QString& );
+ static QString escapeAlias(const QString &);
+ static QString unescapeAlias(const QString &);
SocketApi *socketApi();
*
* @returns an empty string if it is allowed, or an error if it is not allowed
*/
- QString checkPathValidityForNewFolder(const QString &path, const QUrl& serverUrl = QUrl(), bool forNewDirectory = false) const;
+ QString checkPathValidityForNewFolder(const QString &path, const QUrl &serverUrl = QUrl(), bool forNewDirectory = false) const;
/**
* Attempts to find a non-existing, acceptable path for creating a new sync folder.
/**
* Access to the current queue of scheduled folders.
*/
- QQueue<Folder*> scheduleQueue() const;
+ QQueue<Folder *> scheduleQueue() const;
/**
* Access to the currently syncing folder.
*/
- Folder* currentSyncFolder() const;
+ Folder *currentSyncFolder() const;
/** Removes all folders */
int unloadAndDeleteAllFolders();
* If enabled is set to false, no new folders will start to sync.
* The current one will finish.
*/
- void setSyncEnabled( bool );
+ void setSyncEnabled(bool);
/** Queues a folder for syncing. */
- void scheduleFolder(Folder*);
+ void scheduleFolder(Folder *);
/** Puts a folder in the very front of the queue. */
- void scheduleFolderNext(Folder*);
+ void scheduleFolderNext(Folder *);
/** Queues all folders for syncing. */
void scheduleAllFolders();
*
* Attention: The folder may be zero. Do a general update of the state then.
*/
- void folderSyncStateChange(Folder*);
+ void folderSyncStateChange(Folder *);
/**
* Indicates when the schedule queue changes.
* Automatically detemines the folder that's responsible for the file.
* See slotWatchedFileUnlocked().
*/
- void slotSyncOnceFileUnlocks(const QString& path);
+ void slotSyncOnceFileUnlocks(const QString &path);
// slot to schedule an ETag job (from Folder only)
- void slotScheduleETagJob ( const QString &alias, RequestEtagJob *job);
+ void slotScheduleETagJob(const QString &alias, RequestEtagJob *job);
private slots:
void slotFolderSyncPaused(Folder *, bool paused);
void slotFolderCanSyncChanged();
void slotFolderSyncStarted();
- void slotFolderSyncFinished( const SyncResult& );
+ void slotFolderSyncFinished(const SyncResult &);
void slotRunOneEtagJob();
- void slotEtagJobDestroyed (QObject*);
+ void slotEtagJobDestroyed(QObject *);
// slot to take the next folder from queue and start syncing.
void slotStartScheduledFolderSync();
void slotEtagPollTimerTimeout();
- void slotRemoveFoldersForAccount(AccountState* accountState);
+ void slotRemoveFoldersForAccount(AccountState *accountState);
// Wraps the Folder::syncStateChange() signal into the
// FolderMan::folderSyncStateChange(Folder*) signal.
void slotForwardFolderSyncStateChange();
- void slotServerVersionChanged(Account* account);
+ void slotServerVersionChanged(Account *account);
/**
* A file whose locks were being monitored has become unlocked.
* This schedules the folder for synchronization that contains
* the file with the given path.
*/
- void slotWatchedFileUnlocked(const QString& path);
+ void slotWatchedFileUnlocked(const QString &path);
/**
* Schedules folders whose time to sync has come.
void slotScheduleFolderByTime();
private:
-
/** Adds a new folder, does not add it to the account settings and
* does not set an account on the new folder.
*/
- Folder* addFolderInternal(FolderDefinition folderDefinition,
- AccountState* accountState);
+ Folder *addFolderInternal(FolderDefinition folderDefinition,
+ AccountState *accountState);
/* unloads a folder object, does not delete it */
- void unloadFolder( Folder * );
+ void unloadFolder(Folder *);
/** Will start a sync after a bit of delay. */
void startScheduledSyncSoon();
// finds all folder configuration files
// and create the folders
- QString getBackupName( QString fullPathName ) const;
- void registerFolderMonitor( Folder *folder );
+ QString getBackupName(QString fullPathName) const;
+ void registerFolderMonitor(Folder *folder);
// restarts the application (Linux only)
void restartApplication();
- void setupFoldersHelper(QSettings& settings, AccountStatePtr account, bool backwardsCompatible);
+ void setupFoldersHelper(QSettings &settings, AccountStatePtr account, bool backwardsCompatible);
- QSet<Folder*> _disabledFolders;
- Folder::Map _folderMap;
- QString _folderConfigPath;
- Folder *_currentSyncFolder;
+ QSet<Folder *> _disabledFolders;
+ Folder::Map _folderMap;
+ QString _folderConfigPath;
+ Folder *_currentSyncFolder;
QPointer<Folder> _lastSyncFolder;
- bool _syncEnabled;
+ bool _syncEnabled;
/// Watching for file changes in folders
- QMap<QString, FolderWatcher*> _folderWatchers;
+ QMap<QString, FolderWatcher *> _folderWatchers;
/// Starts regular etag query jobs
QTimer _etagPollTimer;
QTimer _timeScheduler;
/// Scheduled folders that should be synced as soon as possible
- QQueue<Folder*> _scheduledFolders;
+ QQueue<Folder *> _scheduledFolders;
/// Picks the next scheduled folder and starts the sync
- QTimer _startScheduledSyncTimer;
+ QTimer _startScheduledSyncTimer;
QScopedPointer<SocketApi> _socketApi;
- bool _appRestartRequired;
+ bool _appRestartRequired;
static FolderMan *_instance;
explicit FolderMan(QObject *parent = 0);
{
QFont aliasFont = normalFont;
aliasFont.setBold(true);
- aliasFont.setPointSize(normalFont.pointSize()+2);
+ aliasFont.setPointSize(normalFont.pointSize() + 2);
return aliasFont;
}
namespace OCC {
-FolderStatusDelegate::FolderStatusDelegate() : QStyledItemDelegate() {
+FolderStatusDelegate::FolderStatusDelegate()
+ : QStyledItemDelegate()
+{
m_moreIcon = QIcon(QLatin1String(":/client/resources/more.png"));
}
}
// allocate each item size in listview.
-QSize FolderStatusDelegate::sizeHint(const QStyleOptionViewItem & option ,
- const QModelIndex & index) const
+QSize FolderStatusDelegate::sizeHint(const QStyleOptionViewItem &option,
+ const QModelIndex &index) const
{
QFont aliasFont = makeAliasFont(option.font);
QFont font = option.font;
auto classif = static_cast<const FolderStatusModel *>(index.model())->classify(index);
if (classif == FolderStatusModel::AddButton) {
- const int margins = aliasFm.height(); // same as 2*aliasMargin of paint
+ const int margins = aliasFm.height(); // same as 2*aliasMargin of paint
QFontMetrics fm(option.font);
QStyleOptionButton opt;
- static_cast<QStyleOption&>(opt) = option;
+ static_cast<QStyleOption &>(opt) = option;
opt.text = addFolderText();
return QApplication::style()->sizeFromContents(
- QStyle::CT_PushButton, &opt, fm.size(Qt::TextSingleLine, opt.text)).
- expandedTo(QApplication::globalStrut())
+ QStyle::CT_PushButton, &opt, fm.size(Qt::TextSingleLine, opt.text))
+ .expandedTo(QApplication::globalStrut())
+ QSize(0, margins);
}
int h = rootFolderHeightWithoutErrors(fm, aliasFm);
// add some space to show an error condition.
- if( ! qvariant_cast<QStringList>(index.data(FolderErrorMsg)).isEmpty() ) {
- int margin = fm.height()/4;
+ if (!qvariant_cast<QStringList>(index.data(FolderErrorMsg)).isEmpty()) {
+ int margin = fm.height() / 4;
QStringList errMsgs = qvariant_cast<QStringList>(index.data(FolderErrorMsg));
- h += margin + errMsgs.count()*fm.height();
+ h += margin + errMsgs.count() * fm.height();
}
- return QSize( 0, h);
+ return QSize(0, h);
}
int FolderStatusDelegate::rootFolderHeightWithoutErrors(const QFontMetrics &fm, const QFontMetrics &aliasFm)
{
- const int aliasMargin = aliasFm.height()/2;
- const int margin = fm.height()/4;
-
- int h = aliasMargin; // margin to top
- h += aliasFm.height(); // alias
- h += margin; // between alias and local path
- h += fm.height(); // local path
- h += margin; // between local and remote path
- h += fm.height(); // remote path
- h += aliasMargin; // bottom margin
+ const int aliasMargin = aliasFm.height() / 2;
+ const int margin = fm.height() / 4;
+
+ int h = aliasMargin; // margin to top
+ h += aliasFm.height(); // alias
+ h += margin; // between alias and local path
+ h += fm.height(); // local path
+ h += margin; // between local and remote path
+ h += fm.height(); // remote path
+ h += aliasMargin; // bottom margin
return h;
}
void FolderStatusDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
- const QModelIndex &index) const
+ const QModelIndex &index) const
{
- QStyledItemDelegate::paint(painter,option,index);
+ QStyledItemDelegate::paint(painter, option, index);
auto textAlign = Qt::AlignLeft;
QFont aliasFont = makeAliasFont(option.font);
- QFont subFont = option.font;
+ QFont subFont = option.font;
QFont errorFont = subFont;
QFont progressFont = subFont;
- progressFont.setPointSize( subFont.pointSize()-2);
+ progressFont.setPointSize(subFont.pointSize() - 2);
- QFontMetrics subFm( subFont );
- QFontMetrics aliasFm( aliasFont );
- QFontMetrics progressFm( progressFont );
+ QFontMetrics subFm(subFont);
+ QFontMetrics aliasFm(aliasFont);
+ QFontMetrics progressFm(progressFont);
- int aliasMargin = aliasFm.height()/2;
- int margin = subFm.height()/4;
+ int aliasMargin = aliasFm.height() / 2;
+ int margin = subFm.height() / 4;
if (index.data(AddButton).toBool()) {
QSize hint = sizeHint(option, index);
QStyleOptionButton opt;
- static_cast<QStyleOption&>(opt) = option;
+ static_cast<QStyleOption &>(opt) = option;
opt.state &= ~QStyle::State_Selected;
opt.state |= QStyle::State_Raised;
opt.text = addFolderText();
opt.rect.adjust(0, aliasMargin, 0, -aliasMargin);
opt.rect = QStyle::visualRect(option.direction, option.rect, opt.rect);
QApplication::style()->drawControl(QStyle::CE_PushButton, &opt, painter
-#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
- , option.widget
+#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
+ ,
+ option.widget
#endif
);
return;
}
painter->save();
- QIcon statusIcon = qvariant_cast<QIcon>(index.data(FolderStatusIconRole));
- QString aliasText = qvariant_cast<QString>(index.data(HeaderRole));
- QString pathText = qvariant_cast<QString>(index.data(FolderPathRole));
- QString remotePath = qvariant_cast<QString>(index.data(FolderSecondPathRole));
- QStringList errorTexts= qvariant_cast<QStringList>(index.data(FolderErrorMsg));
+ QIcon statusIcon = qvariant_cast<QIcon>(index.data(FolderStatusIconRole));
+ QString aliasText = qvariant_cast<QString>(index.data(HeaderRole));
+ QString pathText = qvariant_cast<QString>(index.data(FolderPathRole));
+ QString remotePath = qvariant_cast<QString>(index.data(FolderSecondPathRole));
+ QStringList errorTexts = qvariant_cast<QStringList>(index.data(FolderErrorMsg));
- int overallPercent = qvariant_cast<int>(index.data(SyncProgressOverallPercent));
+ int overallPercent = qvariant_cast<int>(index.data(SyncProgressOverallPercent));
QString overallString = qvariant_cast<QString>(index.data(SyncProgressOverallString));
- QString itemString = qvariant_cast<QString>(index.data(SyncProgressItemString));
- int warningCount = qvariant_cast<int>(index.data(WarningCount));
- bool syncOngoing = qvariant_cast<bool>(index.data(SyncRunning));
- bool syncEnabled = qvariant_cast<bool>(index.data(FolderAccountConnected));
+ QString itemString = qvariant_cast<QString>(index.data(SyncProgressItemString));
+ int warningCount = qvariant_cast<int>(index.data(WarningCount));
+ bool syncOngoing = qvariant_cast<bool>(index.data(SyncRunning));
+ bool syncEnabled = qvariant_cast<bool>(index.data(FolderAccountConnected));
QRect iconRect = option.rect;
QRect aliasRect = option.rect;
- iconRect.setLeft( option.rect.left() + aliasMargin );
- iconRect.setTop( iconRect.top() + aliasMargin ); // (iconRect.height()-iconsize.height())/2);
+ iconRect.setLeft(option.rect.left() + aliasMargin);
+ iconRect.setTop(iconRect.top() + aliasMargin); // (iconRect.height()-iconsize.height())/2);
// alias box
- aliasRect.setTop(aliasRect.top() + aliasMargin );
+ aliasRect.setTop(aliasRect.top() + aliasMargin);
aliasRect.setBottom(aliasRect.top() + aliasFm.height());
- aliasRect.setRight(aliasRect.right() - aliasMargin );
+ aliasRect.setRight(aliasRect.right() - aliasMargin);
// remote directory box
QRect remotePathRect = aliasRect;
- remotePathRect.setTop(aliasRect.bottom() + margin );
+ remotePathRect.setTop(aliasRect.bottom() + margin);
remotePathRect.setBottom(remotePathRect.top() + subFm.height());
// local directory box
QRect localPathRect = remotePathRect;
- localPathRect.setTop( remotePathRect.bottom() + margin );
- localPathRect.setBottom( localPathRect.top() + subFm.height());
+ localPathRect.setTop(remotePathRect.bottom() + margin);
+ localPathRect.setBottom(localPathRect.top() + subFm.height());
iconRect.setBottom(localPathRect.bottom());
iconRect.setWidth(iconRect.height());
- int nextToIcon = iconRect.right()+aliasMargin;
+ int nextToIcon = iconRect.right() + aliasMargin;
aliasRect.setLeft(nextToIcon);
localPathRect.setLeft(nextToIcon);
remotePathRect.setLeft(nextToIcon);
auto optionsButtonVisualRect = optionsButtonRect(option.rect, option.direction);
- QPixmap pm = statusIcon.pixmap(iconSize, iconSize, syncEnabled ? QIcon::Normal : QIcon::Disabled );
+ QPixmap pm = statusIcon.pixmap(iconSize, iconSize, syncEnabled ? QIcon::Normal : QIcon::Disabled);
painter->drawPixmap(QStyle::visualRect(option.direction, option.rect, iconRect).left(),
- iconRect.top(), pm);
+ iconRect.top(), pm);
// only show the warning icon if the sync is running. Otherwise its
// encoded in the status icon.
- if( warningCount > 0 && syncOngoing) {
+ if (warningCount > 0 && syncOngoing) {
QRect warnRect;
warnRect.setLeft(iconRect.left());
- warnRect.setTop(iconRect.bottom()-17);
+ warnRect.setTop(iconRect.bottom() - 17);
warnRect.setWidth(16);
warnRect.setHeight(16);
QIcon warnIcon(":/client/resources/warning");
- QPixmap pm = warnIcon.pixmap(16,16, syncEnabled ? QIcon::Normal : QIcon::Disabled );
+ QPixmap pm = warnIcon.pixmap(16, 16, syncEnabled ? QIcon::Normal : QIcon::Disabled);
warnRect = QStyle::visualRect(option.direction, option.rect, warnRect);
- painter->drawPixmap(QPoint(warnRect.left(), warnRect.top()),pm );
+ painter->drawPixmap(QPoint(warnRect.left(), warnRect.top()), pm);
}
auto palette = option.palette;
QPalette::ColorGroup cg = option.state & QStyle::State_Enabled
- ? QPalette::Normal : QPalette::Disabled;
+ ? QPalette::Normal
+ : QPalette::Disabled;
if (cg == QPalette::Normal && !(option.state & QStyle::State_Active))
cg = QPalette::Inactive;
painter->drawText(QStyle::visualRect(option.direction, option.rect, aliasRect), textAlign, elidedAlias);
const bool showProgess = !overallString.isEmpty() || !itemString.isEmpty();
- if(!showProgess) {
+ if (!showProgess) {
painter->setFont(subFont);
QString elidedRemotePathText = subFm.elidedText(
- tr("Synchronizing with local folder"),
- Qt::ElideRight, remotePathRect.width());
+ tr("Synchronizing with local folder"),
+ Qt::ElideRight, remotePathRect.width());
painter->drawText(QStyle::visualRect(option.direction, option.rect, remotePathRect),
- textAlign, elidedRemotePathText);
+ textAlign, elidedRemotePathText);
QString elidedPathText = subFm.elidedText(pathText, Qt::ElideMiddle, localPathRect.width());
painter->drawText(QStyle::visualRect(option.direction, option.rect, localPathRect),
- textAlign, elidedPathText);
+ textAlign, elidedPathText);
}
// paint an error overlay if there is an error string
int h = iconRect.bottom();
- if( !errorTexts.isEmpty() ) {
+ if (!errorTexts.isEmpty()) {
h += margin;
QRect errorRect = localPathRect;
- errorRect.setLeft( iconRect.left());
- errorRect.setTop( h );
+ errorRect.setLeft(iconRect.left());
+ errorRect.setTop(h);
errorRect.setHeight(errorTexts.count() * subFm.height() + 2 * margin);
- errorRect.setRight( option.rect.right() - margin );
+ errorRect.setRight(option.rect.right() - margin);
- painter->setBrush( QColor(0xbb, 0x4d, 0x4d) );
- painter->setPen( QColor(0xaa, 0xaa, 0xaa));
+ painter->setBrush(QColor(0xbb, 0x4d, 0x4d));
+ painter->setPen(QColor(0xaa, 0xaa, 0xaa));
painter->drawRoundedRect(QStyle::visualRect(option.direction, option.rect, errorRect),
- 4, 4);
- painter->setPen( Qt::white );
+ 4, 4);
+ painter->setPen(Qt::white);
painter->setFont(errorFont);
- QRect errorTextRect( errorRect.left() + margin,
+ QRect errorTextRect(errorRect.left() + margin,
errorRect.top() + margin,
errorRect.width() - 2 * margin,
- subFm.height() );
+ subFm.height());
- foreach( QString eText, errorTexts ) {
+ foreach (QString eText, errorTexts) {
painter->drawText(QStyle::visualRect(option.direction, option.rect, errorTextRect), textAlign,
- subFm.elidedText( eText, Qt::ElideLeft, errorTextRect.width()));
+ subFm.elidedText(eText, Qt::ElideLeft, errorTextRect.width()));
errorTextRect.translate(0, errorTextRect.height());
}
// Overall Progress Bar.
QRect pBRect;
- pBRect.setTop( remotePathRect.top() );
- pBRect.setLeft( nextToIcon );
+ pBRect.setTop(remotePathRect.top());
+ pBRect.setLeft(nextToIcon);
pBRect.setHeight(barHeight);
- pBRect.setWidth( overallWidth - 2 * margin );
+ pBRect.setWidth(overallWidth - 2 * margin);
-#if QT_VERSION < QT_VERSION_CHECK(5,0,0)
+#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
QStyleOptionProgressBarV2 pBarOpt;
#else
QStyleOptionProgressBar pBarOpt;
#endif
- pBarOpt.state = option.state | QStyle::State_Horizontal;
- pBarOpt.minimum = 0;
- pBarOpt.maximum = 100;
+ pBarOpt.state = option.state | QStyle::State_Horizontal;
+ pBarOpt.minimum = 0;
+ pBarOpt.maximum = 100;
pBarOpt.progress = overallPercent;
pBarOpt.orientation = Qt::Horizontal;
pBarOpt.rect = QStyle::visualRect(option.direction, option.rect, pBRect);
- QApplication::style()->drawControl( QStyle::CE_ProgressBar, &pBarOpt, painter );
+ QApplication::style()->drawControl(QStyle::CE_ProgressBar, &pBarOpt, painter);
// Overall Progress Text
QRect overallProgressRect;
- overallProgressRect.setTop( pBRect.bottom() + margin );
- overallProgressRect.setHeight( fileNameTextHeight );
- overallProgressRect.setLeft( pBRect.left() );
- overallProgressRect.setWidth( pBRect.width() );
+ overallProgressRect.setTop(pBRect.bottom() + margin);
+ overallProgressRect.setHeight(fileNameTextHeight);
+ overallProgressRect.setLeft(pBRect.left());
+ overallProgressRect.setWidth(pBRect.width());
painter->setFont(progressFont);
painter->drawText(QStyle::visualRect(option.direction, option.rect, overallProgressRect),
- Qt::AlignLeft | Qt::AlignVCenter, overallString);
+ Qt::AlignLeft | Qt::AlignVCenter, overallString);
// painter->drawRect(overallProgressRect);
painter->restore();
btnOpt.rect = optionsButtonVisualRect;
btnOpt.icon = m_moreIcon;
btnOpt.iconSize = btnOpt.rect.size();
- QApplication::style()->drawComplexControl( QStyle::CC_ToolButton, &btnOpt, painter );
+ QApplication::style()->drawComplexControl(QStyle::CC_ToolButton, &btnOpt, painter);
}
}
-bool FolderStatusDelegate::editorEvent ( QEvent * event, QAbstractItemModel * model,
- const QStyleOptionViewItem & option, const QModelIndex & index )
+bool FolderStatusDelegate::editorEvent(QEvent *event, QAbstractItemModel *model,
+ const QStyleOptionViewItem &option, const QModelIndex &index)
{
return QStyledItemDelegate::editorEvent(event, model, option, index);
}
opt.text = QLatin1String("...");
QSize textSize = fm.size(Qt::TextShowMnemonic, opt.text);
opt.rect.setSize(textSize);
- QSize size = QApplication::style()->sizeFromContents(QStyle::CT_ToolButton, &opt, textSize).
- expandedTo(QApplication::globalStrut());
+ QSize size = QApplication::style()->sizeFromContents(QStyle::CT_ToolButton, &opt, textSize).expandedTo(QApplication::globalStrut());
int margin = QApplication::style()->pixelMetric(QStyle::PM_DefaultLayoutSpacing);
QRect r(QPoint(within.right() - size.width() - margin,
- within.top() + within.height()/2 - size.height()/2),
- size);
+ within.top() + within.height() / 2 - size.height() / 2),
+ size);
return QStyle::visualRect(direction, within, r);
}
FolderStatusDelegate();
enum datarole { FolderAliasRole = Qt::UserRole + 100,
- HeaderRole,
- FolderPathRole, // for a SubFolder it's the complete path
- FolderSecondPathRole,
- FolderErrorMsg,
- FolderSyncPaused,
- FolderStatusIconRole,
- FolderAccountConnected,
+ HeaderRole,
+ FolderPathRole, // for a SubFolder it's the complete path
+ FolderSecondPathRole,
+ FolderErrorMsg,
+ FolderSyncPaused,
+ FolderStatusIconRole,
+ FolderAccountConnected,
- SyncProgressOverallPercent,
- SyncProgressOverallString,
- SyncProgressItemString,
- WarningCount,
- SyncRunning,
+ SyncProgressOverallPercent,
+ SyncProgressOverallString,
+ SyncProgressItemString,
+ WarningCount,
+ SyncRunning,
- AddButton // 1 = enabled; 2 = disabled
- };
- void paint( QPainter*, const QStyleOptionViewItem&, const QModelIndex& ) const Q_DECL_OVERRIDE;
- QSize sizeHint( const QStyleOptionViewItem&, const QModelIndex& ) const Q_DECL_OVERRIDE;
- bool editorEvent( QEvent* event, QAbstractItemModel* model, const QStyleOptionViewItem& option,
- const QModelIndex& index ) Q_DECL_OVERRIDE;
+ AddButton // 1 = enabled; 2 = disabled
+ };
+ void paint(QPainter *, const QStyleOptionViewItem &, const QModelIndex &) const Q_DECL_OVERRIDE;
+ QSize sizeHint(const QStyleOptionViewItem &, const QModelIndex &) const Q_DECL_OVERRIDE;
+ bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option,
+ const QModelIndex &index) Q_DECL_OVERRIDE;
/**
*/
static QRect optionsButtonRect(QRect within, Qt::LayoutDirection direction);
static int rootFolderHeightWithoutErrors(const QFontMetrics &fm, const QFontMetrics &aliasFm);
+
private:
static QString addFolderText();
};
} // namespace OCC
-
static const char propertyParentIndexC[] = "oc_parentIndex";
static const char propertyPermissionMap[] = "oc_permissionMap";
-static QString removeTrailingSlash(const QString &s) {
+static QString removeTrailingSlash(const QString &s)
+{
if (s.endsWith('/')) {
return s.left(s.size() - 1);
}
}
FolderStatusModel::FolderStatusModel(QObject *parent)
- :QAbstractItemModel(parent), _accountState(0), _dirty(false)
+ : QAbstractItemModel(parent)
+ , _accountState(0)
+ , _dirty(false)
{
}
FolderStatusModel::~FolderStatusModel()
-{ }
+{
+}
-static bool sortByFolderHeader(const FolderStatusModel::SubFolderInfo& lhs, const FolderStatusModel::SubFolderInfo& rhs)
+static bool sortByFolderHeader(const FolderStatusModel::SubFolderInfo &lhs, const FolderStatusModel::SubFolderInfo &rhs)
{
return QString::compare(lhs._folder->shortGuiRemotePathOrAppName(),
- rhs._folder->shortGuiRemotePathOrAppName(),
- Qt::CaseInsensitive) < 0;
+ rhs._folder->shortGuiRemotePathOrAppName(),
+ Qt::CaseInsensitive)
+ < 0;
}
-void FolderStatusModel::setAccountState(const AccountState* accountState)
+void FolderStatusModel::setAccountState(const AccountState *accountState)
{
beginResetModel();
_dirty = false;
_folders.clear();
_accountState = accountState;
- connect(FolderMan::instance(), SIGNAL(folderSyncStateChange(Folder*)),
- SLOT(slotFolderSyncStateChange(Folder*)), Qt::UniqueConnection);
+ connect(FolderMan::instance(), SIGNAL(folderSyncStateChange(Folder *)),
+ SLOT(slotFolderSyncStateChange(Folder *)), Qt::UniqueConnection);
connect(FolderMan::instance(), SIGNAL(scheduleQueueChanged()),
- SLOT(slotFolderScheduleQueueChanged()), Qt::UniqueConnection);
+ SLOT(slotFolderScheduleQueueChanged()), Qt::UniqueConnection);
auto folders = FolderMan::instance()->map();
foreach (auto f, folders) {
- if (!accountState)
- break;
+ if (!accountState)
+ break;
if (f->accountState() != accountState)
continue;
SubFolderInfo info;
}
-Qt::ItemFlags FolderStatusModel::flags ( const QModelIndex &index ) const
+Qt::ItemFlags FolderStatusModel::flags(const QModelIndex &index) const
{
- if (!_accountState) {
- return 0;
- }
+ if (!_accountState) {
+ return 0;
+ }
switch (classify(index)) {
- case AddButton: {
- Qt::ItemFlags ret;
+ case AddButton: {
+ Qt::ItemFlags ret;
#if QT_VERSION >= QT_VERSION_CHECK(5, 1, 0)
- ret = Qt::ItemNeverHasChildren;
+ ret = Qt::ItemNeverHasChildren;
#endif
- if (!_accountState->isConnected()) {
+ if (!_accountState->isConnected()) {
+ return ret;
+ } else if (_folders.count() == 1) {
+ auto remotePath = _folders.at(0)._folder->remotePath();
+ // special case when syncing the entire owncloud: disable the add folder button (#3438)
+ if (remotePath.isEmpty() || remotePath == QLatin1String("/")) {
return ret;
- } else if (_folders.count() == 1) {
- auto remotePath = _folders.at(0)._folder->remotePath();
- // special case when syncing the entire owncloud: disable the add folder button (#3438)
- if (remotePath.isEmpty() || remotePath == QLatin1String("/")) {
- return ret;
- }
}
- return Qt::ItemIsEnabled | ret;
}
- case FetchLabel:
- return Qt::ItemIsEnabled
+ return Qt::ItemIsEnabled | ret;
+ }
+ case FetchLabel:
+ return Qt::ItemIsEnabled
#if QT_VERSION >= QT_VERSION_CHECK(5, 1, 0)
- | Qt::ItemNeverHasChildren
+ | Qt::ItemNeverHasChildren
#endif
- ;
- case RootFolder:
- return Qt::ItemIsEnabled;
- case SubFolder:
- return Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | Qt::ItemIsSelectable;
+ ;
+ case RootFolder:
+ return Qt::ItemIsEnabled;
+ case SubFolder:
+ return Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | Qt::ItemIsSelectable;
}
return 0;
}
if (role == Qt::EditRole)
return QVariant();
- switch(classify(index)) {
+ switch (classify(index)) {
case AddButton: {
if (role == FolderStatusDelegate::AddButton) {
return QVariant(true);
} else if (role == Qt::ToolTipRole) {
if (!_accountState->isConnected()) {
return tr("You need to be connected to add a folder");
- } if (_folders.count() == 1) {
+ }
+ if (_folders.count() == 1) {
auto remotePath = _folders.at(0)._folder->remotePath();
if (remotePath.isEmpty() || remotePath == QLatin1String("/")) {
// Syncing the entire owncloud: disable the add folder button (#3438)
return tr("Adding folder is disabled because you are already syncing all your files. "
- "If you want to sync multiple folders, please remove the currently "
- "configured root folder.");
+ "If you want to sync multiple folders, please remove the currently "
+ "configured root folder.");
}
}
return tr("Click this button to add a folder to synchronize.");
}
return QVariant();
}
- case SubFolder:
- {
+ case SubFolder: {
const auto &x = static_cast<SubFolderInfo *>(index.internalPointer())->_subs[index.row()];
switch (role) {
case Qt::DisplayRole:
if (!f)
return QVariant();
return QVariant(f->path() + x._path);
- }
+ }
}
}
return QVariant();
- case FetchLabel:
- {
+ case FetchLabel: {
const auto x = static_cast<SubFolderInfo *>(index.internalPointer());
- switch(role) {
- case Qt::DisplayRole:
- if (x->_hasError) {
- return QVariant(tr("Error while loading the list of folders from the server.")
- + QString("\n") + x->_lastErrorString);
- } else {
- return tr("Fetching folder list from server...");
- }
- break;
- default: return QVariant();
+ switch (role) {
+ case Qt::DisplayRole:
+ if (x->_hasError) {
+ return QVariant(tr("Error while loading the list of folders from the server.")
+ + QString("\n") + x->_lastErrorString);
+ } else {
+ return tr("Fetching folder list from server...");
+ }
+ break;
+ default:
+ return QVariant();
}
}
case RootFolder:
break;
}
- const SubFolderInfo & folderInfo = _folders.at(index.row());
+ const SubFolderInfo &folderInfo = _folders.at(index.row());
auto f = folderInfo._folder;
if (!f)
return QVariant();
- const SubFolderInfo::Progress & progress = folderInfo._progress;
+ const SubFolderInfo::Progress &progress = folderInfo._progress;
const bool accountConnected = _accountState->isConnected();
switch (role) {
- case FolderStatusDelegate::FolderPathRole : return f->shortGuiLocalPath();
- case FolderStatusDelegate::FolderSecondPathRole : return f->remotePath();
- case FolderStatusDelegate::FolderErrorMsg : return f->syncResult().errorStrings();
- case FolderStatusDelegate::SyncRunning : return f->syncResult().status() == SyncResult::SyncRunning;
- case FolderStatusDelegate::HeaderRole : return f->shortGuiRemotePathOrAppName();
- case FolderStatusDelegate::FolderAliasRole : return f->alias();
- case FolderStatusDelegate::FolderSyncPaused : return f->syncPaused();
- case FolderStatusDelegate::FolderAccountConnected : return accountConnected;
+ case FolderStatusDelegate::FolderPathRole:
+ return f->shortGuiLocalPath();
+ case FolderStatusDelegate::FolderSecondPathRole:
+ return f->remotePath();
+ case FolderStatusDelegate::FolderErrorMsg:
+ return f->syncResult().errorStrings();
+ case FolderStatusDelegate::SyncRunning:
+ return f->syncResult().status() == SyncResult::SyncRunning;
+ case FolderStatusDelegate::HeaderRole:
+ return f->shortGuiRemotePathOrAppName();
+ case FolderStatusDelegate::FolderAliasRole:
+ return f->alias();
+ case FolderStatusDelegate::FolderSyncPaused:
+ return f->syncPaused();
+ case FolderStatusDelegate::FolderAccountConnected:
+ return accountConnected;
case Qt::ToolTipRole: {
QString toolTip;
if (!progress.isNull()) {
return progress._progressString;
}
- if ( accountConnected )
+ if (accountConnected)
toolTip = Theme::instance()->statusHeaderText(f->syncResult().status());
else
toolTip = tr("Signed out");
return toolTip;
}
case FolderStatusDelegate::FolderStatusIconRole:
- if ( accountConnected ) {
+ if (accountConnected) {
auto theme = Theme::instance();
auto status = f->syncResult().status();
- if( f->syncPaused() ) {
- return theme->folderDisabledIcon( );
+ if (f->syncPaused()) {
+ return theme->folderDisabledIcon();
} else {
- if( status == SyncResult::SyncPrepare ) {
+ if (status == SyncResult::SyncPrepare) {
+ return theme->syncStateIcon(SyncResult::SyncRunning);
+ } else if (status == SyncResult::Undefined) {
return theme->syncStateIcon(SyncResult::SyncRunning);
- } else if( status == SyncResult::Undefined ) {
- return theme->syncStateIcon( SyncResult::SyncRunning);
} else {
// keep the previous icon for the prepare phase.
- if( status == SyncResult::Problem) {
- return theme->syncStateIcon( SyncResult::Success);
+ if (status == SyncResult::Problem) {
+ return theme->syncStateIcon(SyncResult::Success);
} else {
- return theme->syncStateIcon( status );
+ return theme->syncStateIcon(status);
}
}
}
return QVariant();
}
-bool FolderStatusModel::setData(const QModelIndex& index, const QVariant& value, int role)
+bool FolderStatusModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
- if(role == Qt::CheckStateRole) {
+ if (role == Qt::CheckStateRole) {
auto info = infoForIndex(index);
Qt::CheckState checked = static_cast<Qt::CheckState>(value.toInt());
auto parentInfo = infoForIndex(parent);
if (parentInfo && parentInfo->_checked != Qt::Checked) {
bool hasUnchecked = false;
- foreach(const auto &sub, parentInfo->_subs) {
+ foreach (const auto &sub, parentInfo->_subs) {
if (sub._checked != Qt::Checked) {
hasUnchecked = true;
break;
setData(parent, Qt::PartiallyChecked, Qt::CheckStateRole);
}
}
-
}
_dirty = true;
emit dirtyChanged();
}
-int FolderStatusModel::columnCount(const QModelIndex&) const
+int FolderStatusModel::columnCount(const QModelIndex &) const
{
return 1;
}
-int FolderStatusModel::rowCount(const QModelIndex& parent) const
+int FolderStatusModel::rowCount(const QModelIndex &parent) const
{
if (!parent.isValid()) {
- if( Theme::instance()->singleSyncFolder() && _folders.count() != 0) {
+ if (Theme::instance()->singleSyncFolder() && _folders.count() != 0) {
// "Add folder" button not visible in the singleSyncFolder configuration.
return _folders.count();
}
return info->_subs.count();
}
-FolderStatusModel::ItemType FolderStatusModel::classify(const QModelIndex& index) const
+FolderStatusModel::ItemType FolderStatusModel::classify(const QModelIndex &index) const
{
- if (auto sub = static_cast<SubFolderInfo*>(index.internalPointer())) {
+ if (auto sub = static_cast<SubFolderInfo *>(index.internalPointer())) {
if (sub->hasLabel()) {
return FetchLabel;
} else {
return AddButton;
}
-FolderStatusModel::SubFolderInfo* FolderStatusModel::infoForIndex(const QModelIndex& index) const
+FolderStatusModel::SubFolderInfo *FolderStatusModel::infoForIndex(const QModelIndex &index) const
{
if (!index.isValid())
return 0;
- if (auto parentInfo = static_cast<SubFolderInfo*>(index.internalPointer())) {
+ if (auto parentInfo = static_cast<SubFolderInfo *>(index.internalPointer())) {
if (parentInfo->hasLabel()) {
return 0;
}
}
}
-QModelIndex FolderStatusModel::indexForPath(Folder *f, const QString& path) const
+QModelIndex FolderStatusModel::indexForPath(Folder *f, const QString &path) const
{
- if( !f ) {
+ if (!f) {
return QModelIndex();
}
if (slashPos == -1) {
// first level folder
for (int i = 0; i < _folders.size(); ++i) {
- auto& info = _folders.at(i);
+ auto &info = _folders.at(i);
if (info._folder == f) {
- if( path.isEmpty() ) { // the folder object
+ if (path.isEmpty()) { // the folder object
return index(i, 0);
}
for (int j = 0; j < info._subs.size(); ++j) {
return QModelIndex();
}
for (int i = 0; i < parentInfo->_subs.size(); ++i) {
- if (parentInfo->_subs.at(i)._name == path.mid(slashPos + 1)) {
+ if (parentInfo->_subs.at(i)._name == path.mid(slashPos + 1)) {
return index(i, 0, parent);
}
}
return QModelIndex();
}
-QModelIndex FolderStatusModel::index(int row, int column, const QModelIndex& parent) const
+QModelIndex FolderStatusModel::index(int row, int column, const QModelIndex &parent) const
{
if (!parent.isValid()) {
- return createIndex(row, column/*, nullptr*/);
- }
- switch(classify(parent)) {
- case AddButton:
- case FetchLabel:
- return QModelIndex();
- case RootFolder:
- if (_folders.count() <= parent.row())
- return QModelIndex(); // should not happen
- return createIndex(row, column, const_cast<SubFolderInfo *>(&_folders[parent.row()]));
- case SubFolder: {
- auto pinfo = static_cast<SubFolderInfo*>(parent.internalPointer());
- if (pinfo->_subs.count() <= parent.row())
- return QModelIndex(); // should not happen
- auto & info = pinfo->_subs[parent.row()];
- if (!info.hasLabel()
- && info._subs.count() <= row)
- return QModelIndex(); // should not happen
- return createIndex(row, column, &info);
- }
+ return createIndex(row, column /*, nullptr*/);
+ }
+ switch (classify(parent)) {
+ case AddButton:
+ case FetchLabel:
+ return QModelIndex();
+ case RootFolder:
+ if (_folders.count() <= parent.row())
+ return QModelIndex(); // should not happen
+ return createIndex(row, column, const_cast<SubFolderInfo *>(&_folders[parent.row()]));
+ case SubFolder: {
+ auto pinfo = static_cast<SubFolderInfo *>(parent.internalPointer());
+ if (pinfo->_subs.count() <= parent.row())
+ return QModelIndex(); // should not happen
+ auto &info = pinfo->_subs[parent.row()];
+ if (!info.hasLabel()
+ && info._subs.count() <= row)
+ return QModelIndex(); // should not happen
+ return createIndex(row, column, &info);
+ }
}
return QModelIndex();
}
-QModelIndex FolderStatusModel::parent(const QModelIndex& child) const
+QModelIndex FolderStatusModel::parent(const QModelIndex &child) const
{
if (!child.isValid()) {
return QModelIndex();
}
- switch(classify(child)) {
- case RootFolder:
- case AddButton:
- return QModelIndex();
- case SubFolder:
- case FetchLabel:
- break;
+ switch (classify(child)) {
+ case RootFolder:
+ case AddButton:
+ return QModelIndex();
+ case SubFolder:
+ case FetchLabel:
+ break;
}
- auto pathIdx = static_cast<SubFolderInfo*>(child.internalPointer())->_pathIdx;
+ auto pathIdx = static_cast<SubFolderInfo *>(child.internalPointer())->_pathIdx;
int i = 1;
ASSERT(pathIdx.at(0) < _folders.count());
if (pathIdx.count() == 1) {
- return createIndex(pathIdx.at(0), 0/*, nullptr*/);
+ return createIndex(pathIdx.at(0), 0 /*, nullptr*/);
}
const SubFolderInfo *info = &_folders[pathIdx.at(0)];
return createIndex(pathIdx.at(i), 0, const_cast<SubFolderInfo *>(info));
}
-bool FolderStatusModel::hasChildren(const QModelIndex& parent) const
+bool FolderStatusModel::hasChildren(const QModelIndex &parent) const
{
if (!parent.isValid())
return true;
}
-bool FolderStatusModel::canFetchMore(const QModelIndex& parent) const
+bool FolderStatusModel::canFetchMore(const QModelIndex &parent) const
{
if (!_accountState) {
- return false;
- }
+ return false;
+ }
if (_accountState->state() != AccountState::Connected) {
return false;
}
}
-void FolderStatusModel::fetchMore(const QModelIndex& parent)
+void FolderStatusModel::fetchMore(const QModelIndex &parent)
{
auto info = infoForIndex(parent);
path += info->_path;
}
LsColJob *job = new LsColJob(_accountState->account(), path, this);
- job->setProperties(QList<QByteArray>() << "resourcetype" << "http://owncloud.org/ns:size" << "http://owncloud.org/ns:permissions");
+ job->setProperties(QList<QByteArray>() << "resourcetype"
+ << "http://owncloud.org/ns:size"
+ << "http://owncloud.org/ns:permissions");
job->setTimeout(60 * 1000);
connect(job, SIGNAL(directoryListingSubfolders(QStringList)),
- SLOT(slotUpdateDirectories(QStringList)));
- connect(job, SIGNAL(finishedWithError(QNetworkReply*)),
- this, SLOT(slotLscolFinishedWithError(QNetworkReply*)));
- connect(job, SIGNAL(directoryListingIterated(const QString&, const QMap<QString,QString>&)),
- this, SLOT(slotGatherPermissions(const QString&, const QMap<QString,QString>&)));
+ SLOT(slotUpdateDirectories(QStringList)));
+ connect(job, SIGNAL(finishedWithError(QNetworkReply *)),
+ this, SLOT(slotLscolFinishedWithError(QNetworkReply *)));
+ connect(job, SIGNAL(directoryListingIterated(const QString &, const QMap<QString, QString> &)),
+ this, SLOT(slotGatherPermissions(const QString &, const QMap<QString, QString> &)));
job->start();
QPersistentModelIndex persistentIndex(parent);
- job->setProperty(propertyParentIndexC , QVariant::fromValue(persistentIndex));
+ job->setProperty(propertyParentIndexC, QVariant::fromValue(persistentIndex));
// Show 'fetching data...' hint after a while.
_fetchingItems[persistentIndex].start();
QTimer::singleShot(1000, this, SLOT(slotShowFetchProgress()));
}
-void FolderStatusModel::slotGatherPermissions(const QString &href, const QMap<QString,QString> &map)
+void FolderStatusModel::slotGatherPermissions(const QString &href, const QMap<QString, QString> &map)
{
auto it = map.find("permissions");
if (it == map.end())
}
if (parentInfo->hasLabel()) {
- beginRemoveRows(idx, 0 ,0);
+ beginRemoveRows(idx, 0, 0);
parentInfo->_lastErrorString.clear();
parentInfo->_hasError = false;
parentInfo->_fetchingLabel = false;
}
auto selectiveSyncUndecidedList = parentInfo->_folder->journalDb()->getSelectiveSyncList(SyncJournalDb::SelectiveSyncUndecidedList, &ok2);
- if( !(ok1 && ok2) ) {
+ if (!(ok1 && ok2)) {
qCWarning(lcFolderStatus) << "Could not retrieve selective sync info from journal";
return;
}
QVector<SubFolderInfo> newSubs;
newSubs.reserve(sortedSubfolders.size());
- foreach (const QString& path, sortedSubfolders) {
+ foreach (const QString &path, sortedSubfolders) {
auto relativePath = path.mid(pathToRemove.size());
if (parentInfo->_folder->isFileExcludedRelative(relativePath)) {
continue;
} else if (parentInfo->_checked == Qt::Checked) {
newInfo._checked = Qt::Checked;
} else {
- foreach(const QString &str , selectiveSyncBlackList) {
+ foreach (const QString &str, selectiveSyncBlackList) {
if (str == relativePath || str == QLatin1String("/")) {
newInfo._checked = Qt::Unchecked;
break;
// Remove all the items from the selectiveSyncUndecidedSet that starts with this path
QString relativePathNext = relativePath;
- relativePathNext[relativePathNext.length()-1].unicode()++;
+ relativePathNext[relativePathNext.length() - 1].unicode()++;
auto it2 = selectiveSyncUndecidedSet.lower_bound(relativePathNext);
selectiveSyncUndecidedSet.erase(it, it2);
}
suggestExpand(idx.child(*it, 0));
}
- /* We need lambda function for the following code.
+/* We need lambda function for the following code.
* It's just a small feature that will be missing if the comiler is too old */
#if !(defined(Q_CC_GNU) && !defined(Q_CC_INTEL) && !defined(Q_CC_CLANG)) || (__GNUC__ * 100 + __GNUC_MINOR__ >= 405)
/* Try to remove the the undecided lists the items that are not on the server. */
auto it = std::remove_if(selectiveSyncUndecidedList.begin(), selectiveSyncUndecidedList.end(),
- [&](const QString &s) { return selectiveSyncUndecidedSet.count(s); } );
+ [&](const QString &s) { return selectiveSyncUndecidedSet.count(s); });
if (it != selectiveSyncUndecidedList.end()) {
selectiveSyncUndecidedList.erase(it, selectiveSyncUndecidedList.end());
parentInfo->_folder->journalDb()->setSelectiveSyncList(
- SyncJournalDb::SelectiveSyncUndecidedList, selectiveSyncUndecidedList);
+ SyncJournalDb::SelectiveSyncUndecidedList, selectiveSyncUndecidedList);
emit dirtyChanged();
}
#endif
}
-void FolderStatusModel::slotLscolFinishedWithError(QNetworkReply* r)
+void FolderStatusModel::slotLscolFinishedWithError(QNetworkReply *r)
{
auto job = qobject_cast<LsColJob *>(sender());
ASSERT(job);
}
QStringList FolderStatusModel::createBlackList(FolderStatusModel::SubFolderInfo *root,
- const QStringList &oldBlackList) const
+ const QStringList &oldBlackList) const
{
- if (!root) return QStringList();
-
- switch(root->_checked) {
- case Qt::Unchecked:
- return QStringList(root->_path);
- case Qt::Checked:
- return QStringList();
- case Qt::PartiallyChecked:
- break;
+ if (!root)
+ return QStringList();
+
+ switch (root->_checked) {
+ case Qt::Unchecked:
+ return QStringList(root->_path);
+ case Qt::Checked:
+ return QStringList();
+ case Qt::PartiallyChecked:
+ break;
}
QStringList result;
} else {
// We did not load from the server so we re-use the one from the old black list
QString path = root->_path;
- foreach (const QString & it, oldBlackList) {
+ foreach (const QString &it, oldBlackList) {
if (it.startsWith(path))
result += it;
}
void FolderStatusModel::slotUpdateFolderState(Folder *folder)
{
- if( ! folder ) return;
+ if (!folder)
+ return;
for (int i = 0; i < _folders.count(); ++i) {
if (_folders.at(i)._folder == folder) {
emit dataChanged(index(i), index(i));
bool ok;
auto oldBlackList = folder->journalDb()->getSelectiveSyncList(SyncJournalDb::SelectiveSyncBlackList, &ok);
- if( !ok ) {
+ if (!ok) {
qCWarning(lcFolderStatus) << "Could not read selective sync list from db.";
return;
}
// The folders that were undecided or blacklisted and that are now checked should go on the white list.
// The user confirmed them already just now.
- QStringList toAddToWhiteList = ((oldBlackListSet + folder->journalDb()->getSelectiveSyncList(
- SyncJournalDb::SelectiveSyncUndecidedList, &ok).toSet()) - blackListSet).toList();
+ QStringList toAddToWhiteList = ((oldBlackListSet + folder->journalDb()->getSelectiveSyncList(SyncJournalDb::SelectiveSyncUndecidedList, &ok).toSet()) - blackListSet).toList();
if (!toAddToWhiteList.isEmpty()) {
auto whiteList = folder->journalDb()->getSelectiveSyncList(SyncJournalDb::SelectiveSyncWhiteList, &ok);
}
//The part that changed should not be read from the DB on next sync because there might be new folders
// (the ones that are no longer in the blacklist)
- foreach(const auto &it, changes) {
+ foreach (const auto &it, changes) {
folder->journalDb()->avoidReadFromDbOnNextSync(it);
}
FolderMan::instance()->scheduleFolder(folder);
void FolderStatusModel::slotSetProgress(const ProgressInfo &progress)
{
- auto par = qobject_cast<QWidget*>(QObject::parent());
+ auto par = qobject_cast<QWidget *>(QObject::parent());
if (!par->isVisible()) {
return; // for https://github.com/owncloud/client/issues/2648#issuecomment-71377909
}
- Folder *f = qobject_cast<Folder*>(sender());
- if( !f ) { return; }
+ Folder *f = qobject_cast<Folder *>(sender());
+ if (!f) {
+ return;
+ }
int folderIndex = -1;
for (int i = 0; i < _folders.count(); ++i) {
break;
}
}
- if (folderIndex < 0) { return; }
+ if (folderIndex < 0) {
+ return;
+ }
auto *pi = &_folders[folderIndex]._progress;
return;
}
- if(!progress._lastCompletedItem.isEmpty()
- && Progress::isWarningKind(progress._lastCompletedItem._status)) {
+ if (!progress._lastCompletedItem.isEmpty()
+ && Progress::isWarningKind(progress._lastCompletedItem._status)) {
pi->_warningCount++;
}
quint64 estimatedUpBw = 0;
quint64 estimatedDownBw = 0;
QString allFilenames;
- foreach(const ProgressInfo::ProgressItem &citm, progress._currentItems) {
+ foreach (const ProgressInfo::ProgressItem &citm, progress._currentItems) {
if (curItemProgress == -1 || (ProgressInfo::isSizeDependent(citm._item)
- && biggerItemSize < citm._item._size)) {
+ && biggerItemSize < citm._item._size)) {
curItemProgress = citm._progress.completed();
curItem = citm._item;
biggerItemSize = citm._item._size;
}
- if (citm._item._direction != SyncFileItem::Up){
+ if (citm._item._direction != SyncFileItem::Up) {
estimatedDownBw += progress.fileProgress(citm._item).estimatedBandwidth;
} else {
estimatedUpBw += progress.fileProgress(citm._item).estimatedBandwidth;
QString fileProgressString;
if (ProgressInfo::isSizeDependent(curItem)) {
- QString s1 = Utility::octetsToString( curItemProgress );
- QString s2 = Utility::octetsToString( curItem._size );
+ QString s1 = Utility::octetsToString(curItemProgress);
+ QString s2 = Utility::octetsToString(curItem._size);
//quint64 estimatedBw = progress.fileProgress(curItem).estimatedBandwidth;
if (estimatedUpBw || estimatedDownBw) {
/*
//: Example text: "download 24Kb/s" (%1 is replaced by 24Kb (translated))
fileProgressString.append(tr("download %1/s").arg(Utility::octetsToString(estimatedDownBw)));
#else
- fileProgressString.append(trUtf8("\u2193" " %1/s").arg(Utility::octetsToString(estimatedDownBw)));
+ fileProgressString.append(trUtf8("\u2193"
+ " %1/s")
+ .arg(Utility::octetsToString(estimatedDownBw)));
#endif
}
if (estimatedUpBw > 0) {
fileProgressString.append(tr(", "));
- #ifdef Q_OS_WIN
+#ifdef Q_OS_WIN
//: Example text: "upload 24Kb/s" (%1 is replaced by 24Kb (translated))
fileProgressString.append(tr("upload %1/s").arg(Utility::octetsToString(estimatedUpBw)));
#else
- fileProgressString.append(trUtf8("\u2191" " %1/s").arg(Utility::octetsToString(estimatedUpBw)));
+ fileProgressString.append(trUtf8("\u2191"
+ " %1/s")
+ .arg(Utility::octetsToString(estimatedUpBw)));
#endif
}
} else {
//: Example text: "uploading foobar.png (2MB of 2MB)"
- fileProgressString = tr("%1 %2 (%3 of %4)") .arg(kindString, itemFileName, s1, s2);
+ fileProgressString = tr("%1 %2 (%3 of %4)").arg(kindString, itemFileName, s1, s2);
}
} else if (!kindString.isEmpty()) {
//: Example text: "uploading foobar.png"
quint64 totalFileCount = qMax(currentFile, progress.totalFiles());
QString overallSyncString;
if (totalSize > 0) {
- QString s1 = Utility::octetsToString( completedSize );
- QString s2 = Utility::octetsToString( totalSize );
+ QString s1 = Utility::octetsToString(completedSize);
+ QString s2 = Utility::octetsToString(totalSize);
if (progress.trustEta()) {
//: Example text: "5 minutes left, 12 MB of 345 MB, file 6 of 7"
overallSyncString = tr("%5 left, %1 of %2, file %3 of %4")
- .arg(s1, s2)
- .arg(currentFile).arg(totalFileCount)
- .arg( Utility::durationToDescriptiveString1(progress.totalProgress().estimatedEta) );
+ .arg(s1, s2)
+ .arg(currentFile)
+ .arg(totalFileCount)
+ .arg(Utility::durationToDescriptiveString1(progress.totalProgress().estimatedEta));
} else {
//: Example text: "12 MB of 345 MB, file 6 of 7"
overallSyncString = tr("%1 of %2, file %3 of %4")
- .arg(s1, s2)
- .arg(currentFile).arg(totalFileCount);
+ .arg(s1, s2)
+ .arg(currentFile)
+ .arg(totalFileCount);
}
} else if (totalFileCount > 0) {
// Don't attempt to estimate the time left if there is no kb to transfer.
- overallSyncString = tr("file %1 of %2") .arg(currentFile).arg(totalFileCount);
+ overallSyncString = tr("file %1 of %2").arg(currentFile).arg(totalFileCount);
}
- pi->_overallSyncString = overallSyncString;
+ pi->_overallSyncString = overallSyncString;
int overallPercent = 0;
- if( totalFileCount > 0 ) {
+ if (totalFileCount > 0) {
// Add one 'byte' for each file so the percentage is moving when deleting or renaming files
- overallPercent = qRound(double(completedSize + completedFile)/double(totalSize + totalFileCount) * 100.0);
+ overallPercent = qRound(double(completedSize + completedFile) / double(totalSize + totalFileCount) * 100.0);
}
pi->_overallPercent = qBound(0, overallPercent, 100);
emit dataChanged(index(folderIndex), index(folderIndex), roles);
void FolderStatusModel::slotFolderSyncStateChange(Folder *f)
{
- if( !f ) { return; }
+ if (!f) {
+ return;
+ }
int folderIndex = -1;
for (int i = 0; i < _folders.count(); ++i) {
break;
}
}
- if (folderIndex < 0) { return; }
+ if (folderIndex < 0) {
+ return;
+ }
- auto& pi = _folders[folderIndex]._progress;
+ auto &pi = _folders[folderIndex]._progress;
SyncResult::Status state = f->syncResult().status();
if (!f->canSync()) {
// Reset progress info.
pi = SubFolderInfo::Progress();
} else if (state == SyncResult::NotYetStarted) {
- FolderMan* folderMan = FolderMan::instance();
+ FolderMan *folderMan = FolderMan::instance();
int pos = folderMan->scheduleQueue().indexOf(f);
if (folderMan->currentSyncFolder()
- && folderMan->currentSyncFolder() != f) {
+ && folderMan->currentSyncFolder() != f) {
pos += 1;
}
QString message;
if (state == SyncResult::Success && f->syncResult().folderStructureWasChanged()) {
// There is a new or a removed folder. reset all data
- auto & info = _folders[folderIndex];
+ auto &info = _folders[folderIndex];
info.resetSubs(this, index(folderIndex));
}
}
void FolderStatusModel::slotFolderScheduleQueueChanged()
{
// Update messages on waiting folders.
- foreach (Folder* f, FolderMan::instance()->map()) {
+ foreach (Folder *f, FolderMan::instance()->map()) {
slotFolderSyncStateChange(f);
}
}
bool ok;
auto undecidedList = folder->journalDb()->getSelectiveSyncList(SyncJournalDb::SelectiveSyncUndecidedList, &ok);
- if( !ok ) {
+ if (!ok) {
qCWarning(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 ) {
+ if (!ok) {
qCWarning(lcFolderStatus) << "Could not read selective sync list from db.";
return;
}
- foreach (const auto& undecidedFolder, undecidedList) {
+ foreach (const auto &undecidedFolder, undecidedList) {
blackList.removeAll(undecidedFolder);
}
folder->journalDb()->setSelectiveSyncList(SyncJournalDb::SelectiveSyncBlackList, blackList);
// Add all undecided folders to the white list
auto whiteList = folder->journalDb()->getSelectiveSyncList(SyncJournalDb::SelectiveSyncWhiteList, &ok);
- if( !ok ) {
+ if (!ok) {
qCWarning(lcFolderStatus) << "Could not read selective sync list from db.";
return;
}
break;
}
}
- if (folderIndex < 0) { return; }
+ if (folderIndex < 0) {
+ return;
+ }
_folders[folderIndex].resetSubs(this, index(folderIndex));
QMutableMapIterator<QPersistentModelIndex, QElapsedTimer> it(_fetchingItems);
while (it.hasNext()) {
it.next();
- if (it.value().elapsed() > 800)
- {
+ if (it.value().elapsed() > 800) {
auto idx = it.key();
- auto* info = infoForIndex(idx);
+ auto *info = infoForIndex(idx);
if (info && info->_fetching) {
bool add = !info->hasLabel();
if (add) {
return _hasError || _fetchingLabel;
}
-void FolderStatusModel::SubFolderInfo::resetSubs(FolderStatusModel* model, QModelIndex index)
+void FolderStatusModel::SubFolderInfo::resetSubs(FolderStatusModel *model, QModelIndex index)
{
_fetched = false;
_fetching = false;
if (hasLabel()) {
- model->beginRemoveRows(index, 0 ,0);
+ model->beginRemoveRows(index, 0, 0);
_fetchingLabel = false;
_hasError = false;
model->endRemoveRows();
{
Q_OBJECT
public:
- FolderStatusModel(QObject * parent = 0);
+ FolderStatusModel(QObject *parent = 0);
~FolderStatusModel();
- void setAccountState(const AccountState* accountState);
+ void setAccountState(const AccountState *accountState);
- Qt::ItemFlags flags( const QModelIndex& ) const Q_DECL_OVERRIDE;
+ Qt::ItemFlags flags(const QModelIndex &) const Q_DECL_OVERRIDE;
QVariant data(const QModelIndex &index, int role) const Q_DECL_OVERRIDE;
- bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole) Q_DECL_OVERRIDE;
- int columnCount(const QModelIndex& parent = QModelIndex()) const Q_DECL_OVERRIDE;
- int rowCount(const QModelIndex& parent = QModelIndex()) const Q_DECL_OVERRIDE;
- QModelIndex index(int row, int column = 0, const QModelIndex& parent = QModelIndex()) const Q_DECL_OVERRIDE;
- QModelIndex parent(const QModelIndex& child) const Q_DECL_OVERRIDE;
- bool canFetchMore(const QModelIndex& parent) const Q_DECL_OVERRIDE;
- void fetchMore(const QModelIndex& parent) Q_DECL_OVERRIDE;
- bool hasChildren(const QModelIndex& parent = QModelIndex()) const Q_DECL_OVERRIDE;
-
- struct SubFolderInfo {
+ bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) Q_DECL_OVERRIDE;
+ int columnCount(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE;
+ int rowCount(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE;
+ QModelIndex index(int row, int column = 0, const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE;
+ QModelIndex parent(const QModelIndex &child) const Q_DECL_OVERRIDE;
+ bool canFetchMore(const QModelIndex &parent) const Q_DECL_OVERRIDE;
+ void fetchMore(const QModelIndex &parent) Q_DECL_OVERRIDE;
+ bool hasChildren(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE;
+
+ struct SubFolderInfo
+ {
SubFolderInfo()
- : _folder(0), _size(0), _isExternal(false), _fetched(false), _fetching(false),
- _hasError(false), _fetchingLabel(false), _isUndecided(false), _checked(Qt::Checked) {}
+ : _folder(0)
+ , _size(0)
+ , _isExternal(false)
+ , _fetched(false)
+ , _fetching(false)
+ , _hasError(false)
+ , _fetchingLabel(false)
+ , _isUndecided(false)
+ , _checked(Qt::Checked)
+ {
+ }
Folder *_folder;
QString _name;
QString _path;
bool hasLabel() const;
// Reset all subfolders and fetch status
- void resetSubs(FolderStatusModel* model, QModelIndex index);
-
- struct Progress {
- Progress() : _warningCount(0), _overallPercent(0) {}
+ void resetSubs(FolderStatusModel *model, QModelIndex index);
+
+ struct Progress
+ {
+ Progress()
+ : _warningCount(0)
+ , _overallPercent(0)
+ {
+ }
bool isNull() const
- { return _progressString.isEmpty() && _warningCount == 0 && _overallSyncString.isEmpty(); }
+ {
+ return _progressString.isEmpty() && _warningCount == 0 && _overallSyncString.isEmpty();
+ }
QString _progressString;
QString _overallSyncString;
int _warningCount;
QVector<SubFolderInfo> _folders;
- enum ItemType { RootFolder, SubFolder, AddButton, FetchLabel };
+ enum ItemType { RootFolder,
+ SubFolder,
+ AddButton,
+ FetchLabel };
ItemType classify(const QModelIndex &index) const;
SubFolderInfo *infoForIndex(const QModelIndex &index) const;
private slots:
void slotUpdateDirectories(const QStringList &);
- void slotGatherPermissions(const QString &name, const QMap<QString,QString> &properties);
+ void slotGatherPermissions(const QString &name, const QMap<QString, QString> &properties);
void slotLscolFinishedWithError(QNetworkReply *r);
- void slotFolderSyncStateChange(Folder* f);
+ void slotFolderSyncStateChange(Folder *f);
void slotFolderScheduleQueueChanged();
void slotNewBigFolder();
void slotShowFetchProgress();
private:
- QStringList createBlackList(OCC::FolderStatusModel::SubFolderInfo* root,
- const QStringList& oldBlackList) const;
- const AccountState* _accountState;
- bool _dirty; // If the selective sync checkboxes were changed
+ QStringList createBlackList(OCC::FolderStatusModel::SubFolderInfo *root,
+ const QStringList &oldBlackList) const;
+ const AccountState *_accountState;
+ bool _dirty; // If the selective sync checkboxes were changed
/**
* Keeps track of items that are fetching data from the server.
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
//the roles argument was added in Qt5
void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles = QVector<int>())
- { emit QAbstractItemModel::dataChanged(topLeft,bottomRight); }
+ {
+ emit QAbstractItemModel::dataChanged(topLeft, bottomRight);
+ }
#endif
signals:
Q_LOGGING_CATEGORY(lcFolderWatcher, "gui.folderwatcher", QtInfoMsg)
-FolderWatcher::FolderWatcher(const QString &root, Folder* folder)
- : QObject(folder),
- _folder(folder)
+FolderWatcher::FolderWatcher(const QString &root, Folder *folder)
+ : QObject(folder)
+ , _folder(folder)
{
_d.reset(new FolderWatcherPrivate(this, root));
}
FolderWatcher::~FolderWatcher()
-{ }
+{
+}
-bool FolderWatcher::pathIsIgnored( const QString& path )
+bool FolderWatcher::pathIsIgnored(const QString &path)
{
- if( path.isEmpty() ) return true;
- if( !_folder ) return false;
+ if (path.isEmpty())
+ return true;
+ if (!_folder)
+ return false;
#ifndef OWNCLOUD_TEST
if (_folder->isFileExcludedAbsolute(path)) {
return false;
}
-void FolderWatcher::changeDetected( const QString& path )
+void FolderWatcher::changeDetected(const QString &path)
{
QStringList paths(path);
changeDetected(paths);
}
-void FolderWatcher::changeDetected( const QStringList& paths )
+void FolderWatcher::changeDetected(const QStringList &paths)
{
// TODO: this shortcut doesn't look very reliable:
// - why is the timeout only 1 second?
// Check if the same path was reported within the last second.
QSet<QString> pathsSet = paths.toSet();
- if( pathsSet == _lastPaths && _timer.elapsed() < 1000 ) {
+ if (pathsSet == _lastPaths && _timer.elapsed() < 1000) {
// the same path was reported within the last second. Skip.
return;
}
// ------- handle ignores:
for (int i = 0; i < paths.size(); ++i) {
QString path = paths[i];
- if( pathIsIgnored(path) ) {
+ if (pathIsIgnored(path)) {
continue;
}
}
}
-void FolderWatcher::addPath(const QString &path )
+void FolderWatcher::addPath(const QString &path)
{
_d->addPath(path);
}
-void FolderWatcher::removePath(const QString &path )
+void FolderWatcher::removePath(const QString &path)
{
_d->removePath(path);
}
} // namespace OCC
-
/**
* @param root Path of the root of the folder
*/
- FolderWatcher(const QString &root, Folder* folder = 0L);
+ FolderWatcher(const QString &root, Folder *folder = 0L);
virtual ~FolderWatcher();
/**
* Those need to be notified when a directory is added or removed while the watcher is disabled.
* This is a no-op for backends that are recursive
*/
- void addPath(const QString&);
- void removePath(const QString&);
+ void addPath(const QString &);
+ void removePath(const QString &);
/* Check if the path is ignored. */
- bool pathIsIgnored( const QString& path );
+ bool pathIsIgnored(const QString &path);
signals:
/** Emitted when one of the watched directories or one
void pathChanged(const QString &path);
/** Emitted if an error occurs */
- void error(const QString& error);
+ void error(const QString &error);
protected slots:
// called from the implementations to indicate a change in path
- void changeDetected( const QString& path);
- void changeDetected( const QStringList& paths);
+ void changeDetected(const QString &path);
+ void changeDetected(const QStringList &paths);
protected:
QHash<QString, int> _pendingPathes;
QScopedPointer<FolderWatcherPrivate> _d;
QTime _timer;
QSet<QString> _lastPaths;
- Folder* _folder;
+ Folder *_folder;
friend class FolderWatcherPrivate;
};
-
}
#endif
namespace OCC {
-FolderWatcherPrivate::FolderWatcherPrivate(FolderWatcher *p, const QString& path)
- : QObject(),
- _parent(p),
- _folder(path)
+FolderWatcherPrivate::FolderWatcherPrivate(FolderWatcher *p, const QString &path)
+ : QObject()
+ , _parent(p)
+ , _folder(path)
{
_fd = inotify_init();
if (_fd != -1) {
- _socket.reset( new QSocketNotifier(_fd, QSocketNotifier::Read) );
+ _socket.reset(new QSocketNotifier(_fd, QSocketNotifier::Read));
connect(_socket.data(), SIGNAL(activated(int)), SLOT(slotReceivedNotification(int)));
} else {
qCWarning(lcFolderWatcher) << "notify_init() failed: " << strerror(errno);
}
QMetaObject::invokeMethod(this, "slotAddFolderRecursive", Q_ARG(QString, path));
-
}
FolderWatcherPrivate::~FolderWatcherPrivate()
{
-
}
// attention: result list passed by reference!
-bool FolderWatcherPrivate::findFoldersBelow( const QDir& dir, QStringList& fullList )
+bool FolderWatcherPrivate::findFoldersBelow(const QDir &dir, QStringList &fullList)
{
bool ok = true;
- if( !(dir.exists() && dir.isReadable()) ) {
+ if (!(dir.exists() && dir.isReadable())) {
qCDebug(lcFolderWatcher) << "Non existing path coming in: " << dir.absolutePath();
ok = false;
} else {
QStringList::const_iterator constIterator;
for (constIterator = pathes.constBegin(); constIterator != pathes.constEnd();
- ++constIterator) {
- const QString fullPath(dir.path()+QLatin1String("/")+(*constIterator));
+ ++constIterator) {
+ const QString fullPath(dir.path() + QLatin1String("/") + (*constIterator));
fullList.append(fullPath);
ok = findFoldersBelow(QDir(fullPath), fullList);
}
return ok;
}
-void FolderWatcherPrivate::inotifyRegisterPath(const QString& path)
+void FolderWatcherPrivate::inotifyRegisterPath(const QString &path)
{
- if( !path.isEmpty()) {
+ if (!path.isEmpty()) {
int wd = inotify_add_watch(_fd, path.toUtf8().constData(),
- IN_CLOSE_WRITE | IN_ATTRIB | IN_MOVE |
- IN_CREATE |IN_DELETE | IN_DELETE_SELF |
- IN_MOVE_SELF |IN_UNMOUNT |IN_ONLYDIR);
- if( wd > -1 ) {
+ IN_CLOSE_WRITE | IN_ATTRIB | IN_MOVE | IN_CREATE | IN_DELETE | IN_DELETE_SELF | IN_MOVE_SELF | IN_UNMOUNT | IN_ONLYDIR);
+ if (wd > -1) {
_watches.insert(wd, path);
- }
+ }
}
}
const QStringList watchedFolders = _watches.values();
QStringList allSubfolders;
- if( !findFoldersBelow(QDir(path), allSubfolders)) {
+ if (!findFoldersBelow(QDir(path), allSubfolders)) {
qCWarning(lcFolderWatcher) << "Could not traverse all sub folders";
}
QStringListIterator subfoldersIt(allSubfolders);
while (subfoldersIt.hasNext()) {
QString subfolder = subfoldersIt.next();
- QDir folder (subfolder);
+ QDir folder(subfolder);
if (folder.exists() && !watchedFolders.contains(folder.absolutePath())) {
subdirs++;
- if( _parent->pathIsIgnored(subfolder) ) {
+ if (_parent->pathIsIgnored(subfolder)) {
qCDebug(lcFolderWatcher) << "* Not adding" << folder.path();
continue;
}
}
}
- if (subdirs >0) {
+ if (subdirs > 0) {
qCDebug(lcFolderWatcher) << " `-> and" << subdirs << "subdirectories";
}
}
void FolderWatcherPrivate::slotReceivedNotification(int fd)
{
int len;
- struct inotify_event* event;
+ struct inotify_event *event;
int i;
int error;
QVarLengthArray<char, 2048> buffer(2048);
do {
- len = read(fd, buffer.data(), buffer.size());
- error = errno;
- /**
+ len = read(fd, buffer.data(), buffer.size());
+ error = errno;
+ /**
* From inotify documentation:
*
* The behavior when the buffer given to read(2) is too
* read(2) returns 0; since kernel 2.6.21, read(2) fails with
* the error EINVAL.
*/
- if (len < 0 && error == EINVAL)
- {
- // double the buffer size
- buffer.resize(buffer.size() * 2);
- /* and try again ... */
- continue;
- }
- } while (false);
+ if (len < 0 && error == EINVAL) {
+ // double the buffer size
+ buffer.resize(buffer.size() * 2);
+ /* and try again ... */
+ continue;
+ }
+ } while (false);
// reset counter
i = 0;
// while there are enough events in the buffer
- while(i + sizeof(struct inotify_event) < static_cast<unsigned int>(len)) {
+ while (i + sizeof(struct inotify_event) < static_cast<unsigned int>(len)) {
// cast an inotify_event
- event = (struct inotify_event*)&buffer[i];
+ event = (struct inotify_event *)&buffer[i];
if (event == NULL) {
qCDebug(lcFolderWatcher) << "NULL event";
i += sizeof(struct inotify_event);
// Fire event for the path that was changed.
if (event->len > 0 && event->wd > -1) {
QByteArray fileName(event->name);
- if (fileName.startsWith("._sync_") ||
- fileName.startsWith(".csync_journal.db") ||
- fileName.startsWith(".owncloudsync.log")) {
+ if (fileName.startsWith("._sync_") || fileName.startsWith(".csync_journal.db") || fileName.startsWith(".owncloudsync.log")) {
} else {
const QString p = _watches[event->wd] + '/' + fileName;
_parent->changeDetected(p);
// increment counter
i += sizeof(struct inotify_event) + event->len;
}
-
}
-void FolderWatcherPrivate::addPath(const QString& path)
+void FolderWatcherPrivate::addPath(const QString &path)
{
slotAddFolderRecursive(path);
}
-void FolderWatcherPrivate::removePath(const QString& path)
+void FolderWatcherPrivate::removePath(const QString &path)
{
int wid = -1;
// Remove the inotify watch.
QHash<int, QString>::const_iterator i = _watches.constBegin();
while (i != _watches.constEnd()) {
- if( i.value() == path ) {
+ if (i.value() == path) {
wid = i.key();
break;
}
++i;
}
- if( wid > -1 ) {
+ if (wid > -1) {
inotify_rm_watch(_fd, wid);
_watches.remove(wid);
}
#include "folderwatcher.h"
-namespace OCC
-{
+namespace OCC {
/**
* @brief Linux (inotify) API implementation of FolderWatcher
{
Q_OBJECT
public:
- FolderWatcherPrivate() { }
+ FolderWatcherPrivate() {}
FolderWatcherPrivate(FolderWatcher *p, const QString &path);
~FolderWatcherPrivate();
void slotAddFolderRecursive(const QString &path);
protected:
- bool findFoldersBelow( const QDir& dir, QStringList& fullList );
- void inotifyRegisterPath(const QString& path);
+ bool findFoldersBelow(const QDir &dir, QStringList &fullList);
+ void inotifyRegisterPath(const QString &path);
private:
FolderWatcher *_parent;
QString _folder;
- QHash <int, QString> _watches;
+ QHash<int, QString> _watches;
QScopedPointer<QSocketNotifier> _socket;
int _fd;
};
-
}
#endif
#include <QStringList>
-
namespace OCC {
-FolderWatcherPrivate::FolderWatcherPrivate(FolderWatcher *p, const QString& path)
- : _parent(p),
- _folder(path)
+FolderWatcherPrivate::FolderWatcherPrivate(FolderWatcher *p, const QString &path)
+ : _parent(p)
+ , _folder(path)
{
this->startWatching();
}
}
static void callback(
- ConstFSEventStreamRef streamRef,
- void *clientCallBackInfo,
- size_t numEvents,
- void *eventPathsVoid,
- const FSEventStreamEventFlags eventFlags[],
- const FSEventStreamEventId eventIds[])
+ ConstFSEventStreamRef streamRef,
+ void *clientCallBackInfo,
+ size_t numEvents,
+ void *eventPathsVoid,
+ const FSEventStreamEventFlags eventFlags[],
+ const FSEventStreamEventId eventIds[])
{
Q_UNUSED(streamRef)
Q_UNUSED(eventFlags)
Q_UNUSED(eventIds)
- const FSEventStreamEventFlags c_interestingFlags
- = kFSEventStreamEventFlagItemCreated // for new folder/file
- | kFSEventStreamEventFlagItemRemoved // for rm
- | kFSEventStreamEventFlagItemInodeMetaMod // for mtime change
- | kFSEventStreamEventFlagItemRenamed // also coming for moves to trash in finder
- | kFSEventStreamEventFlagItemModified; // for content change
+ const FSEventStreamEventFlags c_interestingFlags = kFSEventStreamEventFlagItemCreated // for new folder/file
+ | kFSEventStreamEventFlagItemRemoved // for rm
+ | kFSEventStreamEventFlagItemInodeMetaMod // for mtime change
+ | kFSEventStreamEventFlagItemRenamed // also coming for moves to trash in finder
+ | kFSEventStreamEventFlagItemModified; // for content change
//We ignore other flags, e.g. for owner change, xattr change, Finder label change etc
qCDebug(lcFolderWatcher) << "FolderWatcherPrivate::callback by OS X";
paths.append(fn);
}
- reinterpret_cast<FolderWatcherPrivate*>(clientCallBackInfo)->doNotifyParent(paths);
+ reinterpret_cast<FolderWatcherPrivate *>(clientCallBackInfo)->doNotifyParent(paths);
}
void FolderWatcherPrivate::startWatching()
{
qCDebug(lcFolderWatcher) << "FolderWatcherPrivate::startWatching()" << _folder;
CFStringRef folderCF = CFStringCreateWithCharacters(0, reinterpret_cast<const UniChar *>(_folder.unicode()),
- _folder.length());
- CFArrayRef pathsToWatch = CFStringCreateArrayBySeparatingStrings (NULL, folderCF, CFSTR(":"));
+ _folder.length());
+ CFArrayRef pathsToWatch = CFStringCreateArrayBySeparatingStrings(NULL, folderCF, CFSTR(":"));
- FSEventStreamContext ctx = {0, this, NULL, NULL, NULL};
+ FSEventStreamContext ctx = { 0, this, NULL, NULL, NULL };
// TODO: Add kFSEventStreamCreateFlagFileEvents ?
_stream = FSEventStreamCreate(NULL,
- &callback,
- &ctx,
- pathsToWatch,
- kFSEventStreamEventIdSinceNow,
- 0, // latency
- kFSEventStreamCreateFlagUseCFTypes|kFSEventStreamCreateFlagFileEvents|kFSEventStreamCreateFlagIgnoreSelf
- );
+ &callback,
+ &ctx,
+ pathsToWatch,
+ kFSEventStreamEventIdSinceNow,
+ 0, // latency
+ kFSEventStreamCreateFlagUseCFTypes | kFSEventStreamCreateFlagFileEvents | kFSEventStreamCreateFlagIgnoreSelf);
CFRelease(pathsToWatch);
FSEventStreamScheduleWithRunLoop(_stream, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
FSEventStreamStart(_stream);
}
-void FolderWatcherPrivate::doNotifyParent(const QStringList &paths) {
-
+void FolderWatcherPrivate::doNotifyParent(const QStringList &paths)
+{
_parent->changeDetected(paths);
}
-
} // ns mirall
#include <CoreServices/CoreServices.h>
-namespace OCC
-{
+namespace OCC {
/**
* @brief Mac OS X API implementation of FolderWatcher
class FolderWatcherPrivate
{
public:
-
FolderWatcherPrivate(FolderWatcher *p, const QString &path);
~FolderWatcherPrivate();
FSEventStreamRef _stream;
};
-
}
#endif
namespace OCC {
void WatcherThread::watchChanges(size_t fileNotifyBufferSize,
- bool* increaseBufferSize)
+ bool *increaseBufferSize)
{
*increaseBufferSize = false;
QString longPath = FileSystem::longWinPath(_path);
_directory = CreateFileW(
- (wchar_t*) longPath.utf16(),
+ (wchar_t *)longPath.utf16(),
FILE_LIST_DIRECTORY,
FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE,
NULL,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED,
- NULL
- );
+ NULL);
- if (_directory == INVALID_HANDLE_VALUE)
- {
+ if (_directory == INVALID_HANDLE_VALUE) {
DWORD errorCode = GetLastError();
qCWarning(lcFolderWatcher) << "Failed to create handle for" << _path << ", error:" << errorCode;
_directory = 0;
overlapped.hEvent = _resultEvent;
// QVarLengthArray ensures the stack-buffer is aligned like double and qint64.
- QVarLengthArray<char, 4096*10> fileNotifyBuffer;
+ QVarLengthArray<char, 4096 * 10> fileNotifyBuffer;
fileNotifyBuffer.resize(fileNotifyBufferSize);
const size_t fileNameBufferSize = 4096;
ResetEvent(_resultEvent);
FILE_NOTIFY_INFORMATION *pFileNotifyBuffer =
- (FILE_NOTIFY_INFORMATION*)fileNotifyBuffer.data();
+ (FILE_NOTIFY_INFORMATION *)fileNotifyBuffer.data();
DWORD dwBytesReturned = 0;
SecureZeroMemory(pFileNotifyBuffer, fileNotifyBufferSize);
- if(! ReadDirectoryChangesW( _directory, (LPVOID)pFileNotifyBuffer,
- fileNotifyBufferSize, true,
- FILE_NOTIFY_CHANGE_FILE_NAME |
- FILE_NOTIFY_CHANGE_DIR_NAME |
- FILE_NOTIFY_CHANGE_LAST_WRITE,
- &dwBytesReturned,
- &overlapped,
- NULL))
- {
+ if (!ReadDirectoryChangesW(_directory, (LPVOID)pFileNotifyBuffer,
+ fileNotifyBufferSize, true,
+ FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE,
+ &dwBytesReturned,
+ &overlapped,
+ NULL)) {
DWORD errorCode = GetLastError();
if (errorCode == ERROR_NOTIFY_ENUM_DIR) {
qCDebug(lcFolderWatcher) << "The buffer for changes overflowed! Triggering a generic change and resizing";
break;
}
- HANDLE handles[] = {_resultEvent, _stopEvent};
+ HANDLE handles[] = { _resultEvent, _stopEvent };
DWORD result = WaitForMultipleObjects(
- 2, handles,
- false, // awake once one of them arrives
- INFINITE);
+ 2, handles,
+ false, // awake once one of them arrives
+ INFINITE);
if (result == 1) {
qCDebug(lcFolderWatcher) << "Received stop event, aborting folder watcher thread";
break;
}
bool ok = GetOverlappedResult(_directory, &overlapped, &dwBytesReturned, false);
- if (! ok) {
+ if (!ok) {
DWORD errorCode = GetLastError();
if (errorCode == ERROR_NOTIFY_ENUM_DIR) {
qCDebug(lcFolderWatcher) << "The buffer for changes overflowed! Triggering a generic change and resizing";
// TODO: We could still try expanding the path in the tricky cases...
QString longfile = file;
if (curEntry->Action != FILE_ACTION_REMOVED
- && curEntry->Action != FILE_ACTION_RENAMED_OLD_NAME) {
+ && curEntry->Action != FILE_ACTION_RENAMED_OLD_NAME) {
size_t longNameSize = GetLongPathNameW(reinterpret_cast<LPCWSTR>(file.utf16()), fileNameBuffer, fileNameBufferSize);
if (longNameSize > 0) {
longfile = QString::fromUtf16(reinterpret_cast<const ushort *>(fileNameBuffer), longNameSize);
// and new files in a folder, probably because of the folder's mtime
// changing. We don't need them.
bool skip = curEntry->Action == FILE_ACTION_MODIFIED
- && QFileInfo(longfile).isDir();
+ && QFileInfo(longfile).isDir();
if (!skip) {
emit changed(longfile);
if (curEntry->NextEntryOffset == 0) {
break;
}
- curEntry = (FILE_NOTIFY_INFORMATION*)(
- (char*)curEntry + curEntry->NextEntryOffset);
+ curEntry = (FILE_NOTIFY_INFORMATION *)((char *)curEntry + curEntry->NextEntryOffset);
}
}
// If this buffer fills up before we've extracted its data we will lose
// change information. Therefore start big.
- size_t bufferSize = 4096*10;
- size_t maxBuffer = 64*1024;
+ size_t bufferSize = 4096 * 10;
+ size_t maxBuffer = 64 * 1024;
while (!_done) {
bool increaseBufferSize = false;
watchChanges(bufferSize, &increaseBufferSize);
if (increaseBufferSize) {
- bufferSize = qMin(bufferSize*2, maxBuffer);
+ bufferSize = qMin(bufferSize * 2, maxBuffer);
} else if (!_done) {
// Other errors shouldn't actually happen,
// so sleep a bit to avoid running into the same error case in a
SetEvent(_stopEvent);
}
-FolderWatcherPrivate::FolderWatcherPrivate(FolderWatcher *p, const QString& path)
+FolderWatcherPrivate::FolderWatcherPrivate(FolderWatcher *p, const QString &path)
: _parent(p)
{
_thread = new WatcherThread(path);
- connect(_thread, SIGNAL(changed(const QString&)),
- _parent,SLOT(changeDetected(const QString&)));
+ connect(_thread, SIGNAL(changed(const QString &)),
+ _parent, SLOT(changeDetected(const QString &)));
_thread->start();
}
* @brief The WatcherThread class
* @ingroup gui
*/
-class WatcherThread : public QThread {
+class WatcherThread : public QThread
+{
Q_OBJECT
public:
- WatcherThread(const QString &path) :
- QThread(),
- _path(path),
- _directory(0),
- _resultEvent(0),
- _stopEvent(0),
- _done(false)
- {}
+ WatcherThread(const QString &path)
+ : QThread()
+ , _path(path)
+ , _directory(0)
+ , _resultEvent(0)
+ , _stopEvent(0)
+ , _done(false)
+ {
+ }
~WatcherThread();
protected:
void run();
void watchChanges(size_t fileNotifyBufferSize,
- bool* increaseBufferSize);
+ bool *increaseBufferSize);
void closeHandle();
signals:
* @brief Windows implementation of FolderWatcher
* @ingroup gui
*/
-class FolderWatcherPrivate : public QObject {
+class FolderWatcherPrivate : public QObject
+{
Q_OBJECT
public:
- FolderWatcherPrivate(FolderWatcher *p, const QString& path);
+ FolderWatcherPrivate(FolderWatcher *p, const QString &path);
~FolderWatcherPrivate();
void addPath(const QString &) {}
FolderWatcher *_parent;
WatcherThread *_thread;
};
-
}
#endif // MIRALL_FOLDERWATCHER_WIN_H
#include <stdlib.h>
-namespace OCC
-{
+namespace OCC {
QString FormatWarningsWizardPage::formatWarnings(const QStringList &warnings) const
{
ret = tr("<b>Warning:</b> %1").arg(warnings.first());
} else if (warnings.count() > 1) {
ret = tr("<b>Warning:</b>") + " <ul>";
- Q_FOREACH(QString warning, warnings) {
+ Q_FOREACH (QString warning, warnings) {
ret += QString::fromLatin1("<li>%1</li>").arg(warning);
}
ret += "</ul>";
return ret;
}
-FolderWizardLocalPath::FolderWizardLocalPath(const AccountPtr& account)
- : FormatWarningsWizardPage(),
- _account(account)
+FolderWizardLocalPath::FolderWizardLocalPath(const AccountPtr &account)
+ : FormatWarningsWizardPage()
+ , _account(account)
{
_ui.setupUi(this);
registerField(QLatin1String("sourceFolder*"), _ui.localFolderLineEdit);
QString defaultPath = QDir::homePath() + QLatin1Char('/') + Theme::instance()->appName();
defaultPath = FolderMan::instance()->findGoodPathForNewSyncFolder(defaultPath, account->url());
- _ui.localFolderLineEdit->setText( QDir::toNativeSeparators( defaultPath ) );
+ _ui.localFolderLineEdit->setText(QDir::toNativeSeparators(defaultPath));
_ui.localFolderLineEdit->setToolTip(tr("Enter the path to the local folder."));
_ui.warnLabel->setTextFormat(Qt::RichText);
FolderWizardLocalPath::~FolderWizardLocalPath()
{
-
}
void FolderWizardLocalPath::initializePage()
{
- _ui.warnLabel->hide();
+ _ui.warnLabel->hide();
}
void FolderWizardLocalPath::cleanupPage()
{
- _ui.warnLabel->hide();
+ _ui.warnLabel->hide();
}
bool FolderWizardLocalPath::isComplete() const
{
QUrl serverUrl = _account->url();
- serverUrl.setUserName( _account->credentials()->user() );
+ serverUrl.setUserName(_account->credentials()->user());
QString errorStr = FolderMan::instance()->checkPathValidityForNewFolder(
QDir::fromNativeSeparators(_ui.localFolderLineEdit->text()), serverUrl);
-
bool isOk = errorStr.isEmpty();
QStringList warnStrings;
if (!isOk) {
warnStrings << errorStr;
}
- _ui.warnLabel->setWordWrap(true);
- if( isOk ) {
- _ui.warnLabel->hide();
- _ui.warnLabel->setText( QString::null );
- } else {
- _ui.warnLabel->show();
- QString warnings = formatWarnings(warnStrings);
- _ui.warnLabel->setText( warnings );
- }
- return isOk;
+ _ui.warnLabel->setWordWrap(true);
+ if (isOk) {
+ _ui.warnLabel->hide();
+ _ui.warnLabel->setText(QString::null);
+ } else {
+ _ui.warnLabel->show();
+ QString warnings = formatWarnings(warnStrings);
+ _ui.warnLabel->setText(warnings);
+ }
+ return isOk;
}
void FolderWizardLocalPath::slotChooseLocalFolder()
// open the first entry of the home dir. Otherwise the dir picker comes
// up with the closed home dir icon, stupid Qt default...
QStringList dirs = d.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks,
- QDir::DirsFirst|QDir::Name);
+ QDir::DirsFirst | QDir::Name);
- if(dirs.count() > 0) sf += "/"+dirs.at(0); // Take the first dir in home dir.
+ if (dirs.count() > 0)
+ sf += "/" + dirs.at(0); // Take the first dir in home dir.
QString dir = QFileDialog::getExistingDirectory(this,
- tr("Select the source folder"),
- sf);
+ tr("Select the source folder"),
+ sf);
if (!dir.isEmpty()) {
// set the last directory component name as alias
_ui.localFolderLineEdit->setText(QDir::toNativeSeparators(dir));
}
// =================================================================================
-FolderWizardRemotePath::FolderWizardRemotePath(const AccountPtr& account)
+FolderWizardRemotePath::FolderWizardRemotePath(const AccountPtr &account)
: FormatWarningsWizardPage()
- ,_warnWasVisible(false)
- ,_account(account)
+ , _warnWasVisible(false)
+ , _account(account)
{
_ui.setupUi(this);
connect(_ui.addFolderButton, SIGNAL(clicked()), SLOT(slotAddRemoteFolder()));
connect(_ui.refreshButton, SIGNAL(clicked()), SLOT(slotRefreshFolders()));
- connect(_ui.folderTreeWidget, SIGNAL(itemExpanded(QTreeWidgetItem*)), SLOT(slotItemExpanded(QTreeWidgetItem*)));
- connect(_ui.folderTreeWidget, SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)), SLOT(slotCurrentItemChanged(QTreeWidgetItem*)));
+ connect(_ui.folderTreeWidget, SIGNAL(itemExpanded(QTreeWidgetItem *)), SLOT(slotItemExpanded(QTreeWidgetItem *)));
+ connect(_ui.folderTreeWidget, SIGNAL(currentItemChanged(QTreeWidgetItem *, QTreeWidgetItem *)), SLOT(slotCurrentItemChanged(QTreeWidgetItem *)));
connect(_ui.folderEntry, SIGNAL(textEdited(QString)), SLOT(slotFolderEntryEdited(QString)));
_lscolTimer.setInterval(500);
connect(&_lscolTimer, SIGNAL(timeout()), SLOT(slotLsColFolderEntry()));
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
- _ui.folderTreeWidget->header()->setSectionResizeMode(0,QHeaderView::ResizeToContents);
+ _ui.folderTreeWidget->header()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
// Make sure that there will be a scrollbar when the contents is too wide
_ui.folderTreeWidget->header()->setStretchLastSection(false);
#endif
dlg->setWindowTitle(tr("Create Remote Folder"));
dlg->setLabelText(tr("Enter the name of the new folder to be created below '%1':")
- .arg(parent));
+ .arg(parent));
dlg->open(this, SLOT(slotCreateRemoteFolder(QString)));
dlg->setAttribute(Qt::WA_DeleteOnClose);
}
void FolderWizardRemotePath::slotCreateRemoteFolder(const QString &folder)
{
- if( folder.isEmpty() ) return;
+ if (folder.isEmpty())
+ return;
QTreeWidgetItem *current = _ui.folderTreeWidget->currentItem();
QString fullPath;
MkColJob *job = new MkColJob(_account, fullPath, this);
/* check the owncloud configuration file and query the ownCloud */
connect(job, SIGNAL(finished(QNetworkReply::NetworkError)),
- SLOT(slotCreateRemoteFolderFinished(QNetworkReply::NetworkError)));
- connect(job, SIGNAL(networkError(QNetworkReply*)), SLOT(slotHandleMkdirNetworkError(QNetworkReply*)));
+ SLOT(slotCreateRemoteFolderFinished(QNetworkReply::NetworkError)));
+ connect(job, SIGNAL(networkError(QNetworkReply *)), SLOT(slotHandleMkdirNetworkError(QNetworkReply *)));
job->start();
}
void FolderWizardRemotePath::slotHandleMkdirNetworkError(QNetworkReply *reply)
{
qCWarning(lcWizard) << "webdav mkdir request failed:" << reply->error();
- if( !_account->credentials()->stillValid(reply) ) {
+ if (!_account->credentials()->stillValid(reply)) {
showWarn(tr("Authentication failed accessing %1").arg(Theme::instance()->appNameGUI()));
} else {
showWarn(tr("Failed to create the folder on %1. Please check manually.")
- .arg(Theme::instance()->appNameGUI()));
+ .arg(Theme::instance()->appNameGUI()));
}
}
-void FolderWizardRemotePath::slotHandleLsColNetworkError(QNetworkReply */*reply*/)
+void FolderWizardRemotePath::slotHandleLsColNetworkError(QNetworkReply * /*reply*/)
{
auto job = qobject_cast<MkColJob *>(sender());
showWarn(tr("Failed to list a folder. Error: %1")
- .arg(job->errorStringParsingBody()));
+ .arg(job->errorStringParsingBody()));
}
-static QTreeWidgetItem* findFirstChild(QTreeWidgetItem *parent, const QString& text)
+static QTreeWidgetItem *findFirstChild(QTreeWidgetItem *parent, const QString &text)
{
for (int i = 0; i < parent->childCount(); ++i) {
QTreeWidgetItem *child = parent->child(i);
QTreeWidgetItem *it = _ui.folderTreeWidget->topLevelItem(0);
if (!path.isEmpty()) {
const QStringList pathTrail = path.split(QLatin1Char('/'));
- foreach (const QString& path, pathTrail) {
+ foreach (const QString &path, pathTrail) {
if (!it) {
return false;
}
foreach (QString path, sortedList) {
path.remove(webdavFolder);
QStringList paths = path.split('/');
- if (paths.last().isEmpty()) paths.removeLast();
+ if (paths.last().isEmpty())
+ paths.removeLast();
recursiveInsert(root, paths, path);
}
root->setExpanded(true);
emit completeChanged();
}
-void FolderWizardRemotePath::slotFolderEntryEdited(const QString& text)
+void FolderWizardRemotePath::slotFolderEntryEdited(const QString &text)
{
if (selectByPath(text)) {
_lscolTimer.stop();
// No error handling, no updating, we do this manually
// because of extra logic in the typed-path case.
disconnect(job, 0, this, 0);
- connect(job, SIGNAL(finishedWithError(QNetworkReply*)),
- SLOT(slotTypedPathError(QNetworkReply*)));
+ connect(job, SIGNAL(finishedWithError(QNetworkReply *)),
+ SLOT(slotTypedPathError(QNetworkReply *)));
connect(job, SIGNAL(directoryListingSubfolders(QStringList)),
- SLOT(slotTypedPathFound(QStringList)));
+ SLOT(slotTypedPathFound(QStringList)));
}
-void FolderWizardRemotePath::slotTypedPathFound(const QStringList& subpaths)
+void FolderWizardRemotePath::slotTypedPathFound(const QStringList &subpaths)
{
slotUpdateDirectories(subpaths);
selectByPath(_ui.folderEntry->text());
}
-void FolderWizardRemotePath::slotTypedPathError(QNetworkReply* reply)
+void FolderWizardRemotePath::slotTypedPathError(QNetworkReply *reply)
{
// Ignore 404s, otherwise users will get annoyed by error popups
// when not typing fast enough. It's still clear that a given path
slotHandleLsColNetworkError(reply);
}
-LsColJob* FolderWizardRemotePath::runLsColJob(const QString& path)
+LsColJob *FolderWizardRemotePath::runLsColJob(const QString &path)
{
LsColJob *job = new LsColJob(_account, path, this);
job->setProperties(QList<QByteArray>() << "resourcetype");
connect(job, SIGNAL(directoryListingSubfolders(QStringList)),
- SLOT(slotUpdateDirectories(QStringList)));
- connect(job, SIGNAL(finishedWithError(QNetworkReply*)),
- SLOT(slotHandleLsColNetworkError(QNetworkReply*)));
+ SLOT(slotUpdateDirectories(QStringList)));
+ connect(job, SIGNAL(finishedWithError(QNetworkReply *)),
+ SLOT(slotHandleLsColNetworkError(QNetworkReply *)));
job->start();
return job;
Folder::Map map = FolderMan::instance()->map();
Folder::Map::const_iterator i = map.constBegin();
- for(i = map.constBegin();i != map.constEnd(); i++ ) {
- Folder *f = static_cast<Folder*>(i.value());
+ for (i = map.constBegin(); i != map.constEnd(); i++) {
+ Folder *f = static_cast<Folder *>(i.value());
if (f->accountState()->account() != _account) {
continue;
}
if (QDir::cleanPath(dir) == QDir::cleanPath(curDir)) {
warnStrings.append(tr("This folder is already being synced."));
} else if (dir.startsWith(curDir + QLatin1Char('/'))) {
- warnStrings.append(tr("You are already syncing <i>%1</i>, which is a parent folder of <i>%2</i>.").arg(
- Utility::escape(curDir), Utility::escape(dir)));
+ warnStrings.append(tr("You are already syncing <i>%1</i>, which is a parent folder of <i>%2</i>.").arg(Utility::escape(curDir), Utility::escape(dir)));
}
if (curDir == QLatin1String("/")) {
slotRefreshFolders();
}
-void FolderWizardRemotePath::showWarn( const QString& msg ) const
+void FolderWizardRemotePath::showWarn(const QString &msg) const
{
- if( msg.isEmpty() ) {
- _ui.warnFrame->hide();
+ if (msg.isEmpty()) {
+ _ui.warnFrame->hide();
- } else {
- _ui.warnFrame->show();
- _ui.warnLabel->setText( msg );
- }
+ } else {
+ _ui.warnFrame->show();
+ _ui.warnLabel->setText(msg);
+ }
}
// ====================================================================================
-FolderWizardSelectiveSync::FolderWizardSelectiveSync(const AccountPtr& account)
+FolderWizardSelectiveSync::FolderWizardSelectiveSync(const AccountPtr &account)
{
QVBoxLayout *layout = new QVBoxLayout(this);
_selectiveSync = new SelectiveSyncWidget(account, this);
void FolderWizardSelectiveSync::initializePage()
{
- QString targetPath = wizard()->property("targetPath").toString();
+ QString targetPath = wizard()->property("targetPath").toString();
if (targetPath.startsWith('/')) {
targetPath = targetPath.mid(1);
}
- QString alias = QFileInfo(targetPath).fileName();
+ QString alias = QFileInfo(targetPath).fileName();
if (alias.isEmpty())
alias = Theme::instance()->appName();
QStringList initialBlacklist;
void FolderWizardSelectiveSync::cleanupPage()
{
- QString targetPath = wizard()->property("targetPath").toString();
- QString alias = QFileInfo(targetPath).fileName();
+ QString targetPath = wizard()->property("targetPath").toString();
+ QString alias = QFileInfo(targetPath).fileName();
if (alias.isEmpty())
alias = Theme::instance()->appName();
_selectiveSync->setFolderInfo(targetPath, alias);
}
-
-
// ====================================================================================
*/
FolderWizard::FolderWizard(AccountPtr account, QWidget *parent)
- : QWizard(parent),
- _folderWizardSourcePage(new FolderWizardLocalPath(account)),
- _folderWizardTargetPage(0),
- _folderWizardSelectiveSyncPage(new FolderWizardSelectiveSync(account))
+ : QWizard(parent)
+ , _folderWizardSourcePage(new FolderWizardLocalPath(account))
+ , _folderWizardTargetPage(0)
+ , _folderWizardSelectiveSyncPage(new FolderWizardSelectiveSync(account))
{
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
- setPage(Page_Source, _folderWizardSourcePage );
+ setPage(Page_Source, _folderWizardSourcePage);
if (!Theme::instance()->singleSyncFolder()) {
_folderWizardTargetPage = new FolderWizardRemotePath(account);
- setPage(Page_Target, _folderWizardTargetPage );
+ setPage(Page_Target, _folderWizardTargetPage);
}
setPage(Page_SelectiveSync, _folderWizardSelectiveSyncPage);
- setWindowTitle( tr("Add Folder Sync Connection") );
+ setWindowTitle(tr("Add Folder Sync Connection"));
setOptions(QWizard::CancelButtonOnLeft);
setButtonText(QWizard::FinishButton, tr("Add Sync Connection"));
}
} // end namespace
-
* @brief The FormatWarningsWizardPage class
* @ingroup gui
*/
-class FormatWarningsWizardPage : public QWizardPage {
+class FormatWarningsWizardPage : public QWizardPage
+{
Q_OBJECT
protected:
QString formatWarnings(const QStringList &warnings) const;
{
Q_OBJECT
public:
- explicit FolderWizardLocalPath(const AccountPtr& account);
+ explicit FolderWizardLocalPath(const AccountPtr &account);
~FolderWizardLocalPath();
virtual bool isComplete() const Q_DECL_OVERRIDE;
void initializePage() Q_DECL_OVERRIDE;
void cleanupPage() Q_DECL_OVERRIDE;
- void setFolderMap( const Folder::Map &fm ) { _folderMap = fm; }
+ void setFolderMap(const Folder::Map &fm) { _folderMap = fm; }
protected slots:
void slotChooseLocalFolder();
{
Q_OBJECT
public:
- explicit FolderWizardRemotePath(const AccountPtr& account);
+ explicit FolderWizardRemotePath(const AccountPtr &account);
~FolderWizardRemotePath();
virtual bool isComplete() const Q_DECL_OVERRIDE;
protected slots:
- void showWarn( const QString& = QString() ) const;
+ void showWarn(const QString & = QString()) const;
void slotAddRemoteFolder();
- void slotCreateRemoteFolder(const QString&);
+ void slotCreateRemoteFolder(const QString &);
void slotCreateRemoteFolderFinished(QNetworkReply::NetworkError error);
- void slotHandleMkdirNetworkError(QNetworkReply*);
- void slotHandleLsColNetworkError(QNetworkReply*);
- void slotUpdateDirectories(const QStringList&);
+ void slotHandleMkdirNetworkError(QNetworkReply *);
+ void slotHandleLsColNetworkError(QNetworkReply *);
+ void slotUpdateDirectories(const QStringList &);
void slotRefreshFolders();
- void slotItemExpanded(QTreeWidgetItem*);
- void slotCurrentItemChanged(QTreeWidgetItem*);
- void slotFolderEntryEdited(const QString& text);
+ void slotItemExpanded(QTreeWidgetItem *);
+ void slotCurrentItemChanged(QTreeWidgetItem *);
+ void slotFolderEntryEdited(const QString &text);
void slotLsColFolderEntry();
- void slotTypedPathFound(const QStringList& subpaths);
- void slotTypedPathError(QNetworkReply* reply);
+ void slotTypedPathFound(const QStringList &subpaths);
+ void slotTypedPathError(QNetworkReply *reply);
+
private:
- LsColJob* runLsColJob(const QString& path);
+ LsColJob *runLsColJob(const QString &path);
void recursiveInsert(QTreeWidgetItem *parent, QStringList pathTrail, QString path);
bool selectByPath(QString path);
Ui_FolderWizardTargetPage _ui;
{
Q_OBJECT
public:
- explicit FolderWizardSelectiveSync(const AccountPtr& account);
+ explicit FolderWizardSelectiveSync(const AccountPtr &account);
~FolderWizardSelectiveSync();
virtual bool validatePage() Q_DECL_OVERRIDE;
private:
SelectiveSyncWidget *_selectiveSync;
-
};
/**
{
Q_OBJECT
public:
-
enum {
Page_Source,
Page_Target,
~FolderWizard();
private:
-
FolderWizardLocalPath *_folderWizardSourcePage;
FolderWizardRemotePath *_folderWizardTargetPage;
FolderWizardSelectiveSync *_folderWizardSelectiveSyncPage;
namespace OCC {
-GeneralSettings::GeneralSettings(QWidget *parent) :
- QWidget(parent),
- _ui(new Ui::GeneralSettings),
- _currentlyLoading(false)
+GeneralSettings::GeneralSettings(QWidget *parent)
+ : QWidget(parent)
+ , _ui(new Ui::GeneralSettings)
+ , _currentlyLoading(false)
{
_ui->setupUi(this);
connect(_ui->desktopNotificationsCheckBox, SIGNAL(toggled(bool)),
- SLOT(slotToggleOptionalDesktopNotifications(bool)));
+ SLOT(slotToggleOptionalDesktopNotifications(bool)));
_ui->autostartCheckBox->setChecked(Utility::hasLaunchOnStartup(Theme::instance()->appName()));
connect(_ui->autostartCheckBox, SIGNAL(toggled(bool)), SLOT(slotToggleLaunchOnStartup(bool)));
* align properly vertically , fixes bug #3758
*/
int m0, m1, m2, m3;
- _ui->horizontalLayout_3->getContentsMargins( &m0, &m1, &m2, &m3 );
- _ui->horizontalLayout_3->setContentsMargins(0, m1, m2, m3 );
+ _ui->horizontalLayout_3->getContentsMargins(&m0, &m1, &m2, &m3);
+ _ui->horizontalLayout_3->setContentsMargins(0, m1, m2, m3);
// OEM themes are not obliged to ship mono icons, so there
// is no point in offering an option
connect(_ui->ignoredFilesButton, SIGNAL(clicked()), SLOT(slotIgnoreFilesEditor()));
// accountAdded means the wizard was finished and the wizard might change some options.
- connect(AccountManager::instance(), SIGNAL(accountAdded(AccountState*)), this, SLOT(loadMiscSettings()));
+ connect(AccountManager::instance(), SIGNAL(accountAdded(AccountState *)), this, SLOT(loadMiscSettings()));
}
GeneralSettings::~GeneralSettings()
delete _syncLogDialog;
}
-QSize GeneralSettings::sizeHint() const {
+QSize GeneralSettings::sizeHint() const
+{
return QSize(ownCloudGui::settingsDialogSize().width(), QWidget::sizeHint().height());
}
void GeneralSettings::loadMiscSettings()
{
-#if QT_VERSION < QT_VERSION_CHECK( 5, 4, 0 )
+#if QT_VERSION < QT_VERSION_CHECK(5, 4, 0)
QScopedValueRollback<bool> scope(_currentlyLoading);
_currentlyLoading = true;
#else
void GeneralSettings::slotUpdateInfo()
{
// Note: the sparkle-updater is not an OCUpdater
- OCUpdater *updater = qobject_cast<OCUpdater*>(Updater::instance());
+ OCUpdater *updater = qobject_cast<OCUpdater *>(Updater::instance());
if (ConfigFile().skipUpdateCheck()) {
updater = 0; // don't show update info if updates are disabled
}
cfgFile.setCrashReporter(_ui->crashreporterCheckBox->isChecked());
cfgFile.setNewBigFolderSizeLimit(_ui->newFolderLimitCheckBox->isChecked(),
- _ui->newFolderLimitSpinBox->value());
+ _ui->newFolderLimitSpinBox->value());
cfgFile.setConfirmExternalStorage(_ui->newExternalStorage->isChecked());
}
{
if (_ignoreEditor.isNull()) {
_ignoreEditor = new IgnoreListEditor(this);
- _ignoreEditor->setAttribute( Qt::WA_DeleteOnClose, true );
+ _ignoreEditor->setAttribute(Qt::WA_DeleteOnClose, true);
_ignoreEditor->open();
} else {
ownCloudGui::raiseDialog(_ignoreEditor);
class SyncLogDialog;
namespace Ui {
-class GeneralSettings;
+ class GeneralSettings;
}
/**
void loadMiscSettings();
private:
-
Ui::GeneralSettings *_ui;
QPointer<IgnoreListEditor> _ignoreEditor;
QPointer<SyncLogDialog> _syncLogDialog;
static int patternCol = 0;
static int deletableCol = 1;
-IgnoreListEditor::IgnoreListEditor(QWidget *parent) :
- QDialog(parent),
- ui(new Ui::IgnoreListEditor)
+IgnoreListEditor::IgnoreListEditor(QWidget *parent)
+ : QDialog(parent)
+ , ui(new Ui::IgnoreListEditor)
{
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
ui->setupUi(this);
ConfigFile cfgFile;
readOnlyTooltip = tr("This entry is provided by the system at '%1' "
"and cannot be modified in this view.")
- .arg(QDir::toNativeSeparators(cfgFile.excludeFile(ConfigFile::SystemScope)));
+ .arg(QDir::toNativeSeparators(cfgFile.excludeFile(ConfigFile::SystemScope)));
readIgnoreFile(cfgFile.excludeFile(ConfigFile::SystemScope), true);
readIgnoreFile(cfgFile.excludeFile(ConfigFile::UserScope), false);
ui->tableWidget->horizontalHeader()->setResizeMode(patternCol, QHeaderView::Stretch);
ui->tableWidget->verticalHeader()->setVisible(false);
- ui->syncHiddenFilesCheckBox->setChecked( !FolderMan::instance()->ignoreHiddenFiles() );
+ ui->syncHiddenFilesCheckBox->setChecked(!FolderMan::instance()->ignoreHiddenFiles());
}
IgnoreListEditor::~IgnoreListEditor()
bool IgnoreListEditor::ignoreHiddenFiles()
{
- return ! ui->syncHiddenFilesCheckBox->isChecked();
+ return !ui->syncHiddenFilesCheckBox->isChecked();
}
void IgnoreListEditor::slotItemSelectionChanged()
QString ignoreFile = cfgFile.excludeFile(ConfigFile::UserScope);
QFile ignores(ignoreFile);
if (ignores.open(QIODevice::WriteOnly)) {
- for(int row = 0; row < ui->tableWidget->rowCount(); ++row) {
+ for (int row = 0; row < ui->tableWidget->rowCount(); ++row) {
QTableWidgetItem *patternItem = ui->tableWidget->item(row, patternCol);
QTableWidgetItem *deletableItem = ui->tableWidget->item(row, deletableCol);
if (patternItem->flags() & Qt::ItemIsEnabled) {
if (deletableItem->checkState() == Qt::Checked) {
prepend = "]";
}
- ignores.write(prepend+patternItem->text().toUtf8()+'\n');
+ ignores.write(prepend + patternItem->text().toUtf8() + '\n');
}
}
} else {
QMessageBox::warning(this, tr("Could not open file"),
- tr("Cannot write changes to '%1'.").arg(ignoreFile));
+ tr("Cannot write changes to '%1'.").arg(ignoreFile));
}
ignores.close(); //close the file before reloading stuff.
- FolderMan * folderMan = FolderMan::instance();
+ FolderMan *folderMan = FolderMan::instance();
/* handle the hidden file checkbox */
// We need to force a remote discovery after a change of the ignore list.
// Otherwise we would not download the files/directories that are no longer
// ignored (because the remote etag did not change) (issue #3172)
- foreach (Folder* folder, folderMan->map()) {
+ foreach (Folder *folder, folderMan->map()) {
folder->journalDb()->forceRemoteDiscoveryNextSync();
folderMan->scheduleFolder(folder);
}
{
bool okClicked;
QString pattern = QInputDialog::getText(this, tr("Add Ignore Pattern"),
- tr("Add a new ignore pattern:"),
- QLineEdit::Normal, QString(), &okClicked);
+ tr("Add a new ignore pattern:"),
+ QLineEdit::Normal, QString(), &okClicked);
if (!okClicked || pattern.isEmpty())
return;
namespace OCC {
namespace Ui {
-class IgnoreListEditor;
+ class IgnoreListEditor;
}
/**
void slotAddPattern();
private:
- void readIgnoreFile(const QString& file, bool readOnly);
- int addPattern(const QString& pattern, bool deletable, bool readOnly);
+ void readIgnoreFile(const QString &file, bool readOnly);
+ int addPattern(const QString &pattern, bool deletable, bool readOnly);
QString readOnlyTooltip;
Ui::IgnoreListEditor *ui;
};
static const int check_frequency = 20 * 1000; // ms
-LockWatcher::LockWatcher(QObject* parent)
+LockWatcher::LockWatcher(QObject *parent)
: QObject(parent)
{
connect(&_timer, SIGNAL(timeout()),
- SLOT(checkFiles()));
+ SLOT(checkFiles()));
_timer.start(check_frequency);
}
-void LockWatcher::addFile(const QString& path)
+void LockWatcher::addFile(const QString &path)
{
qCInfo(lcLockWatcher) << "Watching for lock of" << path << "being released";
_watchedPaths.insert(path);
{
QSet<QString> unlocked;
- foreach (const QString& path, _watchedPaths) {
+ foreach (const QString &path, _watchedPaths) {
if (!FileSystem::isFileLocked(path)) {
qCInfo(lcLockWatcher) << "Lock of" << path << "was released";
emit fileUnlocked(path);
{
Q_OBJECT
public:
- explicit LockWatcher(QObject* parent = 0);
+ explicit LockWatcher(QObject *parent = 0);
/** Start watching a file.
*
* If the file is not locked later on, the fileUnlocked signal will be
* emitted once.
*/
- void addFile(const QString& path);
+ void addFile(const QString &path);
signals:
/** Emitted when one of the watched files is no longer
* being locked. */
- void fileUnlocked(const QString& path);
+ void fileUnlocked(const QString &path);
private slots:
void checkFiles();
QSet<QString> _watchedPaths;
QTimer _timer;
};
-
}
// ==============================================================================
LogWidget::LogWidget(QWidget *parent)
- :QPlainTextEdit(parent)
+ : QPlainTextEdit(parent)
{
- setReadOnly( true );
+ setReadOnly(true);
QFont font;
font.setFamily(QLatin1String("Courier New"));
font.setFixedPitch(true);
- document()->setDefaultFont( font );
+ document()->setDefaultFont(font);
}
// ==============================================================================
-LogBrowser::LogBrowser(QWidget *parent) :
- QDialog(parent),
- _logWidget( new LogWidget(parent) )
+LogBrowser::LogBrowser(QWidget *parent)
+ : QDialog(parent)
+ , _logWidget(new LogWidget(parent))
{
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
setObjectName("LogBrowser"); // for save/restoreGeometry()
QVBoxLayout *mainLayout = new QVBoxLayout;
// mainLayout->setMargin(0);
- mainLayout->addWidget( _logWidget );
+ mainLayout->addWidget(_logWidget);
QHBoxLayout *toolLayout = new QHBoxLayout;
- mainLayout->addLayout( toolLayout );
+ mainLayout->addLayout(toolLayout);
// Search input field
QLabel *lab = new QLabel(tr("&Search:") + " ");
_findTermEdit = new QLineEdit;
- lab->setBuddy( _findTermEdit );
+ lab->setBuddy(_findTermEdit);
toolLayout->addWidget(lab);
- toolLayout->addWidget( _findTermEdit );
+ toolLayout->addWidget(_findTermEdit);
// find button
QPushButton *findBtn = new QPushButton;
- findBtn->setText( tr("&Find") );
- connect( findBtn, SIGNAL(clicked()), this, SLOT(slotFind()));
- toolLayout->addWidget( findBtn );
+ findBtn->setText(tr("&Find"));
+ connect(findBtn, SIGNAL(clicked()), this, SLOT(slotFind()));
+ toolLayout->addWidget(findBtn);
// stretch
toolLayout->addStretch(1);
_statusLabel = new QLabel;
- toolLayout->addWidget( _statusLabel );
+ toolLayout->addWidget(_statusLabel);
toolLayout->addStretch(5);
// Debug logging
_logDebugCheckBox = new QCheckBox(tr("&Capture debug messages") + " ");
connect(_logDebugCheckBox, SIGNAL(stateChanged(int)), SLOT(slotDebugCheckStateChanged(int)));
- toolLayout->addWidget( _logDebugCheckBox );
+ toolLayout->addWidget(_logDebugCheckBox);
QDialogButtonBox *btnbox = new QDialogButtonBox;
- QPushButton *closeBtn = btnbox->addButton( QDialogButtonBox::Close );
- connect(closeBtn,SIGNAL(clicked()),this,SLOT(close()));
+ QPushButton *closeBtn = btnbox->addButton(QDialogButtonBox::Close);
+ connect(closeBtn, SIGNAL(clicked()), this, SLOT(close()));
- mainLayout->addWidget( btnbox );
+ mainLayout->addWidget(btnbox);
// clear button
_clearBtn = new QPushButton;
- _clearBtn->setText( tr("Clear") );
- _clearBtn->setToolTip( tr("Clear the log display.") );
+ _clearBtn->setText(tr("Clear"));
+ _clearBtn->setToolTip(tr("Clear the log display."));
btnbox->addButton(_clearBtn, QDialogButtonBox::ActionRole);
- connect( _clearBtn, SIGNAL(clicked()), this, SLOT(slotClearLog()));
+ connect(_clearBtn, SIGNAL(clicked()), this, SLOT(slotClearLog()));
// save Button
_saveBtn = new QPushButton;
- _saveBtn->setText( tr("S&ave") );
+ _saveBtn->setText(tr("S&ave"));
_saveBtn->setToolTip(tr("Save the log file to a file on disk for debugging."));
btnbox->addButton(_saveBtn, QDialogButtonBox::ActionRole);
- connect( _saveBtn, SIGNAL(clicked()),this, SLOT(slotSave()));
+ connect(_saveBtn, SIGNAL(clicked()), this, SLOT(slotSave()));
- setLayout( mainLayout );
+ setLayout(mainLayout);
setModal(false);
Logger::instance()->setLogWindowActivated(true);
// Direct connection for log coming from this thread, and queued for the one in a different thread
- connect(Logger::instance(), SIGNAL(logWindowLog(QString)),this,SLOT(slotNewLog(QString)), Qt::AutoConnection);
+ connect(Logger::instance(), SIGNAL(logWindowLog(QString)), this, SLOT(slotNewLog(QString)), Qt::AutoConnection);
QAction *showLogWindow = new QAction(this);
showLogWindow->setShortcut(QKeySequence("F12"));
ConfigFile cfg;
cfg.restoreGeometry(this);
int lines = cfg.maxLogLines();
- _logWidget->document()->setMaximumBlockCount( lines );
-
+ _logWidget->document()->setMaximumBlockCount(lines);
}
LogBrowser::~LogBrowser()
}
-void LogBrowser::slotNewLog( const QString& msg )
+void LogBrowser::slotNewLog(const QString &msg)
{
- if( _logWidget->isVisible() ) {
- _logWidget->appendPlainText( msg );
+ if (_logWidget->isVisible()) {
+ _logWidget->appendPlainText(msg);
}
}
{
QString searchText = _findTermEdit->text();
- if( searchText.isEmpty() ) return;
+ if (searchText.isEmpty())
+ return;
- search( searchText );
+ search(searchText);
}
void LogBrowser::slotDebugCheckStateChanged(int checkState)
Logger::instance()->setLogDebug(checkState == Qt::Checked);
}
-void LogBrowser::search( const QString& str )
+void LogBrowser::search(const QString &str)
{
QList<QTextEdit::ExtraSelection> extraSelections;
QColor color = QColor(Qt::gray).lighter(130);
_statusLabel->clear();
- while(_logWidget->find(str))
- {
+ while (_logWidget->find(str)) {
QTextEdit::ExtraSelection extra;
extra.format.setBackground(color);
{
_saveBtn->setEnabled(false);
- QString saveFile = QFileDialog::getSaveFileName( this, tr("Save log file"), QDir::homePath() );
+ QString saveFile = QFileDialog::getSaveFileName(this, tr("Save log file"), QDir::homePath());
- if( ! saveFile.isEmpty() ) {
+ if (!saveFile.isEmpty()) {
QFile file(saveFile);
if (file.open(QIODevice::WriteOnly)) {
}
}
_saveBtn->setEnabled(true);
-
}
void LogBrowser::slotClearLog()
* @brief The LogWidget class
* @ingroup gui
*/
-class LogWidget : public QPlainTextEdit
+class LogWidget : public QPlainTextEdit
{
Q_OBJECT
public:
explicit LogWidget(QWidget *parent = 0);
signals:
-
};
/**
*/
class LogBrowser : public QDialog
{
- Q_OBJECT
+ Q_OBJECT
public:
explicit LogBrowser(QWidget *parent = 0);
~LogBrowser();
- void setLogFile(const QString& , bool );
+ void setLogFile(const QString &, bool);
protected:
void showEvent(QShowEvent *) Q_DECL_OVERRIDE;
void closeEvent(QCloseEvent *) Q_DECL_OVERRIDE;
protected slots:
- void slotNewLog( const QString &msg );
+ void slotNewLog(const QString &msg);
void slotFind();
void slotDebugCheckStateChanged(int);
- void search( const QString& );
+ void search(const QString &);
void slotSave();
void slotClearLog();
QCheckBox *_logDebugCheckBox;
QPushButton *_saveBtn;
QPushButton *_clearBtn;
- QLabel *_statusLabel;
-
+ QLabel *_statusLabel;
};
} // namespace
void warnSystray()
{
QMessageBox::critical(0, qApp->translate("main.cpp", "System Tray not available"),
- qApp->translate("main.cpp", "%1 requires on a working system tray. "
- "If you are running XFCE, please follow "
- "<a href=\"http://docs.xfce.org/xfce/xfce4-panel/systray\">these instructions</a>. "
- "Otherwise, please install a system tray application such as 'trayer' and try again.")
- .arg(Theme::instance()->appNameGUI()));
+ qApp->translate("main.cpp", "%1 requires on a working system tray. "
+ "If you are running XFCE, please follow "
+ "<a href=\"http://docs.xfce.org/xfce/xfce4-panel/systray\">these instructions</a>. "
+ "Otherwise, please install a system tray application such as 'trayer' and try again.")
+ .arg(Theme::instance()->appNameGUI()));
}
int main(int argc, char **argv)
Q_INIT_RESOURCE(client);
#ifdef Q_OS_WIN
- // If the font size ratio is set on Windows, we need to
- // enable the auto pixelRatio in Qt since we don't
- // want to use sizes relative to the font size everywhere.
- // This is automatic on OS X, but opt-in on Windows and Linux
- // https://doc-snapshots.qt.io/qt5-5.6/highdpi.html#qt-support
- // We do not define it on linux so the behaviour is kept the same
- // as other Qt apps in the desktop environment. (which may or may
- // not set this envoronment variable)
+// If the font size ratio is set on Windows, we need to
+// enable the auto pixelRatio in Qt since we don't
+// want to use sizes relative to the font size everywhere.
+// This is automatic on OS X, but opt-in on Windows and Linux
+// https://doc-snapshots.qt.io/qt5-5.6/highdpi.html#qt-support
+// We do not define it on linux so the behaviour is kept the same
+// as other Qt apps in the desktop environment. (which may or may
+// not set this envoronment variable)
#if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
qputenv("QT_AUTO_SCREEN_SCALE_FACTOR", "1");
#else
#ifndef Q_OS_WIN
signal(SIGPIPE, SIG_IGN);
#endif
- if( app.giveHelp() ) {
+ if (app.giveHelp()) {
app.showHelp();
return 0;
}
- if( app.versionOnly() ) {
+ if (app.versionOnly()) {
app.showVersion();
return 0;
}
- // check a environment variable for core dumps
+// check a environment variable for core dumps
#ifdef Q_OS_UNIX
- if( !qgetenv("OWNCLOUD_CORE_DUMP").isEmpty() ) {
+ if (!qgetenv("OWNCLOUD_CORE_DUMP").isEmpty()) {
struct rlimit core_limit;
core_limit.rlim_cur = RLIM_INFINITY;
core_limit.rlim_max = RLIM_INFINITY;
// needs to terminate here, e.g. because
// the updater is triggered
Updater *updater = Updater::instance();
- if ( updater && updater->handleStartup()) {
+ if (updater && updater->handleStartup()) {
return true;
}
// if the application is already running, notify it.
- if(app.isRunning()) {
+ if (app.isRunning()) {
qCInfo(lcApplication) << "Already running, exiting...";
if (app.isSessionRestored()) {
// This call is mirrored with the one in Application::slotParseMessage
QStringList args = app.arguments();
if (args.size() > 1) {
QString msg = args.join(QLatin1String("|"));
- if(!app.sendMessage(QLatin1String("MSG_PARSEOPTIONS:") + msg))
+ if (!app.sendMessage(QLatin1String("MSG_PARSEOPTIONS:") + msg))
return -1;
}
- if(!app.sendMessage(QLatin1String("MSG_SHOWSETTINGS"))) {
+ if (!app.sendMessage(QLatin1String("MSG_SHOWSETTINGS"))) {
return -1;
}
return 0;
}
#if QT_VERSION > QT_VERSION_CHECK(5, 0, 0)
if (qgetenv("QT_QPA_PLATFORMTHEME") != "appmenu-qt5")
- // We can't call isSystemTrayAvailable with appmenu-qt5 begause it hides the systemtray
- // (issue #4693)
+// We can't call isSystemTrayAvailable with appmenu-qt5 begause it hides the systemtray
+// (issue #4693)
#endif
{
if (!QSystemTrayIcon::isSystemTrayAvailable()) {
if (!QSystemTrayIcon::isSystemTrayAvailable()) {
Utility::sleep(1);
attempts++;
- if (attempts < 30) continue;
+ if (attempts < 30)
+ continue;
} else {
break;
}
return app.exec();
}
-
namespace OCC {
-NetworkSettings::NetworkSettings(QWidget *parent) :
- QWidget(parent),
- _ui(new Ui::NetworkSettings)
+NetworkSettings::NetworkSettings(QWidget *parent)
+ : QWidget(parent)
+ , _ui(new Ui::NetworkSettings)
{
_ui->setupUi(this);
_ui->passwordLineEdit->setEnabled(true);
_ui->authWidgets->setEnabled(_ui->authRequiredcheckBox->isChecked());
connect(_ui->authRequiredcheckBox, SIGNAL(toggled(bool)),
- _ui->authWidgets, SLOT(setEnabled(bool)));
+ _ui->authWidgets, SLOT(setEnabled(bool)));
connect(_ui->manualProxyRadioButton, SIGNAL(toggled(bool)),
- _ui->manualSettings, SLOT(setEnabled(bool)));
+ _ui->manualSettings, SLOT(setEnabled(bool)));
connect(_ui->manualProxyRadioButton, SIGNAL(toggled(bool)),
- _ui->typeComboBox, SLOT(setEnabled(bool)));
+ _ui->typeComboBox, SLOT(setEnabled(bool)));
loadProxySettings();
loadBWLimitSettings();
delete _ui;
}
-QSize NetworkSettings::sizeHint() const {
+QSize NetworkSettings::sizeHint() const
+{
return QSize(ownCloudGui::settingsDialogSize().width(), QWidget::sizeHint().height());
}
{
ConfigFile cfgFile;
-#if QT_VERSION < QT_VERSION_CHECK(5,3,3)
+#if QT_VERSION < QT_VERSION_CHECK(5, 3, 3)
// QNAM bandwidth limiting only works with versions of Qt greater or equal to 5.3.3
// (It needs Qt commits 097b641 and b99fa32)
#endif
int useDownloadLimit = cfgFile.useDownloadLimit();
- if ( useDownloadLimit >= 1 ) {
+ if (useDownloadLimit >= 1) {
_ui->downloadLimitRadioButton->setChecked(true);
- } else if (useDownloadLimit == 0){
+ } else if (useDownloadLimit == 0) {
_ui->noDownloadLimitRadioButton->setChecked(true);
} else {
_ui->autoDownloadLimitRadioButton->setChecked(true);
_ui->downloadSpinBox->setValue(cfgFile.downloadLimit());
int useUploadLimit = cfgFile.useUploadLimit();
- if ( useUploadLimit >= 1 ) {
+ if (useUploadLimit >= 1) {
_ui->uploadLimitRadioButton->setChecked(true);
- } else if (useUploadLimit == 0){
+ } else if (useUploadLimit == 0) {
_ui->noUploadLimitRadioButton->setChecked(true);
} else {
_ui->autoUploadLimitRadioButton->setChecked(true);
{
ConfigFile cfgFile;
- if (_ui->noProxyRadioButton->isChecked()){
+ if (_ui->noProxyRadioButton->isChecked()) {
cfgFile.setProxyType(QNetworkProxy::NoProxy);
- } else if (_ui->systemProxyRadioButton->isChecked()){
+ } else if (_ui->systemProxyRadioButton->isChecked()) {
cfgFile.setProxyType(QNetworkProxy::DefaultProxy);
} else if (_ui->manualProxyRadioButton->isChecked()) {
int type = _ui->typeComboBox->itemData(_ui->typeComboBox->currentIndex()).toInt();
QString user = _ui->userLineEdit->text();
QString pass = _ui->passwordLineEdit->text();
cfgFile.setProxyType(type, _ui->hostLineEdit->text(),
- _ui->portSpinBox->value(), needsAuth, user, pass);
+ _ui->portSpinBox->value(), needsAuth, user, pass);
}
ClientProxy proxy;
namespace OCC {
namespace Ui {
-class NetworkSettings;
+ class NetworkSettings;
}
/**
Q_DECLARE_LOGGING_CATEGORY(lcNotifications)
NotificationConfirmJob::NotificationConfirmJob(AccountPtr account)
-: AbstractNetworkJob(account, ""),
- _widget(0)
+ : AbstractNetworkJob(account, "")
+ , _widget(0)
{
setIgnoreCredentialFailure(true);
}
-void NotificationConfirmJob::setLinkAndVerb(const QUrl& link, const QByteArray &verb)
+void NotificationConfirmJob::setLinkAndVerb(const QUrl &link, const QByteArray &verb)
{
_link = link;
_verb = verb;
}
-void NotificationConfirmJob::setWidget( NotificationWidget *widget )
+void NotificationConfirmJob::setWidget(NotificationWidget *widget)
{
_widget = widget;
}
void NotificationConfirmJob::start()
{
- if( !_link.isValid() ) {
+ if (!_link.isValid()) {
qCWarning(lcNotifications) << "Attempt to trigger invalid URL: " << _link.toString();
return;
}
// FIXME: check for the reply code!
const QString replyStr = reply()->readAll();
- if( replyStr.contains( "<?xml version=\"1.0\"?>") ) {
- QRegExp rex("<statuscode>(\\d+)</statuscode>");
- if( replyStr.contains(rex) ) {
- // this is a error message coming back from ocs.
- replyCode = rex.cap(1).toInt();
- }
+ if (replyStr.contains("<?xml version=\"1.0\"?>")) {
+ QRegExp rex("<statuscode>(\\d+)</statuscode>");
+ if (replyStr.contains(rex)) {
+ // this is a error message coming back from ocs.
+ replyCode = rex.cap(1).toInt();
+ }
}
emit jobFinished(replyStr, replyCode);
return true;
-
}
-
}
* All the communication logic is handled in this class.
*
*/
-class NotificationConfirmJob : public AbstractNetworkJob {
+class NotificationConfirmJob : public AbstractNetworkJob
+{
Q_OBJECT
public:
-
explicit NotificationConfirmJob(AccountPtr account);
/**
*
* @param verb currently supported GET PUT POST DELETE
*/
- void setLinkAndVerb(const QUrl& link, const QByteArray &verb);
+ void setLinkAndVerb(const QUrl &link, const QByteArray &verb);
/**
* @brief Start the OCS request
* it when the job has finished
* @param widget pointer to the notification widget to store
*/
- void setWidget( NotificationWidget *widget );
+ void setWidget(NotificationWidget *widget);
/**
* @brief widget - get the associated notification widget as stored
QUrl _link;
NotificationWidget *_widget;
};
-
}
#endif // NotificationConfirmJob_H
Q_LOGGING_CATEGORY(lcNotifications, "gui.notifications", QtInfoMsg)
-NotificationWidget::NotificationWidget(QWidget *parent) : QWidget(parent)
+NotificationWidget::NotificationWidget(QWidget *parent)
+ : QWidget(parent)
{
_ui.setupUi(this);
_progressIndi = new QProgressIndicator(this);
_ui.horizontalLayout->addWidget(_progressIndi);
}
-void NotificationWidget::setActivity(const Activity& activity)
+void NotificationWidget::setActivity(const Activity &activity)
{
_myActivity = activity;
ASSERT(!_accountName.isEmpty());
// _ui._headerLabel->setText( );
- _ui._subjectLabel->setVisible( !activity._subject.isEmpty() );
- _ui._messageLabel->setVisible( !activity._message.isEmpty() );
+ _ui._subjectLabel->setVisible(!activity._subject.isEmpty());
+ _ui._messageLabel->setVisible(!activity._message.isEmpty());
_ui._subjectLabel->setText(activity._subject);
_ui._messageLabel->setText(activity._message);
_ui._timeLabel->setText(tText);
// always remove the buttons
- foreach( auto button, _ui._buttonBox->buttons() ) {
+ foreach (auto button, _ui._buttonBox->buttons()) {
_ui._buttonBox->removeButton(button);
}
_buttons.clear();
// display buttons for the links
- if( activity._links.isEmpty() ) {
+ if (activity._links.isEmpty()) {
// in case there is no action defined, do a close button.
- QPushButton *b = _ui._buttonBox->addButton( QDialogButtonBox::Close );
+ QPushButton *b = _ui._buttonBox->addButton(QDialogButtonBox::Close);
b->setDefault(true);
connect(b, SIGNAL(clicked()), this, SLOT(slotButtonClicked()));
_buttons.append(b);
} else {
- foreach( auto link, activity._links ) {
+ foreach (auto link, activity._links) {
QPushButton *b = _ui._buttonBox->addButton(link._label, QDialogButtonBox::AcceptRole);
b->setDefault(link._isPrimary);
connect(b, SIGNAL(clicked()), this, SLOT(slotButtonClicked()));
{
QObject *buttonWidget = QObject::sender();
int index = -1;
- if( buttonWidget ) {
+ if (buttonWidget) {
// find the button that was clicked, it has to be in the list
// of buttons that were added to the button box before.
- for( int i = 0; i < _buttons.count(); i++ ) {
- if( _buttons.at(i) == buttonWidget ) {
+ for (int i = 0; i < _buttons.count(); i++) {
+ if (_buttons.at(i) == buttonWidget) {
index = i;
}
_buttons.at(i)->setEnabled(false);
}
// if the button was found, the link must be called
- if( index > -1 && _myActivity._links.count() == 0 ) {
+ if (index > -1 && _myActivity._links.count() == 0) {
// no links, that means it was the close button
// empty link. Just close and remove the widget.
QString doneText = tr("Closing in a few seconds...");
return;
}
- if( index > -1 && index < _myActivity._links.count() ) {
+ if (index > -1 && index < _myActivity._links.count()) {
ActivityLink triggeredLink = _myActivity._links.at(index);
_actionLabel = triggeredLink._label;
- if( ! triggeredLink._link.isEmpty() ) {
- qCInfo(lcNotifications) << "Notification Link: "<< triggeredLink._verb << triggeredLink._link;
+ if (!triggeredLink._link.isEmpty()) {
+ qCInfo(lcNotifications) << "Notification Link: " << triggeredLink._verb << triggeredLink._link;
_progressIndi->startAnimation();
- emit sendNotificationRequest( _accountName, triggeredLink._link, triggeredLink._verb );
+ emit sendNotificationRequest(_accountName, triggeredLink._link, triggeredLink._verb);
}
}
}
QString timeStr = locale.toString(QTime::currentTime());
// the ocs API returns stat code 100 if it succeeded.
- if( statusCode != OCS_SUCCESS_STATUS_CODE ) {
+ if (statusCode != OCS_SUCCESS_STATUS_CODE) {
qCWarning(lcNotifications) << "Notification Request to Server failed, leave button visible.";
- for( i = 0; i < _buttons.count(); i++ ) {
+ for (i = 0; i < _buttons.count(); i++) {
_buttons.at(i)->setEnabled(true);
}
//: The second parameter is a time, such as 'failed at 09:58pm'
//: The second parameter is a time, such as 'selected at 09:58pm'
doneText = tr("'%1' selected at %2").arg(_actionLabel, timeStr);
}
- _ui._timeLabel->setText( doneText );
+ _ui._timeLabel->setText(doneText);
_progressIndi->stopAnimation();
-
}
-
}
Activity activity() const;
signals:
- void sendNotificationRequest( const QString&, const QString& link, const QByteArray& verb);
- void requestCleanupAndBlacklist( const Activity& activity );
+ void sendNotificationRequest(const QString &, const QString &link, const QByteArray &verb);
+ void requestCleanupAndBlacklist(const Activity &activity);
public slots:
- void setActivity(const Activity& activity);
- void slotNotificationRequestFinished(int statusCode);
+ void setActivity(const Activity &activity);
+ void slotNotificationRequestFinished(int statusCode);
private slots:
- void slotButtonClicked();
+ void slotButtonClicked();
private:
Ui_NotificationWidget _ui;
Activity _myActivity;
- QList<QPushButton*> _buttons;
+ QList<QPushButton *> _buttons;
QString _accountName;
QProgressIndicator *_progressIndi;
QString _actionLabel;
};
-
}
#endif // NOTIFICATIONWIDGET_H
Q_LOGGING_CATEGORY(lcOcs, "gui.sharing.ocs", QtInfoMsg)
OcsJob::OcsJob(AccountPtr account)
-: AbstractNetworkJob(account, "")
+ : AbstractNetworkJob(account, "")
{
_passStatusCodes.append(OCS_SUCCESS_STATUS_CODE);
setIgnoreCredentialFailure(true);
static QList<QPair<QByteArray, QByteArray>>
percentEncodeQueryItems(
- const QList<QPair<QString, QString>> & items)
+ const QList<QPair<QString, QString>> &items)
{
QList<QPair<QByteArray, QByteArray>> result;
- foreach (const auto& item, items) {
+ foreach (const auto &item, items) {
result.append(qMakePair(
QUrl::toPercentEncoding(item.first),
QUrl::toPercentEncoding(item.second)));
} else if (_verb == "POST" || _verb == "PUT") {
// Url encode the _postParams and put them in a buffer.
QByteArray postData;
- Q_FOREACH(auto tmp, _params) {
+ Q_FOREACH (auto tmp, _params) {
if (!postData.isEmpty()) {
postData.append("&");
}
QJsonParseError error;
auto json = QJsonDocument::fromJson(replyData, &error);
if (error.error != QJsonParseError::NoError) {
- qCWarning(lcOcs) << "Could not parse reply to"
- << _verb
- << Utility::concatUrlPath(account()->url(), path())
- << _params
- << error.errorString()
- << ":" << replyData;
+ qCWarning(lcOcs) << "Could not parse reply to"
+ << _verb
+ << Utility::concatUrlPath(account()->url(), path())
+ << _params
+ << error.errorString()
+ << ":" << replyData;
}
QString message;
const int statusCode = getJsonReturnCode(json, message);
if (!_passStatusCodes.contains(statusCode)) {
qCWarning(lcOcs) << "Reply to"
- << _verb
- << Utility::concatUrlPath(account()->url(), path())
- << _params
- << "has unexpected status code:" << statusCode << replyData;
+ << _verb
+ << Utility::concatUrlPath(account()->url(), path())
+ << _params
+ << "has unexpected status code:" << statusCode << replyData;
emit ocsError(statusCode, message);
} else {
emit jobFinished(json);
return code;
}
-
}
*
* All OCS jobs (e.g. sharing) should extend this class.
*/
-class OcsJob : public AbstractNetworkJob {
+class OcsJob : public AbstractNetworkJob
+{
Q_OBJECT
protected:
-
explicit OcsJob(AccountPtr account);
/**
*
* @param verb currently supported PUT POST DELETE
*/
- void setVerb(const QByteArray& verb);
+ void setVerb(const QByteArray &verb);
/**
* Add a new parameter to the request.
* @param name The name of the parameter
* @param value The value of the parameter
*/
- void addParam(const QString& name, const QString &value);
+ void addParam(const QString &name, const QString &value);
/**
* Set the post parameters
* @param postParams list of pairs to add (urlEncoded) to the body of the
* request
*/
- void setPostParams(const QList<QPair<QString, QString> >& postParams);
+ void setPostParams(const QList<QPair<QString, QString>> &postParams);
/**
* List of expected statuscodes for this request
private:
QByteArray _verb;
- QList<QPair<QString, QString> > _params;
+ QList<QPair<QString, QString>> _params;
QVector<int> _passStatusCodes;
};
-
}
#endif // OCSJOB_H
namespace OCC {
OcsShareeJob::OcsShareeJob(AccountPtr account)
-: OcsJob(account)
+ : OcsJob(account)
{
setPath("ocs/v1.php/apps/files_sharing/api/v1/sharees");
connect(this, SIGNAL(jobFinished(QJsonDocument)), SLOT(jobDone(QJsonDocument)));
-
}
void OcsShareeJob::getSharees(const QString &search,
- const QString &itemType,
- int page,
- int perPage)
+ const QString &itemType,
+ int page,
+ int perPage)
{
setVerb("GET");
{
emit shareeJobFinished(reply);
}
-
}
*
* Fetching sharees from the OCS Sharee API
*/
-class OcsShareeJob : public OcsJob {
+class OcsShareeJob : public OcsJob
+{
Q_OBJECT
public:
-
explicit OcsShareeJob(AccountPtr account);
/**
*
* @param path Path to request shares for (default all shares)
*/
- void getSharees(const QString& search, const QString& itemType, int page = 1, int perPage = 50);
+ void getSharees(const QString &search, const QString &itemType, int page = 1, int perPage = 50);
signals:
/**
* Result of the OCS request
private slots:
void jobDone(const QJsonDocument &reply);
-
};
-
}
#endif // OCSSHAREEJOB_H
namespace OCC {
OcsShareJob::OcsShareJob(AccountPtr account)
-: OcsJob(account)
+ : OcsJob(account)
{
setPath("ocs/v1.php/apps/files_sharing/api/v1/shares");
connect(this, SIGNAL(jobFinished(QJsonDocument)), this, SLOT(jobDone(QJsonDocument)));
start();
}
-void OcsShareJob::setPermissions(const QString &shareId,
- const Share::Permissions permissions)
+void OcsShareJob::setPermissions(const QString &shareId,
+ const Share::Permissions permissions)
{
appendPath(shareId);
setVerb("PUT");
}
void OcsShareJob::createLinkShare(const QString &path,
- const QString &name,
- const QString &password)
+ const QString &name,
+ const QString &password)
{
setVerb("POST");
start();
}
-void OcsShareJob::createShare(const QString& path,
- const Share::ShareType shareType,
- const QString& shareWith,
- const Share::Permissions permissions)
+void OcsShareJob::createShare(const QString &path,
+ const Share::ShareType shareType,
+ const QString &shareWith,
+ const Share::Permissions permissions)
{
setVerb("POST");
{
emit shareJobFinished(reply, _value);
}
-
}
* Handle talking to the OCS Share API.
* For creation, deletion and modification of shares.
*/
-class OcsShareJob : public OcsJob {
+class OcsShareJob : public OcsJob
+{
Q_OBJECT
public:
-
/**
* Constructor for new shares or listing of shares
*/
*
* @param path Path to request shares for (default all shares)
*/
- void getShares(const QString& path = "");
+ void getShares(const QString &path = "");
/**
* Delete the current Share
* @param date The expire date, if this date is invalid the expire date
* will be removed
*/
- void setExpireDate(const QString &shareId, const QDate& date);
+ void setExpireDate(const QString &shareId, const QDate &date);
/**
* Set the password of a share
* @param password The password of the share, if the password is empty the
* share will be removed
*/
- void setPassword(const QString &shareId, const QString& password);
+ void setPassword(const QString &shareId, const QString &password);
/**
* Set the share to be public upload
*
* @param permissions
*/
- void setPermissions(const QString &shareId,
- const Share::Permissions permissions);
+ void setPermissions(const QString &shareId,
+ const Share::Permissions permissions);
/**
* Create a new link share
* @param name The name of the link share, empty name auto-generates one
* @param password Optionally a password for the share
*/
- void createLinkShare(const QString& path,
- const QString& name,
- const QString& password);
+ void createLinkShare(const QString &path,
+ const QString &name,
+ const QString &password);
/**
* Create a new share
* @param shareWith The uid/gid/federated id to share with
* @param permissions The permissions the share will have
*/
- void createShare(const QString& path,
- const Share::ShareType shareType,
- const QString& shareWith = "",
- const Share::Permissions permissions = SharePermissionRead);
+ void createShare(const QString &path,
+ const Share::ShareType shareType,
+ const QString &shareWith = "",
+ const Share::Permissions permissions = SharePermissionRead);
/**
* Returns information on the items shared with the current user.
private:
QVariant _value;
};
-
}
#endif // OCSSHAREJOB_H
// local location
QString xdgDataHome = QFile::decodeName(qgetenv("XDG_DATA_HOME"));
if (xdgDataHome.isEmpty()) {
- xdgDataHome = QDir::homePath()+"/.local/share";
+ xdgDataHome = QDir::homePath() + "/.local/share";
}
dirs.prepend(xdgDataHome);
return dirs;
static QString findDefaultFileManager()
{
QProcess p;
- p.start("xdg-mime", QStringList() << "query" << "default" << "inode/directory", QFile::ReadOnly);
+ p.start("xdg-mime", QStringList() << "query"
+ << "default"
+ << "inode/directory",
+ QFile::ReadOnly);
p.waitForFinished();
QString fileName = QString::fromUtf8(p.readAll().trimmed());
if (fileName.isEmpty())
QFileInfo fi;
QStringList dirs = xdgDataDirs();
QStringList subdirs;
- subdirs << "/applications/" << "/applications/kde4/";
- foreach(QString dir, dirs) {
- foreach(QString subdir, subdirs) {
+ subdirs << "/applications/"
+ << "/applications/kde4/";
+ foreach (QString dir, dirs) {
+ foreach (QString subdir, subdirs) {
fi.setFile(dir + subdir + fileName);
if (fi.exists()) {
return fi.absoluteFilePath();
QFileInfo fi(localPath);
// canonicalFilePath returns empty if the file does not exist
- if( !fi.canonicalFilePath().isEmpty() ) {
+ if (!fi.canonicalFilePath().isEmpty()) {
QString nativeArgs;
if (!fi.isDir()) {
nativeArgs += QLatin1String("/select,");
QStringList scriptArgs;
scriptArgs << QLatin1String("-e")
<< QString::fromLatin1("tell application \"Finder\" to reveal POSIX file \"%1\"")
- .arg(localPath);
+ .arg(localPath);
QProcess::execute(QLatin1String("/usr/bin/osascript"), scriptArgs);
scriptArgs.clear();
scriptArgs << QLatin1String("-e")
bool canHandleFile = false; // assume dumb fm
args = exec.split(' ');
- if (args.count() > 0) app = args.takeFirst();
+ if (args.count() > 0)
+ app = args.takeFirst();
QString kdeSelectParam("--select");
canHandleFile = true;
}
- if (app.contains("dolphin"))
- {
+ if (app.contains("dolphin")) {
static bool dolphinCanSelect = checkDolphinCanSelect();
if (dolphinCanSelect && !args.contains(kdeSelectParam)) {
args.prepend(kdeSelectParam);
}
- if (args.count() == 0) args << fileToOpen;
+ if (args.count() == 0)
+ args << fileToOpen;
if (app.isEmpty() || args.isEmpty() || !canHandleFile) {
// fall back: open the default file manager, without ever selecting the file
}
}
}
-
}
#include "owncloudsetupwizard.h"
#include "sharedialog.h"
#if defined(Q_OS_MAC)
-# include "settingsdialogmac.h"
-# include "macwindow.h" // qtmacgoodies
+#include "settingsdialogmac.h"
+#include "macwindow.h" // qtmacgoodies
#else
-# include "settingsdialog.h"
+#include "settingsdialog.h"
#endif
#include "logger.h"
#include "logbrowser.h"
const char propertyAccountC[] = "oc_account";
-ownCloudGui::ownCloudGui(Application *parent) :
- QObject(parent),
- _tray(0),
+ownCloudGui::ownCloudGui(Application *parent)
+ : QObject(parent)
+ , _tray(0)
+ ,
#if defined(Q_OS_MAC)
- _settingsDialog(new SettingsDialogMac(this)),
+ _settingsDialog(new SettingsDialogMac(this))
+ ,
#else
- _settingsDialog(new SettingsDialog(this)),
+ _settingsDialog(new SettingsDialog(this))
+ ,
#endif
- _logBrowser(0),
- _contextMenuVisibleOsx(false),
- _recentActionsMenu(0),
- _qdbusmenuWorkaround(false),
- _folderOpenActionMapper(new QSignalMapper(this)),
- _recentItemsMapper(new QSignalMapper(this)),
- _app(parent)
+ _logBrowser(0)
+ , _contextMenuVisibleOsx(false)
+ , _recentActionsMenu(0)
+ , _qdbusmenuWorkaround(false)
+ , _folderOpenActionMapper(new QSignalMapper(this))
+ , _recentItemsMapper(new QSignalMapper(this))
+ , _app(parent)
{
_tray = new Systray();
_tray->setParent(this);
// for the beginning, set the offline icon until the account was verified
- _tray->setIcon( Theme::instance()->folderOfflineIcon(/*systray?*/ true, /*currently visible?*/ false));
+ _tray->setIcon(Theme::instance()->folderOfflineIcon(/*systray?*/ true, /*currently visible?*/ false));
connect(_tray.data(), SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
- SLOT(slotTrayClicked(QSystemTrayIcon::ActivationReason)));
+ SLOT(slotTrayClicked(QSystemTrayIcon::ActivationReason)));
setupActions();
setupContextMenu();
/* use a signal mapper to map the open requests to the alias names */
connect(_folderOpenActionMapper, SIGNAL(mapped(QString)),
- this, SLOT(slotFolderOpenAction(QString)));
+ this, SLOT(slotFolderOpenAction(QString)));
connect(_recentItemsMapper, SIGNAL(mapped(QString)),
- this, SLOT(slotOpenPath(QString)));
+ this, SLOT(slotOpenPath(QString)));
ProgressDispatcher *pd = ProgressDispatcher::instance();
- connect( pd, SIGNAL(progressInfo(QString,ProgressInfo)), this,
- SLOT(slotUpdateProgress(QString,ProgressInfo)) );
+ connect(pd, SIGNAL(progressInfo(QString, ProgressInfo)), this,
+ SLOT(slotUpdateProgress(QString, ProgressInfo)));
FolderMan *folderMan = FolderMan::instance();
- connect( folderMan, SIGNAL(folderSyncStateChange(Folder*)),
- this,SLOT(slotSyncStateChange(Folder*)));
+ connect(folderMan, SIGNAL(folderSyncStateChange(Folder *)),
+ this, SLOT(slotSyncStateChange(Folder *)));
- connect( AccountManager::instance(), SIGNAL(accountAdded(AccountState*)),
- SLOT(updateContextMenuNeeded()));
- connect( AccountManager::instance(), SIGNAL(accountRemoved(AccountState*)),
- SLOT(updateContextMenuNeeded()));
+ connect(AccountManager::instance(), SIGNAL(accountAdded(AccountState *)),
+ SLOT(updateContextMenuNeeded()));
+ connect(AccountManager::instance(), SIGNAL(accountRemoved(AccountState *)),
+ SLOT(updateContextMenuNeeded()));
- connect( Logger::instance(), SIGNAL(guiLog(QString,QString)),
- SLOT(slotShowTrayMessage(QString,QString)));
- connect( Logger::instance(), SIGNAL(optionalGuiLog(QString,QString)),
- SLOT(slotShowOptionalTrayMessage(QString,QString)));
- connect( Logger::instance(), SIGNAL(guiMessage(QString,QString)),
- SLOT(slotShowGuiMessage(QString,QString)));
+ connect(Logger::instance(), SIGNAL(guiLog(QString, QString)),
+ SLOT(slotShowTrayMessage(QString, QString)));
+ connect(Logger::instance(), SIGNAL(optionalGuiLog(QString, QString)),
+ SLOT(slotShowOptionalTrayMessage(QString, QString)));
+ connect(Logger::instance(), SIGNAL(guiMessage(QString, QString)),
+ SLOT(slotShowGuiMessage(QString, QString)));
setupOverlayIcons();
}
" end try\n"
"end tell\n");
- QString osascript = "/usr/bin/osascript";
- QStringList processArguments;
- // processArguments << "-l" << "AppleScript";
-
- QProcess p;
- p.start(osascript, processArguments);
- p.write(aScript.toUtf8());
- p.closeWriteChannel();
- //p.waitForReadyRead(-1);
- p.waitForFinished(5000);
- QByteArray result = p.readAll();
- QString resultAsString(result); // if appropriate
- qCInfo(lcApplication) << "Load Finder Overlay-Plugin: " << resultAsString << ": " << p.exitCode()
- << (p.exitCode() != 0 ? p.errorString() : QString::null);
- } else {
+ QString osascript = "/usr/bin/osascript";
+ QStringList processArguments;
+ // processArguments << "-l" << "AppleScript";
+
+ QProcess p;
+ p.start(osascript, processArguments);
+ p.write(aScript.toUtf8());
+ p.closeWriteChannel();
+ //p.waitForReadyRead(-1);
+ p.waitForFinished(5000);
+ QByteArray result = p.readAll();
+ QString resultAsString(result); // if appropriate
+ qCInfo(lcApplication) << "Load Finder Overlay-Plugin: " << resultAsString << ": " << p.exitCode()
+ << (p.exitCode() != 0 ? p.errorString() : QString::null);
+ } else {
qCWarning(lcApplication) << finderExtension << "does not exist! Finder Overlay Plugin loading failed";
}
}
void ownCloudGui::slotOpenSettingsDialog()
{
// if account is set up, start the configuration wizard.
- if( !AccountManager::instance()->accounts().isEmpty() ) {
+ if (!AccountManager::instance()->accounts().isEmpty()) {
if (_settingsDialog.isNull() || QApplication::activeWindow() != _settingsDialog) {
slotShowSettings();
} else {
}
}
-void ownCloudGui::slotTrayClicked( QSystemTrayIcon::ActivationReason reason )
+void ownCloudGui::slotTrayClicked(QSystemTrayIcon::ActivationReason reason)
{
if (_qdbusmenuWorkaround) {
static QElapsedTimer last_click;
}
// Left click
- if( reason == QSystemTrayIcon::Trigger ) {
+ if (reason == QSystemTrayIcon::Trigger) {
if (OwncloudSetupWizard::bringWizardToFrontIfVisible()) {
// brought wizard to front
} else if (_shareDialogs.size() > 0) {
// Share dialog(s) be hidden by other apps, bring them back
- Q_FOREACH(const QPointer<ShareDialog> &shareDialog, _shareDialogs) {
+ Q_FOREACH (const QPointer<ShareDialog> &shareDialog, _shareDialogs) {
Q_ASSERT(shareDialog.data());
raiseDialog(shareDialog);
}
// or SSL error dialog also comes to front.
}
-void ownCloudGui::slotSyncStateChange( Folder* folder )
+void ownCloudGui::slotSyncStateChange(Folder *folder)
{
slotComputeOverallSyncStatus();
updateContextMenuNeeded();
- if( !folder ) {
+ if (!folder) {
return; // Valid, just a general GUI redraw was needed.
}
auto result = folder->syncResult();
- qCInfo(lcApplication) << "Sync state changed for folder " << folder->remoteUrl().toString() << ": " << result.statusString();
+ qCInfo(lcApplication) << "Sync state changed for folder " << folder->remoteUrl().toString() << ": " << result.statusString();
if (result.status() == SyncResult::Success || result.status() == SyncResult::Error) {
Logger::instance()->enterNextLogFile();
}
if (result.status() == SyncResult::NotYetStarted) {
- _settingsDialog->slotRefreshActivity( folder->accountState() );
+ _settingsDialog->slotRefreshActivity(folder->accountState());
}
}
slotComputeOverallSyncStatus();
}
-void ownCloudGui::slotTrayMessageIfServerUnsupported(Account* account)
+void ownCloudGui::slotTrayMessageIfServerUnsupported(Account *account)
{
if (account->serverVersionUnsupported()) {
slotShowTrayMessage(
- tr("Unsupported Server Version"),
- tr("The server on account %1 runs an old and unsupported version %2. "
- "Using this client with unsupported server versions is untested and "
- "potentially dangerous. Proceed at your own risk.")
- .arg(account->displayName(), account->serverVersion()));
+ tr("Unsupported Server Version"),
+ tr("The server on account %1 runs an old and unsupported version %2. "
+ "Using this client with unsupported server versions is untested and "
+ "potentially dangerous. Proceed at your own risk.")
+ .arg(account->displayName(), account->serverVersion()));
}
}
problemAccounts.append(a);
}
}
- foreach (Folder* f, FolderMan::instance()->map()) {
+ foreach (Folder *f, FolderMan::instance()->map()) {
if (!f->syncPaused()) {
allPaused = false;
}
foreach (AccountStatePtr a, problemAccounts) {
accountNames.append(a->account()->displayName());
}
- _tray->setToolTip(tr("Disconnected from %1").arg(
- accountNames.join(QLatin1String(", "))));
+ _tray->setToolTip(tr("Disconnected from %1").arg(accountNames.join(QLatin1String(", "))));
#else
QStringList messages;
messages.append(tr("Disconnected from accounts:"));
foreach (AccountStatePtr a, problemAccounts) {
- QString message = tr("Account %1: %2").arg(
- a->account()->displayName(), a->stateString(a->state()));
- if (! a->connectionErrors().empty()) {
+ QString message = tr("Account %1: %2").arg(a->account()->displayName(), a->stateString(a->state()));
+ if (!a->connectionErrors().empty()) {
message += QLatin1String("\n");
message += a->connectionErrors().join(QLatin1String("\n"));
}
SyncResult overallResult = FolderMan::accountStatus(map.values());
// create the tray blob message, check if we have an defined state
- if( overallResult.status() != SyncResult::Undefined ) {
- if( map.count() > 0 ) {
+ if (overallResult.status() != SyncResult::Undefined) {
+ if (map.count() > 0) {
#ifdef Q_OS_WIN
// Windows has a 128-char tray tooltip length limit.
trayMessage = folderMan->statusToString(overallResult.status(), false);
#else
QStringList allStatusStrings;
- foreach(Folder* folder, map.values()) {
+ foreach (Folder *folder, map.values()) {
QString folderMessage = folderMan->statusToString(folder->syncResult().status(), folder->syncPaused());
allStatusStrings += tr("Folder %1: %2").arg(folder->shortGuiLocalPath(), folderMessage);
}
trayMessage = tr("No sync folders configured.");
}
- QIcon statusIcon = Theme::instance()->syncStateIcon( overallResult.status(), true, contextMenuVisible());
- _tray->setIcon( statusIcon );
+ QIcon statusIcon = Theme::instance()->syncStateIcon(overallResult.status(), true, contextMenuVisible());
+ _tray->setIcon(statusIcon);
_tray->setToolTip(trayMessage);
} else {
// undefined because there are no folders.
QIcon icon = Theme::instance()->syncStateIcon(SyncResult::Problem, true, contextMenuVisible());
- _tray->setIcon( icon );
+ _tray->setIcon(icon);
_tray->setToolTip(tr("There are no sync folders configured."));
}
}
bool singleSyncFolder = folderMan->map().size() == 1 && Theme::instance()->singleSyncFolder();
bool onePaused = false;
bool allPaused = true;
- foreach (Folder* folder, folderMan->map()) {
+ foreach (Folder *folder, folderMan->map()) {
if (folder->accountState() != accountState.data()) {
continue;
}
menu->addAction(tr("Managed Folders:"))->setDisabled(true);
}
- QAction *action = new QAction( tr("Open folder '%1'").arg(folder->shortGuiLocalPath()), menu );
- connect(action, SIGNAL(triggered()),_folderOpenActionMapper, SLOT(map()));
- _folderOpenActionMapper->setMapping( action, folder->alias() );
+ QAction *action = new QAction(tr("Open folder '%1'").arg(folder->shortGuiLocalPath()), menu);
+ connect(action, SIGNAL(triggered()), _folderOpenActionMapper, SLOT(map()));
+ _folderOpenActionMapper->setMapping(action, folder->alias());
menu->addAction(action);
}
- menu->addSeparator();
- if (separateMenu) {
- if (onePaused) {
- QAction* enable = menu->addAction(tr("Unpause all folders"));
- enable->setProperty(propertyAccountC, QVariant::fromValue(accountState));
- connect(enable, SIGNAL(triggered(bool)), SLOT(slotUnpauseAllFolders()));
- }
- if (!allPaused) {
- QAction* enable = menu->addAction(tr("Pause all folders"));
- enable->setProperty(propertyAccountC, QVariant::fromValue(accountState));
- connect(enable, SIGNAL(triggered(bool)), SLOT(slotPauseAllFolders()));
- }
-
- if (accountState->isSignedOut()) {
- QAction* signin = menu->addAction(tr("Log in..."));
- signin->setProperty(propertyAccountC, QVariant::fromValue(accountState));
- connect(signin, SIGNAL(triggered()), this, SLOT(slotLogin()));
- } else {
- QAction* signout = menu->addAction(tr("Log out"));
- signout->setProperty(propertyAccountC, QVariant::fromValue(accountState));
- connect(signout, SIGNAL(triggered()), this, SLOT(slotLogout()));
- }
- }
+ menu->addSeparator();
+ if (separateMenu) {
+ if (onePaused) {
+ QAction *enable = menu->addAction(tr("Unpause all folders"));
+ enable->setProperty(propertyAccountC, QVariant::fromValue(accountState));
+ connect(enable, SIGNAL(triggered(bool)), SLOT(slotUnpauseAllFolders()));
+ }
+ if (!allPaused) {
+ QAction *enable = menu->addAction(tr("Pause all folders"));
+ enable->setProperty(propertyAccountC, QVariant::fromValue(accountState));
+ connect(enable, SIGNAL(triggered(bool)), SLOT(slotPauseAllFolders()));
+ }
+ if (accountState->isSignedOut()) {
+ QAction *signin = menu->addAction(tr("Log in..."));
+ signin->setProperty(propertyAccountC, QVariant::fromValue(accountState));
+ connect(signin, SIGNAL(triggered()), this, SLOT(slotLogin()));
+ } else {
+ QAction *signout = menu->addAction(tr("Log out"));
+ signout->setProperty(propertyAccountC, QVariant::fromValue(accountState));
+ connect(signout, SIGNAL(triggered()), this, SLOT(slotLogout()));
+ }
+ }
}
void ownCloudGui::slotContextMenuAboutToShow()
}
_contextMenu.reset(new QMenu());
- _contextMenu->setTitle(Theme::instance()->appNameGUI() );
+ _contextMenu->setTitle(Theme::instance()->appNameGUI());
_recentActionsMenu = new QMenu(tr("Recent Changes"), _contextMenu.data());
return;
}
- // Enables workarounds for bugs introduced in Qt 5.5.0
- // In particular QTBUG-47863 #3672 (tray menu fails to update and
- // becomes unresponsive) and QTBUG-48068 #3722 (click signal is
- // emitted several times)
- // The Qt version check intentionally uses 5.0.0 (where platformMenu()
- // was introduced) instead of 5.5.0 to avoid issues where the Qt
- // version used to build is different from the one used at runtime.
- // If we build with 5.6.1 or newer, we can skip this because the
- // bugs should be fixed there.
+// Enables workarounds for bugs introduced in Qt 5.5.0
+// In particular QTBUG-47863 #3672 (tray menu fails to update and
+// becomes unresponsive) and QTBUG-48068 #3722 (click signal is
+// emitted several times)
+// The Qt version check intentionally uses 5.0.0 (where platformMenu()
+// was introduced) instead of 5.5.0 to avoid issues where the Qt
+// version used to build is different from the one used at runtime.
+// If we build with 5.6.1 or newer, we can skip this because the
+// bugs should be fixed there.
#ifdef Q_OS_LINUX
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) && (QT_VERSION < QT_VERSION_CHECK(5, 6, 0))
if (qVersion() == QByteArray("5.5.0")) {
- QObject* platformMenu = reinterpret_cast<QObject*>(_tray->contextMenu()->platformMenu());
+ QObject *platformMenu = reinterpret_cast<QObject *>(_tray->contextMenu()->platformMenu());
if (platformMenu
- && platformMenu->metaObject()->className() == QLatin1String("QDBusPlatformMenu")) {
+ && platformMenu->metaObject()->className() == QLatin1String("QDBusPlatformMenu")) {
_qdbusmenuWorkaround = true;
qCWarning(lcApplication) << "Enabled QDBusPlatformMenu workaround";
}
_workaroundBatchTrayUpdate.setInterval(30 * 1000);
_workaroundBatchTrayUpdate.setSingleShot(true);
} else {
- // Update the context menu whenever we're about to show it
- // to the user.
+// Update the context menu whenever we're about to show it
+// to the user.
#ifdef Q_OS_MAC
// https://bugreports.qt.io/browse/QTBUG-54633
connect(_contextMenu.data(), SIGNAL(aboutToShow()), SLOT(slotContextMenuAboutToShow()));
slotRebuildRecentMenus();
// We must call deleteLater because we might be called from the press in one of the actions.
- foreach (auto menu, _accountMenus) { menu->deleteLater(); }
+ foreach (auto menu, _accountMenus) {
+ menu->deleteLater();
+ }
_accountMenus.clear();
if (accountList.count() > 1) {
foreach (AccountStatePtr account, accountList) {
- QMenu* accountMenu = new QMenu(account->account()->displayName(), _contextMenu.data());
+ QMenu *accountMenu = new QMenu(account->account()->displayName(), _contextMenu.data());
_accountMenus.append(accountMenu);
_contextMenu->addMenu(accountMenu);
_contextMenu->addAction(_actionHelp);
}
- if(_actionCrash) {
+ if (_actionCrash) {
_contextMenu->addAction(_actionCrash);
}
} else {
text = tr("Unpause synchronization");
}
- QAction* action = _contextMenu->addAction(text);
+ QAction *action = _contextMenu->addAction(text);
connect(action, SIGNAL(triggered(bool)), SLOT(slotUnpauseAllFolders()));
}
if (atLeastOneNotPaused) {
} else {
text = tr("Pause synchronization");
}
- QAction* action = _contextMenu->addAction(text);
+ QAction *action = _contextMenu->addAction(text);
connect(action, SIGNAL(triggered(bool)), SLOT(slotPauseAllFolders()));
}
if (atLeastOneSignedIn) {
void ownCloudGui::slotShowTrayMessage(const QString &title, const QString &msg)
{
- if( _tray )
+ if (_tray)
_tray->showMessage(title, msg);
else
qCWarning(lcApplication) << "Tray not ready: " << msg;
/*
* open the folder with the given Alias
*/
-void ownCloudGui::slotFolderOpenAction( const QString& alias )
+void ownCloudGui::slotFolderOpenAction(const QString &alias)
{
Folder *f = FolderMan::instance()->folder(alias);
- if( f ) {
+ if (f) {
qCInfo(lcApplication) << "opening local url " << f->path();
QUrl url = QUrl::fromLocalFile(f->path());
void ownCloudGui::setupActions()
{
_actionStatus = new QAction(tr("Unknown status"), this);
- _actionStatus->setEnabled( false );
+ _actionStatus->setEnabled(false);
_actionSettings = new QAction(tr("Settings..."), this);
_actionNewAccountWizard = new QAction(tr("New account..."), this);
_actionRecent = new QAction(tr("Details..."), this);
- _actionRecent->setEnabled( true );
+ _actionRecent->setEnabled(true);
QObject::connect(_actionRecent, SIGNAL(triggered(bool)), SLOT(slotShowSyncProtocol()));
QObject::connect(_actionSettings, SIGNAL(triggered(bool)), SLOT(slotShowSettings()));
_actionLogout = new QAction(tr("Log out"), this);
connect(_actionLogout, SIGNAL(triggered()), this, SLOT(slotLogout()));
- if(_app->debugMode()) {
+ if (_app->debugMode()) {
_actionCrash = new QAction(tr("Crash now", "Only shows in debug mode to allow testing the crash handler"), this);
connect(_actionCrash, SIGNAL(triggered()), _app, SLOT(slotCrash()));
} else {
_actionCrash = 0;
}
-
}
void ownCloudGui::slotRebuildRecentMenus()
{
_recentActionsMenu->clear();
if (!_recentItemsActions.isEmpty()) {
- foreach(QAction *a, _recentItemsActions) {
+ foreach (QAction *a, _recentItemsActions) {
_recentActionsMenu->addAction(a);
}
_recentActionsMenu->addSeparator();
/// Returns true if the completion of a given item should show up in the
/// 'Recent Activity' menu
-static bool shouldShowInRecentsMenu(const SyncFileItem& item)
+static bool shouldShowInRecentsMenu(const SyncFileItem &item)
{
- return
- !Progress::isIgnoredKind(item._status)
- && item._instruction != CSYNC_INSTRUCTION_EVAL
- && item._instruction != CSYNC_INSTRUCTION_NONE;
+ return !Progress::isIgnoredKind(item._status)
+ && item._instruction != CSYNC_INSTRUCTION_EVAL
+ && item._instruction != CSYNC_INSTRUCTION_NONE;
}
-void ownCloudGui::slotUpdateProgress(const QString &folder, const ProgressInfo& progress)
+void ownCloudGui::slotUpdateProgress(const QString &folder, const ProgressInfo &progress)
{
Q_UNUSED(folder);
if (!progress._currentDiscoveredFolder.isEmpty()) {
- _actionStatus->setText( tr("Checking for changes in '%1'")
- .arg( progress._currentDiscoveredFolder ));
- } else if (progress.totalSize() == 0 ) {
+ _actionStatus->setText(tr("Checking for changes in '%1'")
+ .arg(progress._currentDiscoveredFolder));
+ } else if (progress.totalSize() == 0) {
quint64 currentFile = progress.currentFile();
quint64 totalFileCount = qMax(progress.totalFiles(), currentFile);
QString msg;
if (progress.trustEta()) {
msg = tr("Syncing %1 of %2 (%3 left)")
- .arg( currentFile ).arg( totalFileCount )
- .arg( Utility::durationToDescriptiveString2(progress.totalProgress().estimatedEta) );
+ .arg(currentFile)
+ .arg(totalFileCount)
+ .arg(Utility::durationToDescriptiveString2(progress.totalProgress().estimatedEta));
} else {
msg = tr("Syncing %1 of %2")
- .arg( currentFile ).arg( totalFileCount );
+ .arg(currentFile)
+ .arg(totalFileCount);
}
- _actionStatus->setText( msg );
+ _actionStatus->setText(msg);
} else {
- QString totalSizeStr = Utility::octetsToString( progress.totalSize() );
+ QString totalSizeStr = Utility::octetsToString(progress.totalSize());
QString msg;
if (progress.trustEta()) {
msg = tr("Syncing %1 (%2 left)")
- .arg( totalSizeStr, Utility::durationToDescriptiveString2(progress.totalProgress().estimatedEta) );
+ .arg(totalSizeStr, Utility::durationToDescriptiveString2(progress.totalProgress().estimatedEta));
} else {
msg = tr("Syncing %1")
- .arg( totalSizeStr );
+ .arg(totalSizeStr);
}
- _actionStatus->setText( msg );
+ _actionStatus->setText(msg);
}
- _actionRecent->setIcon( QIcon() ); // Fixme: Set a "in-progress"-item eventually.
+ _actionRecent->setIcon(QIcon()); // Fixme: Set a "in-progress"-item eventually.
if (!progress._lastCompletedItem.isEmpty()
- && shouldShowInRecentsMenu(progress._lastCompletedItem)) {
-
+ && shouldShowInRecentsMenu(progress._lastCompletedItem)) {
if (Progress::isWarningKind(progress._lastCompletedItem._status)) {
// display a warn icon if warnings happened.
QIcon warnIcon(":/client/resources/warning");
}
if (progress.isUpdatingEstimates()
- && progress.completedFiles() >= progress.totalFiles()
- && progress._currentDiscoveredFolder.isEmpty()) {
+ && progress.completedFiles() >= progress.totalFiles()
+ && progress._currentDiscoveredFolder.isEmpty()) {
QTimer::singleShot(2000, this, SLOT(slotDisplayIdle()));
}
}
void ownCloudGui::setPauseOnAllFoldersHelper(bool pause)
{
- QList<AccountState*> accounts;
+ QList<AccountState *> accounts;
if (auto account = qvariant_cast<AccountStatePtr>(sender()->property(propertyAccountC))) {
accounts.append(account.data());
} else {
accounts.append(a.data());
}
}
- foreach (Folder* f, FolderMan::instance()->map()) {
+ foreach (Folder *f, FolderMan::instance()->map()) {
if (accounts.contains(f->accountState())) {
f->setSyncPaused(pause);
if (pause) {
if (_settingsDialog.isNull()) {
_settingsDialog =
#if defined(Q_OS_MAC)
- new SettingsDialogMac(this);
+ new SettingsDialogMac(this);
#else
- new SettingsDialog(this);
+ new SettingsDialog(this);
#endif
- _settingsDialog->setAttribute( Qt::WA_DeleteOnClose, true );
+ _settingsDialog->setAttribute(Qt::WA_DeleteOnClose, true);
_settingsDialog->show();
}
raiseDialog(_settingsDialog.data());
// that saving the geometries happens ASAP during a OS shutdown
// those do delete on close
- if (!_settingsDialog.isNull()) _settingsDialog->close();
- if (!_logBrowser.isNull()) _logBrowser->deleteLater();
+ if (!_settingsDialog.isNull())
+ _settingsDialog->close();
+ if (!_logBrowser.isNull())
+ _logBrowser->deleteLater();
}
void ownCloudGui::slotToggleLogBrowser()
// ## TODO: allow new log name maybe?
}
- if (_logBrowser->isVisible() ) {
+ if (_logBrowser->isVisible()) {
_logBrowser->hide();
} else {
raiseDialog(_logBrowser);
QDesktopServices::openUrl(QUrl(Theme::instance()->helpUrl()));
}
-void ownCloudGui::raiseDialog( QWidget *raiseWidget )
+void ownCloudGui::raiseDialog(QWidget *raiseWidget)
{
- if( raiseWidget && raiseWidget->parentWidget() == 0) {
+ if (raiseWidget && raiseWidget->parentWidget() == 0) {
// Qt has a bug which causes parent-less dialogs to pop-under.
raiseWidget->showNormal();
raiseWidget->raise();
e.xclient.data.l[4] = 0l;
Display *display = QX11Info::display();
XSendEvent(display,
- RootWindow(display, DefaultScreen(display)),
- False, // propagate
- SubstructureRedirectMask|SubstructureNotifyMask,
- &e);
+ RootWindow(display, DefaultScreen(display)),
+ False, // propagate
+ SubstructureRedirectMask | SubstructureNotifyMask,
+ &e);
#endif
}
}
// The correct value will be found with a propfind from ShareDialog.
// (we want to show the dialog directly, not wait for the propfind first)
SharePermissions maxSharingPermissions =
- SharePermissionRead
- | SharePermissionUpdate | SharePermissionCreate | SharePermissionDelete
- | SharePermissionShare;
+ SharePermissionRead
+ | SharePermissionUpdate | SharePermissionCreate | SharePermissionDelete
+ | SharePermissionShare;
if (!resharingAllowed) {
maxSharingPermissions = 0;
}
} else {
qCInfo(lcApplication) << "Opening share dialog" << sharePath << localPath << maxSharingPermissions;
w = new ShareDialog(accountState, sharePath, localPath, maxSharingPermissions);
- w->setAttribute( Qt::WA_DeleteOnClose, true );
+ w->setAttribute(Qt::WA_DeleteOnClose, true);
_shareDialogs[localPath] = w;
- connect(w, SIGNAL(destroyed(QObject*)), SLOT(slotRemoveDestroyedShareDialogs()));
+ connect(w, SIGNAL(destroyed(QObject *)), SLOT(slotRemoveDestroyedShareDialogs()));
}
raiseDialog(w);
}
void ownCloudGui::slotRemoveDestroyedShareDialogs()
{
- QMutableMapIterator<QString, QPointer<ShareDialog> > it(_shareDialogs);
+ QMutableMapIterator<QString, QPointer<ShareDialog>> it(_shareDialogs);
while (it.hasNext()) {
it.next();
- if (! it.value() || it.value() == sender()) {
+ if (!it.value() || it.value() == sender()) {
it.remove();
}
}
void slotComputeOverallSyncStatus();
void slotShowTrayMessage(const QString &title, const QString &msg);
void slotShowOptionalTrayMessage(const QString &title, const QString &msg);
- void slotFolderOpenAction( const QString& alias );
+ void slotFolderOpenAction(const QString &alias);
void slotRebuildRecentMenus();
- void slotUpdateProgress(const QString &folder, const ProgressInfo& progress);
+ void slotUpdateProgress(const QString &folder, const ProgressInfo &progress);
void slotShowGuiMessage(const QString &title, const QString &message);
void slotFoldersChanged();
void slotShowSettings();
void slotShowSyncProtocol();
void slotShutdown();
- void slotSyncStateChange(Folder*);
- void slotTrayClicked( QSystemTrayIcon::ActivationReason reason );
+ void slotSyncStateChange(Folder *);
+ void slotTrayClicked(QSystemTrayIcon::ActivationReason reason);
void slotToggleLogBrowser();
void slotOpenOwnCloud();
void slotOpenSettingsDialog();
void slotHelp();
- void slotOpenPath(const QString& path);
+ void slotOpenPath(const QString &path);
void slotAccountStateChanged();
void slotTrayMessageIfServerUnsupported(Account *account);
void slotShowShareDialog(const QString &sharePath, const QString &localPath, bool resharingAllowed);
private:
void setPauseOnAllFoldersHelper(bool pause);
void setupActions();
- void addAccountContextMenu(AccountStatePtr accountState, QMenu* menu, bool separateMenu);
+ void addAccountContextMenu(AccountStatePtr accountState, QMenu *menu, bool separateMenu);
QPointer<Systray> _tray;
#if defined(Q_OS_MAC)
#else
QPointer<SettingsDialog> _settingsDialog;
#endif
- QPointer<LogBrowser>_logBrowser;
- // tray's menu
+ QPointer<LogBrowser> _logBrowser;
+ // tray's menu
QScopedPointer<QMenu> _contextMenu;
// Manually tracking whether the context menu is visible, but only works
bool _contextMenuVisibleOsx;
QMenu *_recentActionsMenu;
- QVector<QMenu*> _accountMenus;
+ QVector<QMenu *> _accountMenus;
bool _qdbusmenuWorkaround;
QTimer _workaroundBatchTrayUpdate;
- QMap<QString, QPointer<ShareDialog> > _shareDialogs;
+ QMap<QString, QPointer<ShareDialog>> _shareDialogs;
QAction *_actionLogin;
QAction *_actionLogout;
QAction *_actionQuit;
QAction *_actionCrash;
- QList<QAction*> _recentItemsActions;
+ QList<QAction *> _recentItemsActions;
QSignalMapper *_folderOpenActionMapper;
QSignalMapper *_recentItemsMapper;
namespace OCC {
-OwncloudSetupWizard::OwncloudSetupWizard(QObject* parent) :
- QObject( parent ),
- _ocWizard(new OwncloudWizard),
- _remoteFolder()
+OwncloudSetupWizard::OwncloudSetupWizard(QObject *parent)
+ : QObject(parent)
+ , _ocWizard(new OwncloudWizard)
+ , _remoteFolder()
{
- connect( _ocWizard, SIGNAL(determineAuthType(const QString&)),
- this, SLOT(slotDetermineAuthType(const QString&)));
- connect( _ocWizard, SIGNAL(connectToOCUrl( const QString& ) ),
- this, SLOT(slotConnectToOCUrl( const QString& )));
- connect( _ocWizard, SIGNAL(createLocalAndRemoteFolders(QString, QString)),
- this, SLOT(slotCreateLocalAndRemoteFolders(QString, QString)));
+ connect(_ocWizard, SIGNAL(determineAuthType(const QString &)),
+ this, SLOT(slotDetermineAuthType(const QString &)));
+ connect(_ocWizard, SIGNAL(connectToOCUrl(const QString &)),
+ this, SLOT(slotConnectToOCUrl(const QString &)));
+ connect(_ocWizard, SIGNAL(createLocalAndRemoteFolders(QString, QString)),
+ this, SLOT(slotCreateLocalAndRemoteFolders(QString, QString)));
/* basicSetupFinished might be called from a reply from the network.
slotAssistantFinished might destroy the temporary QNetworkAccessManager.
Therefore Qt::QueuedConnection is required */
- connect( _ocWizard, SIGNAL(basicSetupFinished(int)),
- this, SLOT(slotAssistantFinished(int)), Qt::QueuedConnection);
- connect( _ocWizard, SIGNAL(finished(int)), SLOT(deleteLater()));
- connect( _ocWizard, SIGNAL(skipFolderConfiguration()), SLOT(slotSkipFolderConfiguration()));
+ connect(_ocWizard, SIGNAL(basicSetupFinished(int)),
+ this, SLOT(slotAssistantFinished(int)), Qt::QueuedConnection);
+ connect(_ocWizard, SIGNAL(finished(int)), SLOT(deleteLater()));
+ connect(_ocWizard, SIGNAL(skipFolderConfiguration()), SLOT(slotSkipFolderConfiguration()));
}
OwncloudSetupWizard::~OwncloudSetupWizard()
static QPointer<OwncloudSetupWizard> wiz = 0;
-void OwncloudSetupWizard::runWizard(QObject* obj, const char* amember, QWidget *parent)
+void OwncloudSetupWizard::runWizard(QObject *obj, const char *amember, QWidget *parent)
{
if (!wiz.isNull()) {
return;
}
wiz = new OwncloudSetupWizard(parent);
- connect( wiz, SIGNAL(ownCloudWizardDone(int)), obj, amember);
+ connect(wiz, SIGNAL(ownCloudWizardDone(int)), obj, amember);
FolderMan::instance()->setSyncEnabled(false);
wiz->startWizard();
}
// if its a relative path, prepend with users home dir, otherwise use as absolute path
- if( !QDir(localFolder).isAbsolute() ) {
+ if (!QDir(localFolder).isAbsolute()) {
localFolder = QDir::homePath() + QDir::separator() + localFolder;
}
// remember the local folder to compare later if it changed, but clean first
QString lf = QDir::fromNativeSeparators(localFolder);
- if( !lf.endsWith(QLatin1Char('/'))) {
+ if (!lf.endsWith(QLatin1Char('/'))) {
lf.append(QLatin1Char('/'));
}
if (ClientProxy::isUsingSystemDefault()) {
qCDebug(lcWizard) << "Trying to look up system proxy";
ClientProxy::lookupSystemProxyAsync(account->url(),
- this, SLOT(slotSystemProxyLookupDone(QNetworkProxy)));
+ this, SLOT(slotSystemProxyLookupDone(QNetworkProxy)));
} else {
// We want to reset the QNAM proxy so that the global proxy settings are used (via ClientProxy settings)
account->networkAccessManager()->setProxy(QNetworkProxy(QNetworkProxy::DefaultProxy));
account->setCredentials(CredentialsFactory::create("dummy"));
CheckServerJob *job = new CheckServerJob(_ocWizard->account(), this);
job->setIgnoreCredentialFailure(true);
- connect(job, SIGNAL(instanceFound(QUrl,QJsonObject)), SLOT(slotOwnCloudFoundAuth(QUrl,QJsonObject)));
- connect(job, SIGNAL(instanceNotFound(QNetworkReply*)), SLOT(slotNoOwnCloudFoundAuth(QNetworkReply*)));
- connect(job, SIGNAL(timeout(const QUrl&)), SLOT(slotNoOwnCloudFoundAuthTimeout(const QUrl&)));
- job->setTimeout((account->url().scheme() == "https") ? 30*1000 : 10*1000);
+ connect(job, SIGNAL(instanceFound(QUrl, QJsonObject)), SLOT(slotOwnCloudFoundAuth(QUrl, QJsonObject)));
+ connect(job, SIGNAL(instanceNotFound(QNetworkReply *)), SLOT(slotNoOwnCloudFoundAuth(QNetworkReply *)));
+ connect(job, SIGNAL(timeout(const QUrl &)), SLOT(slotNoOwnCloudFoundAuthTimeout(const QUrl &)));
+ job->setTimeout((account->url().scheme() == "https") ? 30 * 1000 : 10 * 1000);
job->start();
}
-void OwncloudSetupWizard::slotOwnCloudFoundAuth(const QUrl& url, const QJsonObject &info)
+void OwncloudSetupWizard::slotOwnCloudFoundAuth(const QUrl &url, const QJsonObject &info)
{
auto serverVersion = CheckServerJob::version(info);
_ocWizard->appendToConfigurationLog(tr("<font color=\"green\">Successfully connected to %1: %2 version %3 (%4)</font><br/><br/>")
- .arg(Utility::escape(url.toString()),
- Utility::escape(Theme::instance()->appNameGUI()),
- Utility::escape(CheckServerJob::versionString(info)),
- Utility::escape(serverVersion)));
+ .arg(Utility::escape(url.toString()),
+ Utility::escape(Theme::instance()->appNameGUI()),
+ Utility::escape(CheckServerJob::versionString(info)),
+ Utility::escape(serverVersion)));
// Note with newer servers we get the version actually only later in capabilities
// https://github.com/owncloud/core/pull/27473/files
DetermineAuthTypeJob *job = new DetermineAuthTypeJob(_ocWizard->account(), this);
job->setIgnoreCredentialFailure(true);
connect(job, SIGNAL(authType(WizardCommon::AuthType)),
- _ocWizard, SLOT(setAuthType(WizardCommon::AuthType)));
+ _ocWizard, SLOT(setAuthType(WizardCommon::AuthType)));
job->start();
}
} else {
msg = tr("Failed to connect to %1 at %2:<br/>%3")
.arg(Utility::escape(Theme::instance()->appNameGUI()),
- Utility::escape(reply->url().toString()),
- Utility::escape(job->errorString()));
+ Utility::escape(reply->url().toString()),
+ Utility::escape(job->errorString()));
}
bool isDowngradeAdvised = checkDowngradeAdvised(reply);
if (resultCode != 200 && contentType.startsWith("text/")) {
// 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);
+ QString serverError = reply->peek(1024 * 20);
qCDebug(lcWizard) << serverError;
QMessageBox messageBox(_ocWizard);
messageBox.setText(serverError);
_ocWizard->account()->resetRejectedCertificates();
}
-void OwncloudSetupWizard::slotNoOwnCloudFoundAuthTimeout(const QUrl&url)
+void OwncloudSetupWizard::slotNoOwnCloudFoundAuthTimeout(const QUrl &url)
{
_ocWizard->displayError(
tr("Timeout while trying to connect to %1 at %2.")
false);
}
-void OwncloudSetupWizard::slotConnectToOCUrl( const QString& url )
+void OwncloudSetupWizard::slotConnectToOCUrl(const QString &url)
{
qCInfo(lcWizard) << "Connect to url: " << url;
AbstractCredentials *creds = _ocWizard->getCredentials();
_ocWizard->account()->setCredentials(creds);
- _ocWizard->setField(QLatin1String("OCUrl"), url );
+ _ocWizard->setField(QLatin1String("OCUrl"), url);
_ocWizard->appendToConfigurationLog(tr("Trying to connect to %1 at %2...")
- .arg( Theme::instance()->appNameGUI() ).arg(url) );
+ .arg(Theme::instance()->appNameGUI())
+ .arg(url));
testOwnCloudConnect();
}
{
QString errorMsg;
- PropfindJob* job = qobject_cast<PropfindJob*>(sender());
+ PropfindJob *job = qobject_cast<PropfindJob *>(sender());
if (!job) {
qCWarning(lcWizard) << "Can't check for authed redirects. This slot should be invoked from PropfindJob!";
return;
}
- QNetworkReply* reply = job->reply();
+ QNetworkReply *reply = job->reply();
// If there were redirects on the *authed* requests, also store
// the updated server URL, similar to redirects on status.php.
"'%1'. The URL is bad, the server is misconfigured.")
.arg(Utility::escape(redirectUrl.toString()));
- // A 404 is actually a success: we were authorized to know that the folder does
- // not exist. It will be created later...
+ // A 404 is actually a success: we were authorized to know that the folder does
+ // not exist. It will be created later...
} else if (reply->error() == QNetworkReply::ContentNotFoundError) {
_ocWizard->successfulStep();
return;
- // Provide messages for other errors, such as invalid credentials.
+ // Provide messages for other errors, such as invalid credentials.
} else if (reply->error() != QNetworkReply::NoError) {
if (!_ocWizard->account()->credentials()->stillValid(reply)) {
errorMsg = tr("Access forbidden by server. To verify that you have proper access, "
errorMsg = job->errorStringParsingBody();
}
- // Something else went wrong, maybe the response was 200 but with invalid data.
+ // Something else went wrong, maybe the response was 200 but with invalid data.
} else {
errorMsg = tr("There was an invalid response to an authenticated webdav request");
}
_ocWizard->displayError(errorMsg, _ocWizard->currentId() == WizardCommon::Page_ServerSetup && checkDowngradeAdvised(reply));
}
-bool OwncloudSetupWizard::checkDowngradeAdvised(QNetworkReply* reply)
+bool OwncloudSetupWizard::checkDowngradeAdvised(QNetworkReply *reply)
{
- if(reply->url().scheme() != QLatin1String("https")) {
+ if (reply->url().scheme() != QLatin1String("https")) {
return false;
}
return true;
}
-void OwncloudSetupWizard::slotCreateLocalAndRemoteFolders(const QString& localFolder, const QString& remoteFolder)
+void OwncloudSetupWizard::slotCreateLocalAndRemoteFolders(const QString &localFolder, const QString &remoteFolder)
{
qCInfo(lcWizard) << "Setup local sync folder for new oC connection " << localFolder;
- const QDir fi( localFolder );
+ const QDir fi(localFolder);
bool nextStep = true;
- if( fi.exists() ) {
+ if (fi.exists()) {
FileSystem::setFolderMinimumPermissions(localFolder);
// there is an existing local folder. If its non empty, it can only be synced if the
// ownCloud is newly created.
.arg(Utility::escape(localFolder)));
} else {
QString res = tr("Creating local sync folder %1...").arg(localFolder);
- if( fi.mkpath( localFolder ) ) {
+ if (fi.mkpath(localFolder)) {
FileSystem::setFolderMinimumPermissions(localFolder);
- Utility::setupFavLink( localFolder );
+ Utility::setupFavLink(localFolder);
res += tr("ok");
} else {
res += tr("failed.");
_ocWizard->displayError(tr("Could not create local folder %1").arg(Utility::escape(localFolder)), false);
nextStep = false;
}
- _ocWizard->appendToConfigurationLog( res );
+ _ocWizard->appendToConfigurationLog(res);
}
if (nextStep) {
EntityExistsJob *job = new EntityExistsJob(_ocWizard->account(), _ocWizard->account()->davPath() + remoteFolder, this);
- connect(job, SIGNAL(exists(QNetworkReply*)), SLOT(slotRemoteFolderExists(QNetworkReply*)));
+ connect(job, SIGNAL(exists(QNetworkReply *)), SLOT(slotRemoteFolderExists(QNetworkReply *)));
job->start();
} else {
- finalizeSetup( false );
+ finalizeSetup(false);
}
}
QString error;
QNetworkReply::NetworkError errId = reply->error();
- if( errId == QNetworkReply::NoError ) {
+ if (errId == QNetworkReply::NoError) {
qCInfo(lcWizard) << "Remote folder found, all cool!";
- } else if( errId == QNetworkReply::ContentNotFoundError ) {
- if( _remoteFolder.isEmpty() ) {
+ } else if (errId == QNetworkReply::ContentNotFoundError) {
+ if (_remoteFolder.isEmpty()) {
error = tr("No remote folder specified!");
ok = false;
} else {
ok = false;
}
- if( !ok ) {
+ if (!ok) {
_ocWizard->displayError(Utility::escape(error), false);
}
- finalizeSetup( ok );
+ finalizeSetup(ok);
}
void OwncloudSetupWizard::createRemoteFolder()
{
- _ocWizard->appendToConfigurationLog( tr("creating folder on ownCloud: %1" ).arg( _remoteFolder ));
+ _ocWizard->appendToConfigurationLog(tr("creating folder on ownCloud: %1").arg(_remoteFolder));
MkColJob *job = new MkColJob(_ocWizard->account(), _remoteFolder, this);
connect(job, SIGNAL(finished(QNetworkReply::NetworkError)), SLOT(slotCreateRemoteFolderFinished(QNetworkReply::NetworkError)));
job->start();
}
-void OwncloudSetupWizard::slotCreateRemoteFolderFinished( QNetworkReply::NetworkError error )
+void OwncloudSetupWizard::slotCreateRemoteFolderFinished(QNetworkReply::NetworkError error)
{
qCDebug(lcWizard) << "** webdav mkdir request finished " << error;
// disconnect(ownCloudInfo::instance(), SIGNAL(webdavColCreated(QNetworkReply::NetworkError)),
bool success = true;
- if( error == QNetworkReply::NoError ) {
- _ocWizard->appendToConfigurationLog( tr("Remote folder %1 created successfully.").arg(_remoteFolder));
- } else if( error == 202 ) {
- _ocWizard->appendToConfigurationLog( tr("The remote folder %1 already exists. Connecting it for syncing.").arg(_remoteFolder));
- } else if( error > 202 && error < 300 ) {
- _ocWizard->displayError( tr("The folder creation resulted in HTTP error code %1").arg((int)error ), false);
-
- _ocWizard->appendToConfigurationLog( tr("The folder creation resulted in HTTP error code %1").arg((int)error) );
- } else if( error == QNetworkReply::OperationCanceledError ) {
- _ocWizard->displayError( tr("The remote folder creation failed because the provided credentials "
- "are wrong!"
- "<br/>Please go back and check your credentials.</p>"), false);
- _ocWizard->appendToConfigurationLog( tr("<p><font color=\"red\">Remote folder creation failed probably because the provided credentials are wrong.</font>"
- "<br/>Please go back and check your credentials.</p>"));
+ if (error == QNetworkReply::NoError) {
+ _ocWizard->appendToConfigurationLog(tr("Remote folder %1 created successfully.").arg(_remoteFolder));
+ } else if (error == 202) {
+ _ocWizard->appendToConfigurationLog(tr("The remote folder %1 already exists. Connecting it for syncing.").arg(_remoteFolder));
+ } else if (error > 202 && error < 300) {
+ _ocWizard->displayError(tr("The folder creation resulted in HTTP error code %1").arg((int)error), false);
+
+ _ocWizard->appendToConfigurationLog(tr("The folder creation resulted in HTTP error code %1").arg((int)error));
+ } else if (error == QNetworkReply::OperationCanceledError) {
+ _ocWizard->displayError(tr("The remote folder creation failed because the provided credentials "
+ "are wrong!"
+ "<br/>Please go back and check your credentials.</p>"),
+ false);
+ _ocWizard->appendToConfigurationLog(tr("<p><font color=\"red\">Remote folder creation failed probably because the provided credentials are wrong.</font>"
+ "<br/>Please go back and check your credentials.</p>"));
_remoteFolder.clear();
success = false;
} else {
- _ocWizard->appendToConfigurationLog( tr("Remote folder %1 creation failed with error <tt>%2</tt>.").arg(Utility::escape(_remoteFolder)).arg(error));
- _ocWizard->displayError( tr("Remote folder %1 creation failed with error <tt>%2</tt>.").arg(Utility::escape(_remoteFolder)).arg(error), false );
+ _ocWizard->appendToConfigurationLog(tr("Remote folder %1 creation failed with error <tt>%2</tt>.").arg(Utility::escape(_remoteFolder)).arg(error));
+ _ocWizard->displayError(tr("Remote folder %1 creation failed with error <tt>%2</tt>.").arg(Utility::escape(_remoteFolder)).arg(error), false);
_remoteFolder.clear();
success = false;
}
- finalizeSetup( success );
+ finalizeSetup(success);
}
-void OwncloudSetupWizard::finalizeSetup( bool success )
+void OwncloudSetupWizard::finalizeSetup(bool success)
{
// enable/disable the finish button.
_ocWizard->enableFinishOnResultWidget(success);
const QString localFolder = _ocWizard->property("localFolder").toString();
- if( success ) {
- if( !(localFolder.isEmpty() || _remoteFolder.isEmpty() )) {
+ if (success) {
+ if (!(localFolder.isEmpty() || _remoteFolder.isEmpty())) {
_ocWizard->appendToConfigurationLog(
tr("A sync connection from %1 to remote directory %2 was set up.")
.arg(localFolder, _remoteFolder));
}
- _ocWizard->appendToConfigurationLog( QLatin1String(" "));
- _ocWizard->appendToConfigurationLog( QLatin1String("<p><font color=\"green\"><b>")
- + tr("Successfully connected to %1!")
- .arg(Theme::instance()->appNameGUI())
- + QLatin1String("</b></font></p>"));
+ _ocWizard->appendToConfigurationLog(QLatin1String(" "));
+ _ocWizard->appendToConfigurationLog(QLatin1String("<p><font color=\"green\"><b>")
+ + tr("Successfully connected to %1!")
+ .arg(Theme::instance()->appNameGUI())
+ + QLatin1String("</b></font></p>"));
_ocWizard->successfulStep();
} else {
// ### this is not quite true, pass in the real problem as optional parameter
_ocWizard->appendToConfigurationLog(QLatin1String("<p><font color=\"red\">")
- + tr("Connection to %1 could not be established. Please check again.")
- .arg(Theme::instance()->appNameGUI())
- + QLatin1String("</font></p>"));
+ + tr("Connection to %1 could not be established. Please check again.")
+ .arg(Theme::instance()->appNameGUI())
+ + QLatin1String("</font></p>"));
}
}
-bool OwncloudSetupWizard::ensureStartFromScratch(const QString &localFolder) {
+bool OwncloudSetupWizard::ensureStartFromScratch(const QString &localFolder)
+{
// first try to rename (backup) the current local dir.
bool renameOk = false;
- while( !renameOk ) {
+ while (!renameOk) {
renameOk = FolderMan::instance()->startFromScratch(localFolder);
- if( ! renameOk ) {
+ if (!renameOk) {
QMessageBox::StandardButton but;
- but = QMessageBox::question( 0, tr("Folder rename failed"),
- tr("Can't remove and back up the folder because the folder or a file in it is open in another program."
- " Please close the folder or file and hit retry or cancel the setup."), QMessageBox::Retry | QMessageBox::Abort, QMessageBox::Retry);
- if( but == QMessageBox::Abort ) {
+ but = QMessageBox::question(0, tr("Folder rename failed"),
+ tr("Can't remove and back up the folder because the folder or a file in it is open in another program."
+ " Please close the folder or file and hit retry or cancel the setup."),
+ QMessageBox::Retry | QMessageBox::Abort, QMessageBox::Retry);
+ if (but == QMessageBox::Abort) {
break;
}
}
}
// Method executed when the user end has finished the basic setup.
-void OwncloudSetupWizard::slotAssistantFinished( int result )
+void OwncloudSetupWizard::slotAssistantFinished(int result)
{
FolderMan *folderMan = FolderMan::instance();
- if( result == QDialog::Rejected ) {
+ if (result == QDialog::Rejected) {
qCInfo(lcWizard) << "Rejected the new config, use the old!";
- } else if( result == QDialog::Accepted ) {
+ } else if (result == QDialog::Accepted) {
// This may or may not wipe all folder definitions, depending
// on whether a new account is activated or the existing one
// is changed.
auto f = folderMan->addFolder(account, folderDefinition);
if (f) {
f->journalDb()->setSelectiveSyncList(SyncJournalDb::SelectiveSyncBlackList,
- _ocWizard->selectiveSyncBlacklist());
+ _ocWizard->selectiveSyncBlacklist());
if (!_ocWizard->isConfirmBigFolderChecked()) {
// The user already accepted the selective sync dialog. everything is in the white list
f->journalDb()->setSelectiveSyncList(SyncJournalDb::SelectiveSyncWhiteList,
- QStringList() << QLatin1String("/"));
+ QStringList() << QLatin1String("/"));
}
}
_ocWizard->appendToConfigurationLog(tr("<font color=\"green\"><b>Local sync folder %1 successfully created!</b></font>").arg(localFolder));
}
// notify others.
- emit ownCloudWizardDone( result );
+ emit ownCloudWizardDone(result);
}
void OwncloudSetupWizard::slotSkipFolderConfiguration()
{
applyAccountChanges();
- disconnect( _ocWizard, SIGNAL(basicSetupFinished(int)),
- this, SLOT(slotAssistantFinished(int)) );
+ disconnect(_ocWizard, SIGNAL(basicSetupFinished(int)),
+ this, SLOT(slotAssistantFinished(int)));
_ocWizard->close();
- emit ownCloudWizardDone( QDialog::Accepted );
+ emit ownCloudWizardDone(QDialog::Accepted);
}
AccountState *OwncloudSetupWizard::applyAccountChanges()
* @brief The DetermineAuthTypeJob class
* @ingroup gui
*/
-class DetermineAuthTypeJob : public AbstractNetworkJob {
+class DetermineAuthTypeJob : public AbstractNetworkJob
+{
Q_OBJECT
public:
explicit DetermineAuthTypeJob(AccountPtr account, QObject *parent = 0);
void authType(WizardCommon::AuthType);
private slots:
bool finished() Q_DECL_OVERRIDE;
+
private:
int _redirects;
};
Q_OBJECT
public:
/** Run the wizard */
- static void runWizard(QObject *obj, const char* amember, QWidget *parent = 0 );
+ static void runWizard(QObject *obj, const char *amember, QWidget *parent = 0);
static bool bringWizardToFrontIfVisible();
signals:
// overall dialog close signal.
- void ownCloudWizardDone( int );
+ void ownCloudWizardDone(int);
private slots:
- void slotDetermineAuthType(const QString&);
+ void slotDetermineAuthType(const QString &);
void slotSystemProxyLookupDone(const QNetworkProxy &proxy);
void slotContinueDetermineAuth();
- void slotOwnCloudFoundAuth(const QUrl&, const QJsonObject&);
+ void slotOwnCloudFoundAuth(const QUrl &, const QJsonObject &);
void slotNoOwnCloudFoundAuth(QNetworkReply *reply);
- void slotNoOwnCloudFoundAuthTimeout(const QUrl&url);
+ void slotNoOwnCloudFoundAuthTimeout(const QUrl &url);
- void slotConnectToOCUrl(const QString&);
+ void slotConnectToOCUrl(const QString &);
void slotAuthError();
- void slotCreateLocalAndRemoteFolders(const QString&, const QString&);
- void slotRemoteFolderExists(QNetworkReply*);
+ void slotCreateLocalAndRemoteFolders(const QString &, const QString &);
+ void slotRemoteFolderExists(QNetworkReply *);
void slotCreateRemoteFolderFinished(QNetworkReply::NetworkError);
- void slotAssistantFinished( int );
+ void slotAssistantFinished(int);
void slotSkipFolderConfiguration();
private:
- explicit OwncloudSetupWizard(QObject *parent = 0 );
+ explicit OwncloudSetupWizard(QObject *parent = 0);
~OwncloudSetupWizard();
void startWizard();
void testOwnCloudConnect();
void createRemoteFolder();
- void finalizeSetup( bool );
+ void finalizeSetup(bool);
bool ensureStartFromScratch(const QString &localFolder);
AccountState *applyAccountChanges();
- bool checkDowngradeAdvised(QNetworkReply* reply);
+ bool checkDowngradeAdvised(QNetworkReply *reply);
- OwncloudWizard* _ocWizard;
+ OwncloudWizard *_ocWizard;
QString _initLocalFolder;
QString _remoteFolder;
};
-
}
#endif // OWNCLOUDSETUPWIZARD_H
namespace OCC {
-ProtocolWidget::ProtocolWidget(QWidget *parent) :
- QWidget(parent),
- IgnoredIndicatorRole( Qt::UserRole +1 ),
- _ui(new Ui::ProtocolWidget)
+ProtocolWidget::ProtocolWidget(QWidget *parent)
+ : QWidget(parent)
+ , IgnoredIndicatorRole(Qt::UserRole + 1)
+ , _ui(new Ui::ProtocolWidget)
{
_ui->setupUi(this);
- connect(ProgressDispatcher::instance(), SIGNAL(progressInfo(QString,ProgressInfo)),
- this, SLOT(slotProgressInfo(QString,ProgressInfo)));
- connect(ProgressDispatcher::instance(), SIGNAL(itemCompleted(QString,SyncFileItemPtr)),
- this, SLOT(slotItemCompleted(QString,SyncFileItemPtr)));
+ connect(ProgressDispatcher::instance(), SIGNAL(progressInfo(QString, ProgressInfo)),
+ this, SLOT(slotProgressInfo(QString, ProgressInfo)));
+ connect(ProgressDispatcher::instance(), SIGNAL(itemCompleted(QString, SyncFileItemPtr)),
+ this, SLOT(slotItemCompleted(QString, SyncFileItemPtr)));
- connect(_ui->_treeWidget, SIGNAL(itemActivated(QTreeWidgetItem*,int)), SLOT(slotOpenFile(QTreeWidgetItem*,int)));
+ connect(_ui->_treeWidget, SIGNAL(itemActivated(QTreeWidgetItem *, int)), SLOT(slotOpenFile(QTreeWidgetItem *, int)));
// Adjust copyToClipboard() when making changes here!
QStringList header;
timestampColumnExtra = 20; // font metrics are broken on Windows, see #4721
#endif
- _ui->_treeWidget->setHeaderLabels( header );
+ _ui->_treeWidget->setHeaderLabels(header);
int timestampColumnWidth =
_ui->_treeWidget->fontMetrics().width(timeString(QDateTime::currentDateTime()))
+ timestampColumnExtra;
_ui->_headerLabel->setText(tr("Local sync protocol"));
QPushButton *copyBtn = _ui->_dialogButtonBox->addButton(tr("Copy"), QDialogButtonBox::ActionRole);
- copyBtn->setToolTip( tr("Copy the activity list to the clipboard."));
+ copyBtn->setToolTip(tr("Copy the activity list to the clipboard."));
copyBtn->setEnabled(true);
connect(copyBtn, SIGNAL(clicked()), SIGNAL(copyToClipboard()));
// be embedded into another gui element.
_issueItemView = new QTreeWidget(this);
header.removeLast();
- _issueItemView->setHeaderLabels( header );
+ _issueItemView->setHeaderLabels(header);
timestampColumnWidth =
- ActivityItemDelegate::rowHeight() // icon
- + _issueItemView->fontMetrics().width(timeString(QDateTime::currentDateTime()))
- + timestampColumnExtra;
+ ActivityItemDelegate::rowHeight() // icon
+ + _issueItemView->fontMetrics().width(timeString(QDateTime::currentDateTime()))
+ + timestampColumnExtra;
_issueItemView->setColumnWidth(0, timestampColumnWidth);
_issueItemView->setColumnWidth(1, 180);
_issueItemView->setColumnCount(4);
_issueItemView->setRootIsDecorated(false);
_issueItemView->setTextElideMode(Qt::ElideMiddle);
_issueItemView->header()->setObjectName("ActivityErrorListHeader");
- connect(_issueItemView, SIGNAL(itemActivated(QTreeWidgetItem*,int)),
- SLOT(slotOpenFile(QTreeWidgetItem*,int)));
+ connect(_issueItemView, SIGNAL(itemActivated(QTreeWidgetItem *, int)),
+ SLOT(slotOpenFile(QTreeWidgetItem *, int)));
}
ProtocolWidget::~ProtocolWidget()
void ProtocolWidget::hideEvent(QHideEvent *ev)
{
ConfigFile cfg;
- cfg.saveGeometryHeader(_ui->_treeWidget->header() );
+ cfg.saveGeometryHeader(_ui->_treeWidget->header());
QWidget::hideEvent(ev);
}
-void ProtocolWidget::cleanItems(const QString& folder)
+void ProtocolWidget::cleanItems(const QString &folder)
{
// The issue list is a state, clear it and let the next sync fill it
// with ignored files and propagation errors.
int itemCnt = _issueItemView->topLevelItemCount();
- for( int cnt = itemCnt-1; cnt >=0 ; cnt-- ) {
+ for (int cnt = itemCnt - 1; cnt >= 0; cnt--) {
QTreeWidgetItem *item = _issueItemView->topLevelItem(cnt);
QString itemFolder = item->data(2, Qt::UserRole).toString();
- if( itemFolder == folder ) {
+ if (itemFolder == folder) {
delete item;
}
}
// update the tabtext
- emit( issueItemCountUpdated(_issueItemView->topLevelItemCount()) );
+ emit(issueItemCountUpdated(_issueItemView->topLevelItemCount()));
}
QString ProtocolWidget::timeString(QDateTime dt, QLocale::FormatType format) const
return loc.toString(dt, dtFormat);
}
-void ProtocolWidget::slotOpenFile( QTreeWidgetItem *item, int )
+void ProtocolWidget::slotOpenFile(QTreeWidgetItem *item, int)
{
QString folderName = item->data(2, Qt::UserRole).toString();
QString fileName = item->text(1);
}
}
-QTreeWidgetItem* ProtocolWidget::createCompletedTreewidgetItem(const QString& folder, const SyncFileItem& item)
+QTreeWidgetItem *ProtocolWidget::createCompletedTreewidgetItem(const QString &folder, const SyncFileItem &item)
{
auto f = FolderMan::instance()->folder(folder);
if (!f) {
QIcon icon;
if (item._status == SyncFileItem::NormalError
- || item._status == SyncFileItem::FatalError) {
+ || item._status == SyncFileItem::FatalError) {
icon = Theme::instance()->syncStateIcon(SyncResult::Error);
} else if (Progress::isWarningKind(item._status)) {
icon = Theme::instance()->syncStateIcon(SyncResult::Problem);
}
if (ProgressInfo::isSizeDependent(item)) {
- columns << Utility::octetsToString( item._size );
+ columns << Utility::octetsToString(item._size);
}
QTreeWidgetItem *twitem = new QTreeWidgetItem(columns);
twitem->setIcon(0, icon);
twitem->setToolTip(0, longTimeStr);
twitem->setToolTip(1, item._file);
- twitem->setToolTip(3, message );
- twitem->setData(2, Qt::UserRole, folder);
+ twitem->setToolTip(3, message);
+ twitem->setData(2, Qt::UserRole, folder);
return twitem;
}
-void ProtocolWidget::slotProgressInfo( const QString& folder, const ProgressInfo& progress )
+void ProtocolWidget::slotProgressInfo(const QString &folder, const ProgressInfo &progress)
{
- if( !progress.isUpdatingEstimates() ) {
+ if (!progress.isUpdatingEstimates()) {
// The sync is restarting, clean the old items
cleanItems(folder);
} else if (progress.completedFiles() >= progress.totalFiles()) {
void ProtocolWidget::slotItemCompleted(const QString &folder, const SyncFileItemPtr &item)
{
QTreeWidgetItem *line = createCompletedTreewidgetItem(folder, *item);
- if(line) {
- if( item->hasErrorStatus() ) {
+ if (line) {
+ if (item->hasErrorStatus()) {
_issueItemView->insertTopLevelItem(0, line);
emit issueItemCountUpdated(_issueItemView->topLevelItemCount());
} else {
// Limit the number of items
int itemCnt = _ui->_treeWidget->topLevelItemCount();
- while(itemCnt > 2000) {
+ while (itemCnt > 2000) {
delete _ui->_treeWidget->takeTopLevelItem(itemCnt - 1);
itemCnt--;
}
}
-void ProtocolWidget::storeSyncActivity(QTextStream& ts)
+void ProtocolWidget::storeSyncActivity(QTextStream &ts)
{
int topLevelItems = _ui->_treeWidget->topLevelItemCount();
for (int i = 0; i < topLevelItems; i++) {
QTreeWidgetItem *child = _ui->_treeWidget->topLevelItem(i);
ts << right
- // time stamp
+ // time stamp
<< qSetFieldWidth(20)
- << child->data(0,Qt::DisplayRole).toString()
- // separator
+ << child->data(0, Qt::DisplayRole).toString()
+ // separator
<< qSetFieldWidth(0) << ","
- // file name
+ // file name
<< qSetFieldWidth(64)
- << child->data(1,Qt::DisplayRole).toString()
- // separator
+ << child->data(1, Qt::DisplayRole).toString()
+ // separator
<< qSetFieldWidth(0) << ","
- // folder
+ // folder
<< qSetFieldWidth(30)
<< child->data(2, Qt::DisplayRole).toString()
- // separator
+ // separator
<< qSetFieldWidth(0) << ","
- // action
+ // action
<< qSetFieldWidth(15)
<< child->data(3, Qt::DisplayRole).toString()
- // separator
+ // separator
<< qSetFieldWidth(0) << ","
- // size
+ // size
<< qSetFieldWidth(10)
<< child->data(4, Qt::DisplayRole).toString()
<< qSetFieldWidth(0)
}
}
-void ProtocolWidget::storeSyncIssues(QTextStream& ts)
+void ProtocolWidget::storeSyncIssues(QTextStream &ts)
{
int topLevelItems = _issueItemView->topLevelItemCount();
for (int i = 0; i < topLevelItems; i++) {
QTreeWidgetItem *child = _issueItemView->topLevelItem(i);
ts << right
- // time stamp
+ // time stamp
<< qSetFieldWidth(20)
- << child->data(0,Qt::DisplayRole).toString()
- // separator
+ << child->data(0, Qt::DisplayRole).toString()
+ // separator
<< qSetFieldWidth(0) << ","
- // file name
+ // file name
<< qSetFieldWidth(64)
- << child->data(1,Qt::DisplayRole).toString()
- // separator
+ << child->data(1, Qt::DisplayRole).toString()
+ // separator
<< qSetFieldWidth(0) << ","
- // folder
+ // folder
<< qSetFieldWidth(30)
<< child->data(2, Qt::DisplayRole).toString()
- // separator
+ // separator
<< qSetFieldWidth(0) << ","
- // action
+ // action
<< qSetFieldWidth(15)
<< child->data(3, Qt::DisplayRole).toString()
<< qSetFieldWidth(0)
<< endl;
}
}
-
}
class SyncResult;
namespace Ui {
- class ProtocolWidget;
+ class ProtocolWidget;
}
class Application;
QSize sizeHint() const { return ownCloudGui::settingsDialogSize(); }
QTreeWidget *issueWidget() { return _issueItemView; }
- void storeSyncActivity(QTextStream& ts);
- void storeSyncIssues(QTextStream& ts);
+ void storeSyncActivity(QTextStream &ts);
+ void storeSyncIssues(QTextStream &ts);
public slots:
- void slotProgressInfo( const QString& folder, const ProgressInfo& progress );
- void slotItemCompleted( const QString& folder, const SyncFileItemPtr& item);
- void slotOpenFile( QTreeWidgetItem* item, int );
+ void slotProgressInfo(const QString &folder, const ProgressInfo &progress);
+ void slotItemCompleted(const QString &folder, const SyncFileItemPtr &item);
+ void slotOpenFile(QTreeWidgetItem *item, int);
protected:
void showEvent(QShowEvent *);
void issueItemCountUpdated(int);
private:
- void setSyncResultStatus(const SyncResult& result );
- void cleanItems( const QString& folder );
+ void setSyncResultStatus(const SyncResult &result);
+ void cleanItems(const QString &folder);
- QTreeWidgetItem* createCompletedTreewidgetItem(const QString &folder, const SyncFileItem &item );
+ QTreeWidgetItem *createCompletedTreewidgetItem(const QString &folder, const SyncFileItem &item);
QString timeString(QDateTime dt, QLocale::FormatType format = QLocale::NarrowFormat) const;
Ui::ProtocolWidget *_ui;
QTreeWidget *_issueItemView;
};
-
}
#endif // PROTOCOLWIDGET_H
namespace OCC {
-ProxyAuthDialog::ProxyAuthDialog(QWidget *parent) :
- QDialog(parent),
- ui(new Ui::ProxyAuthDialog)
+ProxyAuthDialog::ProxyAuthDialog(QWidget *parent)
+ : QDialog(parent)
+ , ui(new Ui::ProxyAuthDialog)
{
ui->setupUi(this);
}
namespace OCC {
namespace Ui {
-class ProxyAuthDialog;
+ class ProxyAuthDialog;
}
/**
explicit ProxyAuthDialog(QWidget *parent = 0);
~ProxyAuthDialog();
- void setProxyAddress(const QString& address);
+ void setProxyAddress(const QString &address);
QString username() const;
QString password() const;
Q_LOGGING_CATEGORY(lcProxy, "gui.credentials.proxy", QtInfoMsg)
-ProxyAuthHandler* ProxyAuthHandler::instance()
+ProxyAuthHandler *ProxyAuthHandler::instance()
{
static ProxyAuthHandler inst;
return &inst;
}
void ProxyAuthHandler::handleProxyAuthenticationRequired(
- const QNetworkProxy& proxy,
- QAuthenticator* authenticator)
+ const QNetworkProxy &proxy,
+ QAuthenticator *authenticator)
{
if (!_dialog) {
return;
// If the user explicitly configured the proxy in the
// network settings, don't ask about it.
if (_configFile->proxyType() == QNetworkProxy::HttpProxy
- || _configFile->proxyType() == QNetworkProxy::Socks5Proxy) {
+ || _configFile->proxyType() == QNetworkProxy::Socks5Proxy) {
_blocked = true;
}
}
}
// Find the responsible QNAM if possible.
- QNetworkAccessManager* sending_qnam = 0;
+ QNetworkAccessManager *sending_qnam = 0;
QWeakPointer<QNetworkAccessManager> qnam_alive;
- if (Account* account = qobject_cast<Account*>(sender())) {
+ if (Account *account = qobject_cast<Account *>(sender())) {
// Since we go into an event loop, it's possible for the account's qnam
// to be destroyed before we get back. We can use this to check for its
// liveness.
// isn't reliable, so we also invalidate credentials if we previously
// gave presumably valid credentials to the same QNAM.
bool invalidated = false;
- if (!_waitingForDialog && !_waitingForKeychain &&
- (!authenticator->user().isEmpty()
- || (sending_qnam && _gaveCredentialsTo.contains(sending_qnam)))) {
+ if (!_waitingForDialog && !_waitingForKeychain && (!authenticator->user().isEmpty()
+ || (sending_qnam && _gaveCredentialsTo.contains(sending_qnam)))) {
qCInfo(lcProxy) << "invalidating old creds" << key;
_username.clear();
_password.clear();
sending_qnam = qnam_alive.data();
if (sending_qnam) {
_gaveCredentialsTo.insert(sending_qnam);
- connect(sending_qnam, SIGNAL(destroyed(QObject*)),
- SLOT(slotSenderDestroyed(QObject*)));
+ connect(sending_qnam, SIGNAL(destroyed(QObject *)),
+ SLOT(slotSenderDestroyed(QObject *)));
}
}
_keychainJobRunning = false;
}
-void ProxyAuthHandler::slotSenderDestroyed(QObject* obj)
+void ProxyAuthHandler::slotSenderDestroyed(QObject *obj)
{
_gaveCredentialsTo.remove(obj);
}
_readPasswordJob->setInsecureFallback(false);
_readPasswordJob->setKey(keychainPasswordKey());
_readPasswordJob->setAutoDelete(false);
- connect(_readPasswordJob.data(), SIGNAL(finished(QKeychain::Job*)),
- SLOT(slotKeychainJobDone()));
+ connect(_readPasswordJob.data(), SIGNAL(finished(QKeychain::Job *)),
+ SLOT(slotKeychainJobDone()));
_keychainJobRunning = true;
_readPasswordJob->start();
}
_settings->setValue(keychainUsernameKey(), _username);
- WritePasswordJob* job = new WritePasswordJob(Theme::instance()->appName(), this);
+ WritePasswordJob *job = new WritePasswordJob(Theme::instance()->appName(), this);
job->setSettings(_settings.data());
job->setInsecureFallback(false);
job->setKey(keychainPasswordKey());
job->setTextData(_password);
job->setAutoDelete(false);
- connect(job, SIGNAL(finished(QKeychain::Job*)), SLOT(slotKeychainJobDone()));
+ connect(job, SIGNAL(finished(QKeychain::Job *)), SLOT(slotKeychainJobDone()));
_keychainJobRunning = true;
job->start();
Q_OBJECT
public:
- static ProxyAuthHandler* instance();
+ static ProxyAuthHandler *instance();
virtual ~ProxyAuthHandler();
public slots:
/// Intended for QNetworkAccessManager::proxyAuthenticationRequired()
- void handleProxyAuthenticationRequired(const QNetworkProxy& proxy,
- QAuthenticator* authenticator);
+ void handleProxyAuthenticationRequired(const QNetworkProxy &proxy,
+ QAuthenticator *authenticator);
private slots:
void slotKeychainJobDone();
- void slotSenderDestroyed(QObject*);
+ void slotSenderDestroyed(QObject *);
private:
ProxyAuthHandler();
/// To distinguish between a new QNAM asking for credentials and credentials
/// failing for an existing QNAM, we keep track of the senders of the
/// proxyAuthRequired signal here.
- QSet<QObject*> _gaveCredentialsTo;
+ QSet<QObject *> _gaveCredentialsTo;
};
} // namespace OCC
namespace OCC {
namespace {
-static const int defaultIntervalT = 30*1000;
-static const int failIntervalT = 5*1000;
+ static const int defaultIntervalT = 30 * 1000;
+ static const int failIntervalT = 5 * 1000;
}
QuotaInfo::QuotaInfo(AccountState *accountState, QObject *parent)
, _active(false)
{
connect(accountState, SIGNAL(stateChanged(int)),
- SLOT(slotAccountStateChanged()));
+ SLOT(slotAccountStateChanged()));
connect(&_jobRestartTimer, SIGNAL(timeout()), SLOT(slotCheckQuota()));
_jobRestartTimer.setSingleShot(true);
}
bool QuotaInfo::canGetQuota() const
{
- if (! _accountState || !_active) {
+ if (!_accountState || !_active) {
return false;
}
AccountPtr account = _accountState->account();
void QuotaInfo::slotCheckQuota()
{
- if (! canGetQuota()) {
+ if (!canGetQuota()) {
return;
}
AccountPtr account = _accountState->account();
_job = new PropfindJob(account, quotaBaseFolder(), this);
- _job->setProperties(QList<QByteArray>() << "quota-available-bytes" << "quota-used-bytes");
+ _job->setProperties(QList<QByteArray>() << "quota-available-bytes"
+ << "quota-used-bytes");
connect(_job, SIGNAL(result(QVariantMap)), SLOT(slotUpdateLastQuota(QVariantMap)));
- connect(_job, SIGNAL(networkError(QNetworkReply*)), SLOT(slotRequestFailed()));
+ connect(_job, SIGNAL(networkError(QNetworkReply *)), SLOT(slotRequestFailed()));
_job->start();
}
_jobRestartTimer.start(defaultIntervalT);
_lastQuotaRecieved = QDateTime::currentDateTime();
}
-
}
*
* @ingroup gui
*/
-class QuotaInfo : public QObject {
+class QuotaInfo : public QObject
+{
Q_OBJECT
public:
- explicit QuotaInfo(OCC::AccountState* accountState, QObject* parent = 0);
+ explicit QuotaInfo(OCC::AccountState *accountState, QObject *parent = 0);
qint64 lastQuotaTotalBytes() const { return _lastQuotaTotalBytes; }
qint64 lastQuotaUsedBytes() const { return _lastQuotaUsedBytes; }
};
-
} // namespace OCC
#endif //QUOTAINFO_H
namespace OCC {
-class SelectiveSyncTreeViewItem : public QTreeWidgetItem {
+class SelectiveSyncTreeViewItem : public QTreeWidgetItem
+{
public:
SelectiveSyncTreeViewItem(int type = QTreeWidgetItem::Type)
- : QTreeWidgetItem(type) { }
+ : QTreeWidgetItem(type)
+ {
+ }
SelectiveSyncTreeViewItem(const QStringList &strings, int type = QTreeWidgetItem::Type)
- : QTreeWidgetItem(strings, type) { }
+ : QTreeWidgetItem(strings, type)
+ {
+ }
SelectiveSyncTreeViewItem(QTreeWidget *view, int type = QTreeWidgetItem::Type)
- : QTreeWidgetItem(view, type) { }
+ : QTreeWidgetItem(view, type)
+ {
+ }
SelectiveSyncTreeViewItem(QTreeWidgetItem *parent, int type = QTreeWidgetItem::Type)
- : QTreeWidgetItem(parent, type) { }
+ : QTreeWidgetItem(parent, type)
+ {
+ }
private:
- bool operator<(const QTreeWidgetItem &other)const {
+ bool operator<(const QTreeWidgetItem &other) const
+ {
int column = treeWidget()->sortColumn();
if (column == 1) {
return data(1, Qt::UserRole).toLongLong() < other.data(1, Qt::UserRole).toLongLong();
}
- return QTreeWidgetItem::operator <(other);
+ return QTreeWidgetItem::operator<(other);
}
};
layout->addWidget(_folderTree);
- connect(_folderTree, SIGNAL(itemExpanded(QTreeWidgetItem*)),
- SLOT(slotItemExpanded(QTreeWidgetItem*)));
- connect(_folderTree, SIGNAL(itemChanged(QTreeWidgetItem*,int)),
- SLOT(slotItemChanged(QTreeWidgetItem*,int)));
+ connect(_folderTree, SIGNAL(itemExpanded(QTreeWidgetItem *)),
+ SLOT(slotItemExpanded(QTreeWidgetItem *)));
+ connect(_folderTree, SIGNAL(itemChanged(QTreeWidgetItem *, int)),
+ SLOT(slotItemChanged(QTreeWidgetItem *, int)));
_folderTree->setSortingEnabled(true);
_folderTree->sortByColumn(0, Qt::AscendingOrder);
_folderTree->setColumnCount(2);
_folderTree->header()->setSectionResizeMode(0, QHeaderView::QHeaderView::ResizeToContents);
_folderTree->header()->setSectionResizeMode(1, QHeaderView::QHeaderView::ResizeToContents);
#else
- _folderTree->header()->resizeSection(0, sizeHint().width()/2);
+ _folderTree->header()->resizeSection(0, sizeHint().width() / 2);
#endif
_folderTree->header()->setStretchLastSection(true);
_folderTree->headerItem()->setText(0, tr("Name"));
void SelectiveSyncWidget::refreshFolders()
{
LsColJob *job = new LsColJob(_account, _folderPath, this);
- job->setProperties(QList<QByteArray>() << "resourcetype" << "http://owncloud.org/ns:size");
+ job->setProperties(QList<QByteArray>() << "resourcetype"
+ << "http://owncloud.org/ns:size");
connect(job, SIGNAL(directoryListingSubfolders(QStringList)),
- this, SLOT(slotUpdateDirectories(QStringList)));
- connect(job, SIGNAL(finishedWithError(QNetworkReply*)),
- this, SLOT(slotLscolFinishedWithError(QNetworkReply*)));
+ this, SLOT(slotUpdateDirectories(QStringList)));
+ connect(job, SIGNAL(finishedWithError(QNetworkReply *)),
+ this, SLOT(slotLscolFinishedWithError(QNetworkReply *)));
job->start();
_folderTree->clear();
_loading->show();
_loading->move(10, _folderTree->header()->height() + 10);
}
-void SelectiveSyncWidget::setFolderInfo(const QString& folderPath, const QString& rootName, const QStringList& oldBlackList)
+void SelectiveSyncWidget::setFolderInfo(const QString &folderPath, const QString &rootName, const QStringList &oldBlackList)
{
_folderPath = folderPath;
if (_folderPath.startsWith(QLatin1Char('/'))) {
refreshFolders();
}
-static QTreeWidgetItem* findFirstChild(QTreeWidgetItem *parent, const QString& text)
+static QTreeWidgetItem *findFirstChild(QTreeWidgetItem *parent, const QString &text)
{
for (int i = 0; i < parent->childCount(); ++i) {
QTreeWidgetItem *child = parent->child(i);
return 0;
}
-void SelectiveSyncWidget::recursiveInsert(QTreeWidgetItem* parent, QStringList pathTrail, QString path, qint64 size)
+void SelectiveSyncWidget::recursiveInsert(QTreeWidgetItem *parent, QStringList pathTrail, QString path, qint64 size)
{
QFileIconProvider prov;
QIcon folderIcon = prov.icon(QFileIconProvider::Folder);
parent->setToolTip(0, path);
parent->setData(0, Qt::UserRole, path);
} else {
- SelectiveSyncTreeViewItem *item = static_cast<SelectiveSyncTreeViewItem*>(findFirstChild(parent, pathTrail.first()));
+ SelectiveSyncTreeViewItem *item = static_cast<SelectiveSyncTreeViewItem *>(findFirstChild(parent, pathTrail.first()));
if (!item) {
item = new SelectiveSyncTreeViewItem(parent);
if (parent->checkState(0) == Qt::Checked
- || parent->checkState(0) == Qt::PartiallyChecked) {
+ || parent->checkState(0) == Qt::PartiallyChecked) {
item->setCheckState(0, Qt::Checked);
- foreach(const QString &str , _oldBlackList) {
+ foreach (const QString &str, _oldBlackList) {
if (str == path || str == QLatin1String("/")) {
item->setCheckState(0, Qt::Unchecked);
break;
item->setText(1, Utility::octetsToString(size));
item->setData(1, Qt::UserRole, size);
}
-// item->setData(0, Qt::UserRole, pathTrail.first());
+ // item->setData(0, Qt::UserRole, pathTrail.first());
item->setChildIndicatorPolicy(QTreeWidgetItem::ShowIndicator);
}
QScopedValueRollback<bool> isInserting(_inserting);
_inserting = true;
- SelectiveSyncTreeViewItem *root = static_cast<SelectiveSyncTreeViewItem*>(_folderTree->topLevelItem(0));
+ SelectiveSyncTreeViewItem *root = static_cast<SelectiveSyncTreeViewItem *>(_folderTree->topLevelItem(0));
QUrl url = _account->davUrl();
QString pathToRemove = url.path();
auto size = job ? job->_sizes.value(path) : 0;
path.remove(pathToRemove);
QStringList paths = path.split('/');
- if (paths.last().isEmpty()) paths.removeLast();
+ if (paths.last().isEmpty())
+ paths.removeLast();
if (paths.isEmpty())
continue;
if (!path.endsWith('/')) {
void SelectiveSyncWidget::slotItemExpanded(QTreeWidgetItem *item)
{
QString dir = item->data(0, Qt::UserRole).toString();
- if (dir.isEmpty()) return;
+ if (dir.isEmpty())
+ return;
QString prefix;
if (!_folderPath.isEmpty()) {
prefix = _folderPath + QLatin1Char('/');
}
LsColJob *job = new LsColJob(_account, prefix + dir, this);
- job->setProperties(QList<QByteArray>() << "resourcetype" << "http://owncloud.org/ns:size");
+ job->setProperties(QList<QByteArray>() << "resourcetype"
+ << "http://owncloud.org/ns:size");
connect(job, SIGNAL(directoryListingSubfolders(QStringList)),
- SLOT(slotUpdateDirectories(QStringList)));
+ SLOT(slotUpdateDirectories(QStringList)));
job->start();
}
}
}
-QStringList SelectiveSyncWidget::createBlackList(QTreeWidgetItem* root) const
+QStringList SelectiveSyncWidget::createBlackList(QTreeWidgetItem *root) const
{
if (!root) {
root = _folderTree->topLevelItem(0);
}
- if (!root) return QStringList();
+ if (!root)
+ return QStringList();
- switch(root->checkState(0)) {
+ switch (root->checkState(0)) {
case Qt::Unchecked:
return QStringList(root->data(0, Qt::UserRole).toString() + "/");
- case Qt::Checked:
+ case Qt::Checked:
return QStringList();
case Qt::PartiallyChecked:
break;
} else {
// We did not load from the server so we re-use the one from the old black list
QString path = root->data(0, Qt::UserRole).toString();
- foreach (const QString & it, _oldBlackList) {
+ foreach (const QString &it, _oldBlackList) {
if (it.startsWith(path))
result += it;
}
return _oldBlackList;
}
-qint64 SelectiveSyncWidget::estimatedSize(QTreeWidgetItem* root)
+qint64 SelectiveSyncWidget::estimatedSize(QTreeWidgetItem *root)
{
if (!root) {
root = _folderTree->topLevelItem(0);
}
- if (!root) return -1;
+ if (!root)
+ return -1;
- switch(root->checkState(0)) {
- case Qt::Unchecked:
- return 0;
- case Qt::Checked:
- return root->data(1, Qt::UserRole).toLongLong();
- case Qt::PartiallyChecked:
- break;
+ switch (root->checkState(0)) {
+ case Qt::Unchecked:
+ return 0;
+ case Qt::Checked:
+ return root->data(1, Qt::UserRole).toLongLong();
+ case Qt::PartiallyChecked:
+ break;
}
qint64 result = 0;
if (root->childCount()) {
for (int i = 0; i < root->childCount(); ++i) {
auto r = estimatedSize(root->child(i));
- if (r < 0) return r;
+ if (r < 0)
+ return r;
result += r;
}
} else {
}
-SelectiveSyncDialog::SelectiveSyncDialog(AccountPtr account, Folder* folder, QWidget* parent, Qt::WindowFlags f)
- : QDialog(parent, f), _folder(folder),
- _okButton(0) // defined in init()
+SelectiveSyncDialog::SelectiveSyncDialog(AccountPtr account, Folder *folder, QWidget *parent, Qt::WindowFlags f)
+ : QDialog(parent, f)
+ , _folder(folder)
+ , _okButton(0) // defined in init()
{
bool ok;
init(account);
QStringList selectiveSyncList = _folder->journalDb()->getSelectiveSyncList(SyncJournalDb::SelectiveSyncBlackList, &ok);
- if( ok ) {
- _selectiveSync->setFolderInfo(_folder->remotePath(), _folder->alias(),selectiveSyncList);
+ if (ok) {
+ _selectiveSync->setFolderInfo(_folder->remotePath(), _folder->alias(), selectiveSyncList);
} else {
_okButton->setEnabled(false);
}
// Make sure we don't get crashes if the folder is destroyed while we are still open
- connect(_folder, SIGNAL(destroyed(QObject*)), this, SLOT(deleteLater()));
+ connect(_folder, SIGNAL(destroyed(QObject *)), this, SLOT(deleteLater()));
}
SelectiveSyncDialog::SelectiveSyncDialog(AccountPtr account, const QString &folder,
- const QStringList& blacklist, QWidget* parent, Qt::WindowFlags f)
- : QDialog(parent, f), _folder(0)
+ const QStringList &blacklist, QWidget *parent, Qt::WindowFlags f)
+ : QDialog(parent, f)
+ , _folder(0)
{
init(account);
_selectiveSync->setFolderInfo(folder, folder, blacklist);
if (_folder) {
bool ok;
auto oldBlackListSet = _folder->journalDb()->getSelectiveSyncList(SyncJournalDb::SelectiveSyncBlackList, &ok).toSet();
- if( ! ok ) {
+ if (!ok) {
return;
}
QStringList blackList = _selectiveSync->createBlackList();
// (the ones that are no longer in the blacklist)
auto blackListSet = blackList.toSet();
auto changes = (oldBlackListSet - blackListSet) + (blackListSet - oldBlackListSet);
- foreach(const auto &it, changes) {
+ foreach (const auto &it, changes) {
_folder->journalDb()->avoidReadFromDbOnNextSync(it);
}
{
return _selectiveSync->estimatedSize();
}
-
}
-
* @brief The SelectiveSyncWidget contains a folder tree with labels
* @ingroup gui
*/
-class SelectiveSyncWidget : public QWidget {
+class SelectiveSyncWidget : public QWidget
+{
Q_OBJECT
public:
- explicit SelectiveSyncWidget(AccountPtr account, QWidget* parent = 0);
+ explicit SelectiveSyncWidget(AccountPtr account, QWidget *parent = 0);
/// Returns a list of blacklisted paths, each including the trailing /
- QStringList createBlackList(QTreeWidgetItem* root = 0) const;
+ QStringList createBlackList(QTreeWidgetItem *root = 0) const;
/** Returns the oldBlackList passed into setFolderInfo(), except that
* a "/" entry is expanded to all top-level folder names.
// oldBlackList is a list of excluded paths, each including a trailing /
void setFolderInfo(const QString &folderPath, const QString &rootName,
- const QStringList &oldBlackList = QStringList());
+ const QStringList &oldBlackList = QStringList());
QSize sizeHint() const Q_DECL_OVERRIDE;
private slots:
void slotUpdateDirectories(QStringList);
void slotItemExpanded(QTreeWidgetItem *);
- void slotItemChanged(QTreeWidgetItem*,int);
- void slotLscolFinishedWithError(QNetworkReply*);
+ void slotItemChanged(QTreeWidgetItem *, int);
+ void slotLscolFinishedWithError(QNetworkReply *);
+
private:
void refreshFolders();
- void recursiveInsert(QTreeWidgetItem* parent, QStringList pathTrail, QString path, qint64 size);
+ void recursiveInsert(QTreeWidgetItem *parent, QStringList pathTrail, QString path, qint64 size);
AccountPtr _account;
* @brief The SelectiveSyncDialog class
* @ingroup gui
*/
-class SelectiveSyncDialog : public QDialog {
+class SelectiveSyncDialog : public QDialog
+{
Q_OBJECT
public:
// Dialog for a specific folder (used from the account settings button)
- explicit SelectiveSyncDialog(AccountPtr account, Folder *folder, QWidget* parent = 0, Qt::WindowFlags f = 0);
+ explicit SelectiveSyncDialog(AccountPtr account, Folder *folder, QWidget *parent = 0, Qt::WindowFlags f = 0);
// Dialog for the whole account (Used from the wizard)
- explicit SelectiveSyncDialog(AccountPtr account, const QString &folder, const QStringList &blacklist, QWidget* parent = 0, Qt::WindowFlags f = 0);
+ explicit SelectiveSyncDialog(AccountPtr account, const QString &folder, const QStringList &blacklist, QWidget *parent = 0, Qt::WindowFlags f = 0);
virtual void accept() Q_DECL_OVERRIDE;
qint64 estimatedSize();
private:
-
void init(const AccountPtr &account);
SelectiveSyncWidget *_selectiveSync;
Folder *_folder;
QPushButton *_okButton;
};
-
}
#include <QJsonDocument>
#include <QJsonObject>
-namespace OCC
-{
+namespace OCC {
Q_LOGGING_CATEGORY(lcServerNotification, "gui.servernotification", QtInfoMsg)
ServerNotificationHandler::ServerNotificationHandler(QObject *parent)
: QObject(parent)
{
-
}
void ServerNotificationHandler::slotFetchNotifications(AccountState *ptr)
{
// check connectivity and credentials
- if( !( ptr && ptr->isConnected() && ptr->account() &&
- ptr->account()->credentials() &&
- ptr->account()->credentials()->ready() ) ) {
+ if (!(ptr && ptr->isConnected() && ptr->account() && ptr->account()->credentials() && ptr->account()->credentials()->ready())) {
deleteLater();
return;
}
// check if the account has notifications enabled. If the capabilities are
// not yet valid, its assumed that notifications are available.
- if( ptr->account()->capabilities().isValid() ) {
- if( ! ptr->account()->capabilities().notificationsAvailable() ) {
+ if (ptr->account()->capabilities().isValid()) {
+ if (!ptr->account()->capabilities().notificationsAvailable()) {
qCInfo(lcServerNotification) << "Account" << ptr->account()->displayName() << "does not have notifications enabled.";
deleteLater();
return;
}
// if the previous notification job has finished, start next.
- _notificationJob = new JsonApiJob( ptr->account(), QLatin1String("ocs/v2.php/apps/notifications/api/v1/notifications"), this );
+ _notificationJob = new JsonApiJob(ptr->account(), QLatin1String("ocs/v2.php/apps/notifications/api/v1/notifications"), this);
QObject::connect(_notificationJob.data(), SIGNAL(jsonReceived(QJsonDocument, int)),
- this, SLOT(slotNotificationsReceived(QJsonDocument, int)));
- _notificationJob->setProperty("AccountStatePtr", QVariant::fromValue<AccountState*>(ptr));
+ this, SLOT(slotNotificationsReceived(QJsonDocument, int)));
+ _notificationJob->setProperty("AccountStatePtr", QVariant::fromValue<AccountState *>(ptr));
_notificationJob->start();
}
-void ServerNotificationHandler::slotNotificationsReceived(const QJsonDocument& json, int statusCode)
+void ServerNotificationHandler::slotNotificationsReceived(const QJsonDocument &json, int statusCode)
{
- if( statusCode != 200 ) {
+ if (statusCode != 200) {
qCWarning(lcServerNotification) << "Notifications failed with status code " << statusCode;
deleteLater();
return;
auto notifies = json.object().value("ocs").toObject().value("data").toArray();
- AccountState* ai = qvariant_cast<AccountState*>(sender()->property("AccountStatePtr"));
+ AccountState *ai = qvariant_cast<AccountState *>(sender()->property("AccountStatePtr"));
ActivityList list;
- foreach( auto element, notifies ) {
+ foreach (auto element, notifies) {
Activity a;
- auto json = element.toObject();
- a._type = Activity::NotificationType;
- a._accName = ai->account()->displayName();
- a._id = json.value("notification_id").toInt();
- a._subject = json.value("subject").toString();
- a._message = json.value("message").toString();
- QString s = json.value("link").toString();
- if( !s.isEmpty() ) {
- a._link = QUrl(s);
+ auto json = element.toObject();
+ a._type = Activity::NotificationType;
+ a._accName = ai->account()->displayName();
+ a._id = json.value("notification_id").toInt();
+ a._subject = json.value("subject").toString();
+ a._message = json.value("message").toString();
+ QString s = json.value("link").toString();
+ if (!s.isEmpty()) {
+ a._link = QUrl(s);
}
a._dateTime = QDateTime::fromString(json.value("datetime").toString(), Qt::ISODate);
auto actions = json.value("actions").toArray();
- foreach( auto action, actions) {
+ foreach (auto action, actions) {
auto actionJson = action.toObject();
ActivityLink al;
al._label = QUrl::fromPercentEncoding(actionJson.value("label").toString().toUtf8());
- al._link = actionJson.value("link").toString();
- al._verb = actionJson.value("type").toString().toUtf8();
+ al._link = actionJson.value("link").toString();
+ al._verb = actionJson.value("type").toString().toUtf8();
al._isPrimary = actionJson.value("primary").toBool();
a._links.append(al);
}
list.append(a);
}
- emit newNotificationList( list );
+ emit newNotificationList(list);
deleteLater();
}
-
}
class QJsonDocument;
-namespace OCC
-{
+namespace OCC {
class ServerNotificationHandler : public QObject
{
void slotFetchNotifications(AccountState *ptr);
private slots:
- void slotNotificationsReceived(const QJsonDocument& json, int statusCode);
+ void slotNotificationsReceived(const QJsonDocument &json, int statusCode);
private:
QPointer<JsonApiJob> _notificationJob;
-
-
};
-
}
#endif // SERVERNOTIFICATIONHANDLER_H
#include <QPainterPath>
namespace {
- const char TOOLBAR_CSS[] =
+const char TOOLBAR_CSS[] =
"QToolBar { background: %1; margin: 0; padding: 0; border: none; border-bottom: 1px solid %2; spacing: 0; } "
"QToolBar QToolButton { background: %1; border: none; border-bottom: 1px solid %2; margin: 0; padding: 5px; } "
"QToolBar QToolBarExtension { padding:0; } "
"QToolBar QToolButton:checked { background: %3; color: %4; }";
- static const float buttonSizeRatio = 1.618; // golden ratio
+static const float buttonSizeRatio = 1.618; // golden ratio
}
namespace OCC {
-static QIcon circleMask( const QImage& avatar )
+static QIcon circleMask(const QImage &avatar)
{
int dim = avatar.width();
// Whenever you change something here check both settingsdialog.cpp and settingsdialogmac.cpp !
//
-SettingsDialog::SettingsDialog(ownCloudGui *gui, QWidget *parent) :
- QDialog(parent)
- , _ui(new Ui::SettingsDialog), _gui(gui)
+SettingsDialog::SettingsDialog(ownCloudGui *gui, QWidget *parent)
+ : QDialog(parent)
+ , _ui(new Ui::SettingsDialog)
+ , _gui(gui)
{
ConfigFile cfg;
_toolBar->addAction(_activityAction);
_activitySettings = new ActivitySettings;
_ui->stack->addWidget(_activitySettings);
- connect( _activitySettings, SIGNAL(guiLog(QString,QString)), _gui,
- SLOT(slotShowOptionalTrayMessage(QString,QString)) );
- _activitySettings->setNotificationRefreshInterval( cfg.notificationRefreshInterval());
+ connect(_activitySettings, SIGNAL(guiLog(QString, QString)), _gui,
+ SLOT(slotShowOptionalTrayMessage(QString, QString)));
+ _activitySettings->setNotificationRefreshInterval(cfg.notificationRefreshInterval());
QAction *generalAction = createColorAwareAction(QLatin1String(":/client/resources/settings.png"), tr("General"));
_actionGroup->addAction(generalAction);
_actionGroupWidgets.insert(generalAction, generalSettings);
_actionGroupWidgets.insert(networkAction, networkSettings);
- connect(_actionGroup, SIGNAL(triggered(QAction*)), SLOT(slotSwitchPage(QAction*)));
+ connect(_actionGroup, SIGNAL(triggered(QAction *)), SLOT(slotSwitchPage(QAction *)));
- connect(AccountManager::instance(), SIGNAL(accountAdded(AccountState*)),
- this, SLOT(accountAdded(AccountState*)));
- connect(AccountManager::instance(), SIGNAL(accountRemoved(AccountState*)),
- this, SLOT(accountRemoved(AccountState*)));
- foreach (auto ai , AccountManager::instance()->accounts()) {
+ connect(AccountManager::instance(), SIGNAL(accountAdded(AccountState *)),
+ this, SLOT(accountAdded(AccountState *)));
+ connect(AccountManager::instance(), SIGNAL(accountRemoved(AccountState *)),
+ this, SLOT(accountRemoved(AccountState *)));
+ foreach (auto ai, AccountManager::instance()->accounts()) {
accountAdded(ai.data());
}
}
// close event is not being called here
-void SettingsDialog::reject() {
+void SettingsDialog::reject()
+{
ConfigFile cfg;
cfg.saveGeometry(this);
QDialog::reject();
}
-void SettingsDialog::accept() {
+void SettingsDialog::accept()
+{
ConfigFile cfg;
cfg.saveGeometry(this);
QDialog::accept();
void SettingsDialog::showFirstPage()
{
- QList<QAction*> actions = _toolBar->actions();
+ QList<QAction *> actions = _toolBar->actions();
if (!actions.empty()) {
actions.first()->trigger();
}
QAction *accountAction;
QImage avatar = s->account()->avatar();
const QString actionText = brandingSingleAccount ? tr("Account") : s->account()->displayName();
- if(avatar.isNull()) {
+ if (avatar.isNull()) {
accountAction = createColorAwareAction(QLatin1String(":/client/resources/account.png"),
- actionText);
+ actionText);
} else {
QIcon icon = circleMask(avatar);
accountAction = createActionWithIcon(icon, actionText);
}
_toolBar->insertAction(_toolBar->actions().at(0), accountAction);
auto accountSettings = new AccountSettings(s, this);
- _ui->stack->insertWidget(0 , accountSettings);
+ _ui->stack->insertWidget(0, accountSettings);
_actionGroup->addAction(accountAction);
_actionGroupWidgets.insert(accountAction, accountSettings);
_actionForAccount.insert(s->account().data(), accountAction);
- connect( accountSettings, SIGNAL(folderChanged()), _gui, SLOT(slotFoldersChanged()));
- connect( accountSettings, SIGNAL(openFolderAlias(const QString&)),
- _gui, SLOT(slotFolderOpenAction(QString)));
+ connect(accountSettings, SIGNAL(folderChanged()), _gui, SLOT(slotFoldersChanged()));
+ connect(accountSettings, SIGNAL(openFolderAlias(const QString &)),
+ _gui, SLOT(slotFolderOpenAction(QString)));
connect(s->account().data(), SIGNAL(accountChangedAvatar()), SLOT(slotAccountAvatarChanged()));
slotRefreshActivity(s);
void SettingsDialog::slotAccountAvatarChanged()
{
- Account *account = static_cast<Account*>(sender());
- if( account && _actionForAccount.contains(account)) {
+ Account *account = static_cast<Account *>(sender());
+ if (account && _actionForAccount.contains(account)) {
QAction *action = _actionForAccount[account];
- if( action ) {
+ if (action) {
QImage pix = account->avatar();
- if( !pix.isNull() ) {
- action->setIcon( circleMask(pix) );
+ if (!pix.isNull()) {
+ action->setIcon(circleMask(pix));
}
}
}
}
}
- if( _actionForAccount.contains(s->account().data()) ) {
+ if (_actionForAccount.contains(s->account().data())) {
_actionForAccount.remove(s->account().data());
}
_activitySettings->slotRemoveAccount(s);
void SettingsDialog::customizeStyle()
{
- QString highlightColor(palette().highlight().color().name());
+ QString highlightColor(palette().highlight().color().name());
QString altBase(palette().alternateBase().color().name());
QString dark(palette().dark().color().name());
QString background(palette().base().color().name());
- _toolBar->setStyleSheet(QString::fromAscii(TOOLBAR_CSS).arg(background,dark,highlightColor,altBase));
+ _toolBar->setStyleSheet(QString::fromAscii(TOOLBAR_CSS).arg(background, dark, highlightColor, altBase));
- Q_FOREACH(QAction *a, _actionGroup->actions()) {
+ Q_FOREACH (QAction *a, _actionGroup->actions()) {
QIcon icon = createColorAwareIcon(a->property("iconPath").toString());
a->setIcon(icon);
- QToolButton *btn = qobject_cast<QToolButton*>(_toolBar->widgetForAction(a));
+ QToolButton *btn = qobject_cast<QToolButton *>(_toolBar->widgetForAction(a));
if (btn) {
btn->setIcon(icon);
}
}
-
}
QIcon SettingsDialog::createColorAwareIcon(const QString &name)
{
- QColor bg(palette().base().color());
+ QColor bg(palette().base().color());
QImage img(name);
// account for different sensitivity of the human eye to certain colors
- double treshold = 1.0 - ( 0.299 * bg.red() + 0.587 * bg.green() + 0.114 * bg.blue())/255.0;
+ double treshold = 1.0 - (0.299 * bg.red() + 0.587 * bg.green() + 0.114 * bg.blue()) / 255.0;
if (treshold > 0.5) {
img.invertPixels(QImage::InvertRgb);
}
class ToolButtonAction : public QWidgetAction
{
public:
- explicit ToolButtonAction(const QIcon &icon, const QString &text, QObject* parent)
- : QWidgetAction(parent) {
+ explicit ToolButtonAction(const QIcon &icon, const QString &text, QObject *parent)
+ : QWidgetAction(parent)
+ {
setText(text);
setIcon(icon);
}
- QWidget* createWidget(QWidget* parent) Q_DECL_OVERRIDE {
-
- auto toolbar = qobject_cast<QToolBar*>(parent);
+ QWidget *createWidget(QWidget *parent) Q_DECL_OVERRIDE
+ {
+ auto toolbar = qobject_cast<QToolBar *>(parent);
if (!toolbar) {
// this means we are in the extention menu, no special action here
return 0;
}
- QToolButton* btn = new QToolButton(parent);
+ QToolButton *btn = new QToolButton(parent);
btn->setDefaultAction(this);
btn->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
btn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);
-// btn->setMinimumWidth(qMax<int>(parent->sizeHint().height() * buttonSizeRatio,
-// btn->sizeHint().width()));
+ // btn->setMinimumWidth(qMax<int>(parent->sizeHint().height() * buttonSizeRatio,
+ // btn->sizeHint().width()));
return btn;
}
};
-QAction *SettingsDialog::createActionWithIcon(const QIcon& icon, const QString& text, const QString& iconPath)
+QAction *SettingsDialog::createActionWithIcon(const QIcon &icon, const QString &text, const QString &iconPath)
{
QAction *action = new ToolButtonAction(icon, text, this);
action->setCheckable(true);
- if(!iconPath.isEmpty()) {
+ if (!iconPath.isEmpty()) {
action->setProperty("iconPath", iconPath);
}
return action;
-
}
QAction *SettingsDialog::createColorAwareAction(const QString &iconPath, const QString &text)
return createActionWithIcon(coloredIcon, text, iconPath);
}
-void SettingsDialog::slotRefreshActivity( AccountState* accountState )
+void SettingsDialog::slotRefreshActivity(AccountState *accountState)
{
if (accountState) {
_activitySettings->slotRefresh(accountState);
class AccountState;
namespace Ui {
-class SettingsDialog;
+ class SettingsDialog;
}
class AccountSettings;
class Application;
void showFirstPage();
void showActivityPage();
void slotSwitchPage(QAction *action);
- void slotRefreshActivity(AccountState *accountState );
+ void slotRefreshActivity(AccountState *accountState);
void slotAccountAvatarChanged();
protected:
QIcon createColorAwareIcon(const QString &name);
QAction *createColorAwareAction(const QString &iconName, const QString &fileName);
- QAction *createActionWithIcon(const QIcon& icon, const QString& text, const QString& iconPath = QString());
+ QAction *createActionWithIcon(const QIcon &icon, const QString &text, const QString &iconPath = QString());
- Ui::SettingsDialog * const _ui;
+ Ui::SettingsDialog *const _ui;
- QActionGroup* _actionGroup;
+ QActionGroup *_actionGroup;
// Maps the actions from the action group to the corresponding widgets
- QHash<QAction*, QWidget*> _actionGroupWidgets;
+ QHash<QAction *, QWidget *> _actionGroupWidgets;
// Maps the action in the dialog to their according account. Needed in
// case the account avatar changes
- QHash<Account*, QAction*> _actionForAccount;
+ QHash<Account *, QAction *> _actionForAccount;
- QToolBar* _toolBar;
+ QToolBar *_toolBar;
ActivitySettings *_activitySettings;
- QAction * _activityAction;
+ QAction *_activityAction;
ownCloudGui *_gui;
};
-
}
#endif // SETTINGSDIALOG_H
namespace OCC {
// Duplicate in settingsdialog.cpp
-static QIcon circleMask( const QImage& avatar )
+static QIcon circleMask(const QImage &avatar)
{
int dim = avatar.width();
// Whenever you change something here check both settingsdialog.cpp and settingsdialogmac.cpp !
//
SettingsDialogMac::SettingsDialogMac(ownCloudGui *gui, QWidget *parent)
- : MacPreferencesWindow(parent), _gui(gui)
+ : MacPreferencesWindow(parent)
+ , _gui(gui)
{
// do not show minimize button. There is no use, and restoring the
// dialog from minimize is broken in MacPreferencesWindow
- setWindowFlags(Qt::Window | Qt::WindowTitleHint | Qt::CustomizeWindowHint |
- Qt::WindowCloseButtonHint | Qt::WindowMaximizeButtonHint);
+ setWindowFlags(Qt::Window | Qt::WindowTitleHint | Qt::CustomizeWindowHint | Qt::WindowCloseButtonHint | Qt::WindowMaximizeButtonHint);
// Emulate dialog behavior: Escape means close
QIcon activityIcon(QLatin1String(":/client/resources/activity.png"));
_activitySettings = new ActivitySettings;
addPreferencesPanel(activityIcon, tr("Activity"), _activitySettings);
- connect( _activitySettings, SIGNAL(guiLog(QString,QString)), _gui,
- SLOT(slotShowOptionalTrayMessage(QString,QString)) );
+ connect(_activitySettings, SIGNAL(guiLog(QString, QString)), _gui,
+ SLOT(slotShowOptionalTrayMessage(QString, QString)));
connect(AccountManager::instance(), &AccountManager::accountAdded,
- this, &SettingsDialogMac::accountAdded);
+ this, &SettingsDialogMac::accountAdded);
connect(AccountManager::instance(), &AccountManager::accountRemoved,
- this, &SettingsDialogMac::accountRemoved);
- foreach (auto ai , AccountManager::instance()->accounts()) {
+ this, &SettingsDialogMac::accountRemoved);
+ foreach (auto ai, AccountManager::instance()->accounts()) {
accountAdded(ai.data());
}
insertPreferencesPanel(0, accountIcon, displayName, accountSettings);
- connect( accountSettings, &AccountSettings::folderChanged, _gui, &ownCloudGui::slotFoldersChanged);
- connect( accountSettings, &AccountSettings::openFolderAlias, _gui, &ownCloudGui::slotFolderOpenAction);
+ connect(accountSettings, &AccountSettings::folderChanged, _gui, &ownCloudGui::slotFoldersChanged);
+ connect(accountSettings, &AccountSettings::openFolderAlias, _gui, &ownCloudGui::slotFolderOpenAction);
connect(s->account().data(), SIGNAL(accountChangedAvatar()), this, SLOT(slotAccountAvatarChanged()));
void SettingsDialogMac::accountRemoved(AccountState *s)
{
- auto list = findChildren<AccountSettings*>(QString());
- foreach(auto p, list) {
+ auto list = findChildren<AccountSettings *>(QString());
+ foreach (auto p, list) {
if (p->accountsState() == s) {
removePreferencesPanel(p);
}
_activitySettings->slotRemoveAccount(s);
}
-void SettingsDialogMac::slotRefreshActivity( AccountState* accountState )
+void SettingsDialogMac::slotRefreshActivity(AccountState *accountState)
{
if (accountState) {
_activitySettings->slotRefresh(accountState);
void SettingsDialogMac::slotAccountAvatarChanged()
{
- Account *account = static_cast<Account*>(sender());
- auto list = findChildren<AccountSettings*>(QString());
- foreach(auto p, list) {
+ Account *account = static_cast<Account *>(sender());
+ auto list = findChildren<AccountSettings *>(QString());
+ foreach (auto p, list) {
if (p->accountsState()->account() == account) {
int idx = indexForPanel(p);
QImage pix = account->avatar();
}
}
}
-
}
public slots:
void showActivityPage();
- void slotRefreshActivity(AccountState *accountState );
+ void slotRefreshActivity(AccountState *accountState);
private slots:
void accountAdded(AccountState *);
void accountRemoved(AccountState *);
void slotAccountAvatarChanged();
+
private:
void closeEvent(QCloseEvent *event);
- ProtocolWidget *_protocolWidget;
+ ProtocolWidget *_protocolWidget;
ActivitySettings *_activitySettings;
- ownCloudGui *_gui;
+ ownCloudGui *_gui;
int _protocolIdx;
};
-
}
#endif // SETTINGSDIALOGMAC_H
static const int thumbnailSize = 40;
ShareDialog::ShareDialog(QPointer<AccountState> accountState,
- const QString &sharePath,
- const QString &localPath,
- SharePermissions maxSharingPermissions,
- QWidget *parent) :
- QDialog(parent),
- _ui(new Ui::ShareDialog),
- _accountState(accountState),
- _sharePath(sharePath),
- _localPath(localPath),
- _maxSharingPermissions(maxSharingPermissions),
- _linkWidget(NULL),
- _userGroupWidget(NULL),
- _progressIndicator(NULL)
+ const QString &sharePath,
+ const QString &localPath,
+ SharePermissions maxSharingPermissions,
+ QWidget *parent)
+ : QDialog(parent)
+ , _ui(new Ui::ShareDialog)
+ , _accountState(accountState)
+ , _sharePath(sharePath)
+ , _localPath(localPath)
+ , _maxSharingPermissions(maxSharingPermissions)
+ , _linkWidget(NULL)
+ , _userGroupWidget(NULL)
+ , _progressIndicator(NULL)
{
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
setAttribute(Qt::WA_DeleteOnClose);
QFileInfo lPath(_localPath);
QString fileName = lPath.fileName();
_ui->label_name->setText(tr("%1").arg(fileName));
- QFont f( _ui->label_name->font());
- f.setPointSize( f.pointSize() * 1.4 );
- _ui->label_name->setFont( f );
+ QFont f(_ui->label_name->font());
+ f.setPointSize(f.pointSize() * 1.4);
+ _ui->label_name->setFont(f);
_ui->label_sharePath->setWordWrap(true);
QString ocDir(_sharePath);
- ocDir.truncate(ocDir.length()-fileName.length());
+ ocDir.truncate(ocDir.length() - fileName.length());
ocDir.replace(QRegExp("^/*"), "");
ocDir.replace(QRegExp("/*$"), "");
// may be in use or not.
_ui->gridLayout->removeWidget(_ui->label_sharePath);
_ui->gridLayout->removeWidget(_ui->label_name);
- if( ocDir.isEmpty() ) {
+ if (ocDir.isEmpty()) {
_ui->gridLayout->addWidget(_ui->label_name, 0, 1, 2, 1);
_ui->label_sharePath->setText(QString());
} else {
job->setProperties(QList<QByteArray>() << "http://open-collaboration-services.org/ns:share-permissions");
job->setTimeout(10 * 1000);
connect(job, SIGNAL(result(QVariantMap)), SLOT(slotMaxSharingPermissionsReceived(QVariantMap)));
- connect(job, SIGNAL(finishedWithError(QNetworkReply*)), SLOT(slotMaxSharingPermissionsError()));
+ connect(job, SIGNAL(finishedWithError(QNetworkReply *)), SLOT(slotMaxSharingPermissionsError()));
job->start();
}
delete _ui;
}
-void ShareDialog::done( int r ) {
+void ShareDialog::done(int r)
+{
ConfigFile cfg;
cfg.saveGeometry(this);
QDialog::done(r);
}
-void ShareDialog::slotMaxSharingPermissionsReceived(const QVariantMap & result)
+void ShareDialog::slotMaxSharingPermissionsReceived(const QVariantMap &result)
{
const QVariant receivedPermissions = result["share-permissions"];
if (!receivedPermissions.toString().isEmpty()) {
// We only do user/group sharing from 8.2.0
bool userGroupSharing =
- theme->userGroupSharing()
- && _accountState->account()->serverVersionInt() >= Account::makeServerVersion(8, 2, 0);
+ theme->userGroupSharing()
+ && _accountState->account()->serverVersionInt() >= Account::makeServerVersion(8, 2, 0);
if (userGroupSharing) {
_userGroupWidget = new ShareUserGroupWidget(_accountState->account(), _sharePath, _localPath, _maxSharingPermissions, this);
_ui->label_icon->setPixmap(p);
}
-void ShareDialog::slotAccountStateChanged(int state) {
+void ShareDialog::slotAccountStateChanged(int state)
+{
bool enabled = (state == AccountState::State::Connected);
qCDebug(lcSharing) << "Account connected?" << enabled;
_linkWidget->setEnabled(enabled);
}
}
-
}
-
namespace OCC {
namespace Ui {
-class ShareDialog;
+ class ShareDialog;
}
class ShareLinkWidget;
public:
explicit ShareDialog(QPointer<AccountState> accountState,
- const QString &sharePath,
- const QString &localPath,
- SharePermissions maxSharingPermissions,
- QWidget *parent = 0);
+ const QString &sharePath,
+ const QString &localPath,
+ SharePermissions maxSharingPermissions,
+ QWidget *parent = 0);
~ShareDialog();
private slots:
- void done( int r );
+ void done(int r);
void slotMaxSharingPermissionsReceived(const QVariantMap &result);
void slotMaxSharingPermissionsError();
void slotThumbnailFetched(const int &statusCode, const QByteArray &reply);
void slotAccountStateChanged(int state);
private:
-
void showSharingUi();
Ui::ShareDialog *_ui;
ShareUserGroupWidget *_userGroupWidget;
QProgressIndicator *_progressIndicator;
};
-
}
#endif // SHAREDIALOG_H
Q_LOGGING_CATEGORY(lcSharing, "gui.sharing", QtInfoMsg)
Sharee::Sharee(const QString shareWith,
- const QString displayName,
- const Type type)
-: _shareWith(shareWith),
- _displayName(displayName),
- _type(type)
+ const QString displayName,
+ const Type type)
+ : _shareWith(shareWith)
+ , _displayName(displayName)
+ , _type(type)
{
}
}
ShareeModel::ShareeModel(const AccountPtr &account, const QString &type, QObject *parent)
- : QAbstractListModel(parent), _account(account), _type(type)
-{ }
+ : QAbstractListModel(parent)
+ , _account(account)
+ , _type(type)
+{
+}
void ShareeModel::fetch(const QString &search, const ShareeSet &blacklist)
{
_shareeBlacklist = blacklist;
OcsShareeJob *job = new OcsShareeJob(_account);
connect(job, SIGNAL(shareeJobFinished(QJsonDocument)), SLOT(shareesFetched(QJsonDocument)));
- connect(job, SIGNAL(ocsError(int,QString)), SIGNAL(displayErrorMessage(int,QString)));
+ connect(job, SIGNAL(ocsError(int, QString)), SIGNAL(displayErrorMessage(int, QString)));
job->getSharees(_search, _type, 1, 50);
}
auto exact = data.value("exact").toObject();
{
auto users = exact.value("users").toArray();
- foreach(auto user, users) {
+ foreach (auto user, users) {
newSharees.append(parseSharee(user.toObject()));
}
auto groups = exact.value("groups").toArray();
- foreach(auto group, groups) {
+ foreach (auto group, groups) {
newSharees.append(parseSharee(group.toObject()));
}
auto remotes = exact.value("remotes").toArray();
- foreach(auto remote, remotes) {
+ foreach (auto remote, remotes) {
newSharees.append(parseSharee(remote.toObject()));
}
}
{
auto users = data.value("users").toArray();
- foreach(auto user, users) {
+ foreach (auto user, users) {
newSharees.append(parseSharee(user.toObject()));
}
}
{
auto groups = data.value("groups").toArray();
- foreach(auto group, groups) {
+ foreach (auto group, groups) {
newSharees.append(parseSharee(group.toObject()));
}
}
{
auto remotes = data.value("remotes").toArray();
- foreach(auto remote, remotes) {
+ foreach (auto remote, remotes) {
newSharees.append(parseSharee(remote.toObject()));
}
}
// Filter sharees that we have already shared with
QVector<QSharedPointer<Sharee>> filteredSharees;
- foreach(const auto &sharee, newSharees) {
+ foreach (const auto &sharee, newSharees) {
bool found = false;
- foreach(const auto &blacklistSharee, _shareeBlacklist) {
- if (sharee->type() == blacklistSharee->type() &&
- sharee->shareWith() == blacklistSharee->shareWith()) {
+ foreach (const auto &blacklistSharee, _shareeBlacklist) {
+ if (sharee->type() == blacklistSharee->type() && sharee->shareWith() == blacklistSharee->shareWith()) {
found = true;
break;
}
// Helper function for setNewSharees (could be a lambda when we can use them)
static QSharedPointer<Sharee> shareeFromModelIndex(const QModelIndex &idx)
-{ return idx.data(Qt::UserRole).value<QSharedPointer<Sharee>>(); }
+{
+ return idx.data(Qt::UserRole).value<QSharedPointer<Sharee>>();
+}
-struct FindShareeHelper {
+struct FindShareeHelper
+{
const QSharedPointer<Sharee> &sharee;
- bool operator()(const QSharedPointer<Sharee> &s2) const {
+ bool operator()(const QSharedPointer<Sharee> &s2) const
+ {
return s2->format() == sharee->format() && s2->displayName() == sharee->format();
}
};
Do that while preserving the model index so the selection stays
*/
-void ShareeModel::setNewSharees(const QVector<QSharedPointer<Sharee>>& newSharees)
+void ShareeModel::setNewSharees(const QVector<QSharedPointer<Sharee>> &newSharees)
{
layoutAboutToBeChanged();
const auto persistent = persistentIndexList();
oldPersistantSharee.reserve(persistent.size());
std::transform(persistent.begin(), persistent.end(), std::back_inserter(oldPersistantSharee),
- shareeFromModelIndex);
+ shareeFromModelIndex);
_sharees = newSharees;
QModelIndexList newPersistant;
newPersistant.reserve(persistent.size());
- foreach(const QSharedPointer<Sharee> &sharee, oldPersistantSharee) {
+ foreach (const QSharedPointer<Sharee> &sharee, oldPersistantSharee) {
FindShareeHelper helper = { sharee };
auto it = std::find_if(_sharees.constBegin(), _sharees.constEnd(), helper);
if (it == _sharees.constEnd()) {
return QVariant();
}
- const auto & sharee = _sharees.at(index.row());
+ const auto &sharee = _sharees.at(index.row());
if (role == Qt::DisplayRole) {
return sharee->format();
} else if (role == Qt::UserRole) {
return QVariant::fromValue(sharee);
}
-
+
return QVariant();
}
-QSharedPointer<Sharee> ShareeModel::getSharee(int at) {
+QSharedPointer<Sharee> ShareeModel::getSharee(int at)
+{
if (at < 0 || at > _sharees.size()) {
return QSharedPointer<Sharee>(NULL);
}
return _sharees.at(at);
}
-
}
Q_DECLARE_LOGGING_CATEGORY(lcSharing)
-class Sharee {
+class Sharee
+{
public:
-
// Keep in sync with Share::ShareType
enum Type {
User = 0,
};
explicit Sharee(const QString shareWith,
- const QString displayName,
- const Type type);
+ const QString displayName,
+ const Type type);
QString format() const;
QString shareWith() const;
};
-class ShareeModel : public QAbstractListModel {
+class ShareeModel : public QAbstractListModel
+{
Q_OBJECT
public:
explicit ShareeModel(const AccountPtr &account, const QString &type, QObject *parent = 0);
QVector<QSharedPointer<Sharee>> _sharees;
QVector<QSharedPointer<Sharee>> _shareeBlacklist;
};
-
}
Q_DECLARE_METATYPE(QSharedPointer<OCC::Sharee>)
-#endif //SHAREE_H
+#endif //SHAREE_H
const char propertyShareC[] = "oc_share";
ShareLinkWidget::ShareLinkWidget(AccountPtr account,
- const QString &sharePath,
- const QString &localPath,
- SharePermissions maxSharingPermissions,
- QWidget *parent) :
- QWidget(parent),
- _ui(new Ui::ShareLinkWidget),
- _account(account),
- _sharePath(sharePath),
- _localPath(localPath),
- _manager(0),
- _passwordRequired(false),
- _expiryRequired(false),
- _namesSupported(true)
+ const QString &sharePath,
+ const QString &localPath,
+ SharePermissions maxSharingPermissions,
+ QWidget *parent)
+ : QWidget(parent)
+ , _ui(new Ui::ShareLinkWidget)
+ , _account(account)
+ , _sharePath(sharePath)
+ , _localPath(localPath)
+ , _manager(0)
+ , _passwordRequired(false)
+ , _expiryRequired(false)
+ , _namesSupported(true)
{
_ui->setupUi(this);
// the following progress indicator widgets are added to layouts which makes them
// automatically deleted once the dialog dies.
- _pi_create = new QProgressIndicator();
+ _pi_create = new QProgressIndicator();
_pi_password = new QProgressIndicator();
- _pi_date = new QProgressIndicator();
- _pi_editing = new QProgressIndicator();
+ _pi_date = new QProgressIndicator();
+ _pi_editing = new QProgressIndicator();
_ui->horizontalLayout_create->addWidget(_pi_create);
_ui->horizontalLayout_password->addWidget(_pi_password);
_ui->horizontalLayout_editing->addWidget(_pi_editing);
connect(_ui->nameLineEdit, SIGNAL(returnPressed()), SLOT(slotShareNameEntered()));
connect(_ui->createShareButton, SIGNAL(clicked(bool)), SLOT(slotShareNameEntered()));
connect(_ui->linkShares, SIGNAL(itemSelectionChanged()), SLOT(slotShareSelectionChanged()));
- connect(_ui->linkShares, SIGNAL(itemChanged(QTableWidgetItem*)), SLOT(slotNameEdited(QTableWidgetItem*)));
+ connect(_ui->linkShares, SIGNAL(itemChanged(QTableWidgetItem *)), SLOT(slotNameEdited(QTableWidgetItem *)));
connect(_ui->checkBox_password, SIGNAL(clicked()), this, SLOT(slotCheckBoxPasswordClicked()));
connect(_ui->lineEdit_password, SIGNAL(returnPressed()), this, SLOT(slotPasswordReturnPressed()));
connect(_ui->lineEdit_password, SIGNAL(textChanged(QString)), this, SLOT(slotPasswordChanged(QString)));
displayError(tr("Link shares have been disabled"));
_ui->nameLineEdit->setEnabled(false);
_ui->createShareButton->setEnabled(false);
- } else if ( !(maxSharingPermissions & SharePermissionShare) ) {
+ } else if (!(maxSharingPermissions & SharePermissionShare)) {
displayError(tr("The file can not be shared because it was shared without sharing permission."));
_ui->nameLineEdit->setEnabled(false);
_ui->createShareButton->setEnabled(false);
_ui->calendar->setEnabled(false);
// check if the file is already inside of a synced folder
- if( sharePath.isEmpty() ) {
+ if (sharePath.isEmpty()) {
// The file is not yet in an ownCloud synced folder. We could automatically
// copy it over, but that is skipped as not all questions can be answered that
// are involved in that, see https://github.com/owncloud/client/issues/2732
if (_account->capabilities().sharePublicLinkEnforceExpireDate()) {
_ui->checkBox_expire->setEnabled(false);
_ui->calendar->setMaximumDate(QDate::currentDate().addDays(
- _account->capabilities().sharePublicLinkExpireDateDays()
- ));
+ _account->capabilities().sharePublicLinkExpireDateDays()));
_expiryRequired = true;
}
// File can't have public upload set.
_ui->widget_editing->setVisible(!_isFile);
_ui->checkBox_editing->setEnabled(
- _account->capabilities().sharePublicLinkAllowUpload());
+ _account->capabilities().sharePublicLinkAllowUpload());
// Prepare sharing menu
connect(_manager, SIGNAL(sharesFetched(QList<QSharedPointer<Share>>)), SLOT(slotSharesFetched(QList<QSharedPointer<Share>>)));
connect(_manager, SIGNAL(linkShareCreated(QSharedPointer<LinkShare>)), SLOT(slotCreateShareFetched(const QSharedPointer<LinkShare>)));
connect(_manager, SIGNAL(linkShareRequiresPassword(QString)), SLOT(slotCreateShareRequiresPassword(QString)));
- connect(_manager, SIGNAL(serverError(int, QString)), SLOT(slotServerError(int,QString)));
+ connect(_manager, SIGNAL(serverError(int, QString)), SLOT(slotServerError(int, QString)));
}
ShareLinkWidget::~ShareLinkWidget()
table->setRowCount(0);
auto deleteIcon = QIcon::fromTheme(QLatin1String("user-trash"),
- QIcon(QLatin1String(":/client/resources/delete.png")));
+ QIcon(QLatin1String(":/client/resources/delete.png")));
foreach (auto share, shares) {
if (share->getShareType() != Share::TypeLink) {
auto linkShare = qSharedPointerDynamicCast<LinkShare>(share);
// Connect all shares signals to gui slots
- connect(share.data(), SIGNAL(serverError(int, QString)), SLOT(slotServerError(int,QString)));
+ connect(share.data(), SIGNAL(serverError(int, QString)), SLOT(slotServerError(int, QString)));
connect(share.data(), SIGNAL(shareDeleted()), SLOT(slotDeleteShareFetched()));
connect(share.data(), SIGNAL(expireDateSet()), SLOT(slotExpireSet()));
connect(share.data(), SIGNAL(publicUploadSet()), SLOT(slotPublicUploadSet()));
connect(share.data(), SIGNAL(passwordSet()), SLOT(slotPasswordSet()));
- connect(share.data(), SIGNAL(passwordSetError(int, QString)), SLOT(slotPasswordSetError(int,QString)));
+ connect(share.data(), SIGNAL(passwordSetError(int, QString)), SLOT(slotPasswordSetError(int, QString)));
// Build the table row
auto row = table->rowCount();
shareButton->setProperty(propertyShareC, QVariant::fromValue(linkShare));
shareButton->setMenu(_shareLinkMenu);
shareButton->setPopupMode(QToolButton::InstantPopup);
- connect(shareButton, SIGNAL(triggered(QAction*)), SLOT(slotShareLinkButtonTriggered(QAction*)));
+ connect(shareButton, SIGNAL(triggered(QAction *)), SLOT(slotShareLinkButtonTriggered(QAction *)));
table->setCellWidget(row, 1, shareButton);
auto deleteButton = new QToolButton;
_ui->checkBox_password->setEnabled(!_passwordRequired);
_ui->checkBox_expire->setEnabled(!_expiryRequired);
_ui->checkBox_editing->setEnabled(
- _account->capabilities().sharePublicLinkAllowUpload());
+ _account->capabilities().sharePublicLinkAllowUpload());
// Password state
_ui->checkBox_password->setText(tr("P&assword protect"));
_ui->lineEdit_password->clearFocus();
}
-void ShareLinkWidget::slotPasswordChanged(const QString& newText)
+void ShareLinkWidget::slotPasswordChanged(const QString &newText)
{
// disable the set-password button
- _ui->pushButton_setPassword->setEnabled( newText.length() > 0 );
+ _ui->pushButton_setPassword->setEnabled(newText.length() > 0);
}
-void ShareLinkWidget::slotNameEdited(QTableWidgetItem* item)
+void ShareLinkWidget::slotNameEdited(QTableWidgetItem *item)
{
if (!_namesSupported) {
return;
getShares();
}
-void ShareLinkWidget::slotCreateShareRequiresPassword(const QString& message)
+void ShareLinkWidget::slotCreateShareRequiresPassword(const QString &message)
{
// Deselect existing shares
_ui->linkShares->clearSelection();
void ShareLinkWidget::slotCheckBoxExpireClicked()
{
- if (_ui->checkBox_expire->checkState() == Qt::Checked)
- {
+ if (_ui->checkBox_expire->checkState() == Qt::Checked) {
const QDate date = QDate::currentDate().addDays(1);
setExpireDate(date);
_ui->calendar->setDate(date);
_ui->calendar->setMinimumDate(date);
_ui->calendar->setEnabled(true);
- }
- else
- {
+ } else {
setExpireDate(QDate());
_ui->calendar->setEnabled(false);
}
QString fileName = _sharePath.mid(_sharePath.lastIndexOf('/') + 1);
if (!QDesktopServices::openUrl(QUrl(QString(
- "mailto: "
- "?subject=I shared %1 with you"
- "&body=%2").arg(
- fileName,
- url.toString()),
+ "mailto: "
+ "?subject=I shared %1 with you"
+ "&body=%2")
+ .arg(
+ fileName,
+ url.toString()),
QUrl::TolerantMode))) {
QMessageBox::warning(
this,
_ui->lineEdit_password->setFocus();
}
-void ShareLinkWidget::displayError(const QString& errMsg)
+void ShareLinkWidget::displayError(const QString &errMsg)
{
- _ui->errorLabel->setText( errMsg );
+ _ui->errorLabel->setText(errMsg);
_ui->errorLabel->show();
}
-
}
namespace OCC {
namespace Ui {
-class ShareLinkWidget;
+ class ShareLinkWidget;
}
class AbstractCredentials;
public:
explicit ShareLinkWidget(AccountPtr account,
- const QString &sharePath,
- const QString &localPath,
- SharePermissions maxSharingPermissions,
- QWidget *parent = 0);
+ const QString &sharePath,
+ const QString &localPath,
+ SharePermissions maxSharingPermissions,
+ QWidget *parent = 0);
~ShareLinkWidget();
void getShares();
void slotPasswordReturnPressed();
void slotCheckBoxEditingClicked();
void slotExpireDateChanged(const QDate &date);
- void slotPasswordChanged(const QString& newText);
- void slotNameEdited(QTableWidgetItem* item);
+ void slotPasswordChanged(const QString &newText);
+ void slotNameEdited(QTableWidgetItem *item);
- void slotShareLinkButtonTriggered(QAction* action);
+ void slotShareLinkButtonTriggered(QAction *action);
void slotDeleteShareFetched();
void slotCreateShareFetched(const QSharedPointer<LinkShare> share);
- void slotCreateShareRequiresPassword(const QString& message);
+ void slotCreateShareRequiresPassword(const QString &message);
void slotPasswordSet();
void slotExpireSet();
void slotPublicUploadSet();
void slotPasswordSetError(int code, const QString &message);
private:
- void displayError(const QString& errMsg);
+ void displayError(const QString &errMsg);
void setPassword(const QString &password);
void setExpireDate(const QDate &date);
QAction *_emailLinkAction;
QAction *_emailDirectLinkAction;
};
-
}
#endif // SHARELINKWIDGET_H
namespace OCC {
Share::Share(AccountPtr account,
- const QString& id,
- const QString& path,
- const ShareType shareType,
- const Permissions permissions,
- const QSharedPointer<Sharee> shareWith)
-: _account(account),
- _id(id),
- _path(path),
- _shareType(shareType),
- _permissions(permissions),
- _shareWith(shareWith)
+ const QString &id,
+ const QString &path,
+ const ShareType shareType,
+ const Permissions permissions,
+ const QSharedPointer<Sharee> shareWith)
+ : _account(account)
+ , _id(id)
+ , _path(path)
+ , _shareType(shareType)
+ , _permissions(permissions)
+ , _shareWith(shareWith)
{
-
}
AccountPtr Share::account() const
}
LinkShare::LinkShare(AccountPtr account,
- const QString& id,
- const QString& path,
- const QString& name,
- const QString& token,
- Permissions permissions,
- bool passwordSet,
- const QUrl& url,
- const QDate& expireDate)
-: Share(account, id, path, Share::TypeLink, permissions),
- _name(name),
- _token(token),
- _passwordSet(passwordSet),
- _expireDate(expireDate),
- _url(url)
+ const QString &id,
+ const QString &path,
+ const QString &name,
+ const QString &token,
+ Permissions permissions,
+ bool passwordSet,
+ const QUrl &url,
+ const QDate &expireDate)
+ : Share(account, id, path, Share::TypeLink, permissions)
+ , _name(name)
+ , _token(token)
+ , _passwordSet(passwordSet)
+ , _expireDate(expireDate)
+ , _url(url)
{
-
}
bool LinkShare::getPublicUpload()
{
- return ((_permissions & SharePermissionUpdate) &&
- (_permissions & SharePermissionCreate));
+ return ((_permissions & SharePermissionUpdate) && (_permissions & SharePermissionCreate));
}
void LinkShare::setPublicUpload(bool publicUpload)
return _name;
}
-void LinkShare::setName(const QString& name)
+void LinkShare::setName(const QString &name)
{
OcsShareJob *job = new OcsShareJob(_account);
- connect(job, SIGNAL(shareJobFinished(QJsonDocument,QVariant)), SLOT(slotNameSet(QJsonDocument,QVariant)));
- connect(job, SIGNAL(ocsError(int,QString)), SLOT(slotOcsError(int,QString)));
+ connect(job, SIGNAL(shareJobFinished(QJsonDocument, QVariant)), SLOT(slotNameSet(QJsonDocument, QVariant)));
+ connect(job, SIGNAL(ocsError(int, QString)), SLOT(slotOcsError(int, QString)));
job->setName(getId(), name);
}
return _token;
}
-void LinkShare::slotPublicUploadSet(const QJsonDocument&, const QVariant &value)
+void LinkShare::slotPublicUploadSet(const QJsonDocument &, const QVariant &value)
{
if (value.toBool()) {
_permissions = SharePermissionRead | SharePermissionUpdate | SharePermissionCreate;
{
OcsShareJob *job = new OcsShareJob(_account);
connect(job, SIGNAL(shareJobFinished(QJsonDocument, QVariant)), SLOT(slotPasswordSet(QJsonDocument, QVariant)));
- connect(job, SIGNAL(ocsError(int, QString)), SLOT(slotSetPasswordError(int,QString)));
+ connect(job, SIGNAL(ocsError(int, QString)), SLOT(slotSetPasswordError(int, QString)));
job->setPassword(getId(), password);
}
-void LinkShare::slotPasswordSet(const QJsonDocument&, const QVariant &value)
+void LinkShare::slotPasswordSet(const QJsonDocument &, const QVariant &value)
{
_passwordSet = value.toString() == "";
emit passwordSet();
job->setExpireDate(getId(), date);
}
-void LinkShare::slotExpireDateSet(const QJsonDocument& reply, const QVariant &value)
+void LinkShare::slotExpireDateSet(const QJsonDocument &reply, const QVariant &value)
{
auto data = reply.object().value("ocs").toObject().value("data").toObject();
* they use this date.
*/
if (data.value("expiration").isString()) {
- _expireDate = QDate::fromString(data.value("expiration").toString(), "yyyy-MM-dd 00:00:00");
+ _expireDate = QDate::fromString(data.value("expiration").toString(), "yyyy-MM-dd 00:00:00");
} else {
_expireDate = value.toDate();
}
}
ShareManager::ShareManager(AccountPtr account, QObject *parent)
-: QObject(parent),
- _account(account)
+ : QObject(parent)
+ , _account(account)
{
-
}
void ShareManager::createLinkShare(const QString &path,
- const QString &name,
- const QString &password)
+ const QString &name,
+ const QString &password)
{
OcsShareJob *job = new OcsShareJob(_account);
connect(job, SIGNAL(shareJobFinished(QJsonDocument, QVariant)), SLOT(slotLinkShareCreated(QJsonDocument)));
}
-void ShareManager::createShare(const QString& path,
- const Share::ShareType shareType,
- const QString shareWith,
- const Share::Permissions permissions)
+void ShareManager::createShare(const QString &path,
+ const Share::ShareType shareType,
+ const QString shareWith,
+ const Share::Permissions permissions)
{
auto job = new OcsShareJob(_account);
continuation.permissions = permissions;
_jobContinuation[job] = QVariant::fromValue(continuation);
- connect(job, SIGNAL(shareJobFinished(QJsonDocument,QVariant)), SLOT(slotCreateShare(QJsonDocument)));
- connect(job, SIGNAL(ocsError(int,QString)), SLOT(slotOcsError(int,QString)));
+ connect(job, SIGNAL(shareJobFinished(QJsonDocument, QVariant)), SLOT(slotCreateShare(QJsonDocument)));
+ connect(job, SIGNAL(ocsError(int, QString)), SLOT(slotOcsError(int, QString)));
job->getSharedWithMe();
}
// Find existing share permissions (if this was shared with us)
Share::Permissions existingPermissions = SharePermissionDefault;
- foreach (const QJsonValue & element, reply.object()["ocs"].toObject()["data"].toArray()) {
+ foreach (const QJsonValue &element, reply.object()["ocs"].toObject()["data"].toArray()) {
auto map = element.toObject();
if (map["file_target"] == cont.path)
existingPermissions = Share::Permissions(map["permissions"].toInt());
QList<QSharedPointer<Share>> shares;
- foreach(const auto &share, tmpShares) {
+ foreach (const auto &share, tmpShares) {
auto data = share.toObject();
auto shareType = data.value("share_type").toInt();
QDate expireDate;
if (data.value("expiration").isString()) {
- expireDate = QDate::fromString(data.value("expiration").toString(), "yyyy-MM-dd 00:00:00");
+ expireDate = QDate::fromString(data.value("expiration").toString(), "yyyy-MM-dd 00:00:00");
}
return QSharedPointer<LinkShare>(new LinkShare(_account,
- data.value("id").toString(),
- data.value("path").toString(),
- data.value("name").toString(),
- data.value("token").toString(),
- (Share::Permissions)data.value("permissions").toInt(),
- data.value("share_with").isString(), // has password?
- url,
- expireDate));
+ data.value("id").toString(),
+ data.value("path").toString(),
+ data.value("name").toString(),
+ data.value("token").toString(),
+ (Share::Permissions)data.value("permissions").toInt(),
+ data.value("share_with").isString(), // has password?
+ url,
+ expireDate));
}
QSharedPointer<Share> ShareManager::parseShare(const QJsonObject &data)
{
QSharedPointer<Sharee> sharee(new Sharee(data.value("share_with").toString(),
- data.value("share_with_displayname").toString(),
- (Sharee::Type)data.value("share_type").toInt()));
+ data.value("share_with_displayname").toString(),
+ (Sharee::Type)data.value("share_type").toInt()));
return QSharedPointer<Share>(new Share(_account,
- data.value("id").toString(),
- data.value("path").toString(),
- (Share::ShareType)data.value("share_type").toInt(),
- (Share::Permissions)data.value("permissions").toInt(),
- sharee));
+ data.value("id").toString(),
+ data.value("path").toString(),
+ (Share::ShareType)data.value("share_type").toInt(),
+ (Share::Permissions)data.value("permissions").toInt(),
+ sharee));
}
void ShareManager::slotOcsError(int statusCode, const QString &message)
{
emit serverError(statusCode, message);
}
-
}
namespace OCC {
-class Share : public QObject {
+class Share : public QObject
+{
Q_OBJECT
public:
-
/**
* Possible share types
* Need to be in sync with Sharee::Type
*/
enum ShareType {
- TypeUser = Sharee::User,
- TypeGroup = Sharee::Group,
- TypeLink = 3,
+ TypeUser = Sharee::User,
+ TypeGroup = Sharee::Group,
+ TypeLink = 3,
TypeRemote = Sharee::Federated
};
* Constructor for shares
*/
explicit Share(AccountPtr account,
- const QString& id,
- const QString& path,
- const ShareType shareType,
- const Permissions permissions = SharePermissionDefault,
- const QSharedPointer<Sharee> shareWith = QSharedPointer<Sharee>(NULL));
+ const QString &id,
+ const QString &path,
+ const ShareType shareType,
+ const Permissions permissions = SharePermissionDefault,
+ const QSharedPointer<Sharee> shareWith = QSharedPointer<Sharee>(NULL));
/**
* The account the share is defined on.
private slots:
void slotDeleted();
void slotPermissionsSet(const QJsonDocument &, const QVariant &value);
-
};
/**
* There are several methods in the API that either work differently for
* link shares or are only available to link shares.
*/
-class LinkShare : public Share {
+class LinkShare : public Share
+{
Q_OBJECT
public:
-
explicit LinkShare(AccountPtr account,
- const QString& id,
- const QString& path,
- const QString& name,
- const QString& token,
- const Permissions permissions,
- bool passwordSet,
- const QUrl& url,
- const QDate& expireDate);
+ const QString &id,
+ const QString &path,
+ const QString &name,
+ const QString &token,
+ const Permissions permissions,
+ bool passwordSet,
+ const QUrl &url,
+ const QDate &expireDate);
/*
* Get the share link
*
* Emits either nameSet() or serverError().
*/
- void setName(const QString& name);
+ void setName(const QString &name);
/*
* Returns the token of the link share.
* On success the passwordSet signal is emitted
* In case of a server error the serverError signal is emitted.
*/
- void setPassword(const QString& password);
+ void setPassword(const QString &password);
/*
* Is the password set?
* On success the expireDateSet signal is emitted
* In case of a server error the serverError signal is emitted.
*/
- void setExpireDate(const QDate& expireDate);
+ void setExpireDate(const QDate &expireDate);
signals:
void expireDateSet();
void nameSet();
private slots:
- void slotPasswordSet(const QJsonDocument&, const QVariant &value);
- void slotPublicUploadSet(const QJsonDocument&, const QVariant &value);
- void slotExpireDateSet(const QJsonDocument& reply, const QVariant &value);
+ void slotPasswordSet(const QJsonDocument &, const QVariant &value);
+ void slotPublicUploadSet(const QJsonDocument &, const QVariant &value);
+ void slotExpireDateSet(const QJsonDocument &reply, const QVariant &value);
void slotSetPasswordError(int statusCode, const QString &message);
- void slotNameSet(const QJsonDocument&, const QVariant &value);
+ void slotNameSet(const QJsonDocument &, const QVariant &value);
private:
QString _name;
* of shares. It abstracts away from the OCS Share API, all the usages
* shares should talk to this manager and not use OCS Share Job directly
*/
-class ShareManager : public QObject {
+class ShareManager : public QObject
+{
Q_OBJECT
public:
explicit ShareManager(AccountPtr _account, QObject *parent = NULL);
* For older server the linkShareRequiresPassword signal is emitted when it seems appropiate
* In case of a server error the serverError signal is emitted
*/
- void createLinkShare(const QString& path,
- const QString& name,
- const QString& password);
+ void createLinkShare(const QString &path,
+ const QString &name,
+ const QString &password);
/**
* Tell the manager to create a new share
* On success the signal shareCreated is emitted
* In case of a server error the serverError signal is emitted
*/
- void createShare(const QString& path,
- const Share::ShareType shareType,
- const QString shareWith,
- const Share::Permissions permissions);
+ void createShare(const QString &path,
+ const Share::ShareType shareType,
+ const QString shareWith,
+ const Share::Permissions permissions);
/**
* Fetch all the shares for path
* On success the sharesFetched signal is emitted
* In case of a server error the serverError signal is emitted
*/
- void fetchShares(const QString& path);
+ void fetchShares(const QString &path);
signals:
void shareCreated(const QSharedPointer<Share> &share);
QSharedPointer<LinkShare> parseLinkShare(const QJsonObject &data);
QSharedPointer<Share> parseShare(const QJsonObject &data);
- QMap<QObject*, QVariant> _jobContinuation;
+ QMap<QObject *, QVariant> _jobContinuation;
AccountPtr _account;
};
-
}
#endif // SHAREMANAGER_H
* Possible permissions, must match the server permission constants
*/
enum SharePermission {
- SharePermissionRead = 1,
- SharePermissionUpdate = 2,
- SharePermissionCreate = 4,
- SharePermissionDelete = 8,
- SharePermissionShare = 16,
+ SharePermissionRead = 1,
+ SharePermissionUpdate = 2,
+ SharePermissionCreate = 4,
+ SharePermissionDelete = 8,
+ SharePermissionShare = 16,
SharePermissionDefault = 1 << 30
};
Q_DECLARE_FLAGS(SharePermissions, SharePermission)
namespace OCC {
ShareUserGroupWidget::ShareUserGroupWidget(AccountPtr account,
- const QString &sharePath,
- const QString &localPath,
- SharePermissions maxSharingPermissions,
- QWidget *parent) :
- QWidget(parent),
- _ui(new Ui::ShareUserGroupWidget),
- _account(account),
- _sharePath(sharePath),
- _localPath(localPath),
- _maxSharingPermissions(maxSharingPermissions),
- _disableCompleterActivated(false)
+ const QString &sharePath,
+ const QString &localPath,
+ SharePermissions maxSharingPermissions,
+ QWidget *parent)
+ : QWidget(parent)
+ , _ui(new Ui::ShareUserGroupWidget)
+ , _account(account)
+ , _sharePath(sharePath)
+ , _localPath(localPath)
+ , _maxSharingPermissions(maxSharingPermissions)
+ , _disableCompleterActivated(false)
{
setAttribute(Qt::WA_DeleteOnClose);
setObjectName("SharingDialogUG"); // required as group for saveGeometry call
_completer = new QCompleter(this);
_completerModel = new ShareeModel(_account,
- _isFile ? QLatin1String("file") : QLatin1String("folder"),
- _completer);
+ _isFile ? QLatin1String("file") : QLatin1String("folder"),
+ _completer);
connect(_completerModel, SIGNAL(shareesReady()), this, SLOT(slotShareesReady()));
- connect(_completerModel, SIGNAL(displayErrorMessage(int,QString)), this, SLOT(displayError(int,QString)));
+ connect(_completerModel, SIGNAL(displayErrorMessage(int, QString)), this, SLOT(displayError(int, QString)));
_completer->setModel(_completerModel);
_completer->setCaseSensitivity(Qt::CaseInsensitive);
_manager = new ShareManager(_account, this);
connect(_manager, SIGNAL(sharesFetched(QList<QSharedPointer<Share>>)), SLOT(slotSharesFetched(QList<QSharedPointer<Share>>)));
connect(_manager, SIGNAL(shareCreated(QSharedPointer<Share>)), SLOT(getShares()));
- connect(_manager, SIGNAL(serverError(int,QString)), this, SLOT(displayError(int,QString)));
+ connect(_manager, SIGNAL(serverError(int, QString)), this, SLOT(displayError(int, QString)));
connect(_ui->shareeLineEdit, SIGNAL(returnPressed()), SLOT(slotLineEditReturn()));
// By making the next two QueuedConnections we can override
// the strings the completer sets on the line edit.
connect(_completer, SIGNAL(activated(QModelIndex)), SLOT(slotCompleterActivated(QModelIndex)),
- Qt::QueuedConnection);
+ Qt::QueuedConnection);
connect(_completer, SIGNAL(highlighted(QModelIndex)), SLOT(slotCompleterHighlighted(QModelIndex)),
- Qt::QueuedConnection);
+ Qt::QueuedConnection);
// Queued connection so this signal is recieved after textChanged
connect(_ui->shareeLineEdit, SIGNAL(textEdited(QString)),
- this, SLOT(slotLineEditTextEdited(QString)), Qt::QueuedConnection);
+ this, SLOT(slotLineEditTextEdited(QString)), Qt::QueuedConnection);
connect(&_completionTimer, SIGNAL(timeout()), this, SLOT(searchForSharees()));
_completionTimer.setSingleShot(true);
_completionTimer.setInterval(600);
_completionTimer.stop();
}
-void ShareUserGroupWidget::slotLineEditTextEdited(const QString& text)
+void ShareUserGroupWidget::slotLineEditTextEdited(const QString &text)
{
_disableCompleterActivated = false;
// First textChanged is called first and we stopped the timer when the text is changed, programatically or not
for (int i = 0; i < _completerModel->rowCount(); ++i) {
const auto sharee = _completerModel->getSharee(i);
if (sharee->format() == text
- || sharee->displayName() == text
- || sharee->shareWith() == text) {
+ || sharee->displayName() == text
+ || sharee->shareWith() == text) {
slotCompleterActivated(_completerModel->index(i));
// make sure we do not send the same item twice (because return is called when we press
// return to activate an item inthe completer)
QSharedPointer<Sharee> currentUser(new Sharee(_account->credentials()->user(), "", Sharee::Type::User));
blacklist << currentUser;
- foreach (auto sw, _ui->scrollArea->findChildren<ShareUserLine*>()) {
+ foreach (auto sw, _ui->scrollArea->findChildren<ShareUserLine *>()) {
blacklist << sw->share()->getShareWith();
}
_ui->errorLabel->hide();
if (shares.isEmpty()) {
layout->addWidget(new QLabel(tr("The item is not shared with any users or groups")));
} else {
- foreach(const auto &share, shares) {
+ foreach (const auto &share, shares) {
// We don't handle link shares
if (share->getShareType() == Share::TypeLink) {
continue;
void ShareUserGroupWidget::slotAdjustScrollWidgetSize()
{
QScrollArea *scrollArea = _ui->scrollArea;
- if (scrollArea->findChildren<ShareUserLine*>().count() <= 3) {
+ if (scrollArea->findChildren<ShareUserLine *>().count() <= 3) {
auto minimumSize = scrollArea->widget()->sizeHint();
auto spacing = scrollArea->widget()->layout()->spacing();
minimumSize.rwidth() += spacing;
_completer->complete();
}
-void ShareUserGroupWidget::slotCompleterActivated(const QModelIndex & index)
+void ShareUserGroupWidget::slotCompleterActivated(const QModelIndex &index)
{
if (_disableCompleterActivated)
return;
* Add spinner to the bottom of the widget list
*/
auto viewPort = _ui->scrollArea->widget();
- auto layout = qobject_cast<QVBoxLayout*>(viewPort->layout());
+ auto layout = qobject_cast<QVBoxLayout *>(viewPort->layout());
auto indicator = new QProgressIndicator(viewPort);
indicator->startAnimation();
if (layout->count() == 1) {
* https://github.com/owncloud/client/issues/4996
*/
if (sharee->type() == Sharee::Federated
- && _account->serverVersionInt() < Account::makeServerVersion(9, 1, 0)) {
+ && _account->serverVersionInt() < Account::makeServerVersion(9, 1, 0)) {
int permissions = SharePermissionRead | SharePermissionUpdate;
if (!_isFile) {
permissions |= SharePermissionCreate | SharePermissionDelete;
}
_manager->createShare(_sharePath, Share::ShareType(sharee->type()),
- sharee->shareWith(), SharePermission(permissions));
+ sharee->shareWith(), SharePermission(permissions));
} else {
_manager->createShare(_sharePath, Share::ShareType(sharee->type()),
- sharee->shareWith(), SharePermissionDefault);
+ sharee->shareWith(), SharePermissionDefault);
}
_ui->shareeLineEdit->setEnabled(false);
_ui->shareeLineEdit->setText(QString());
}
-void ShareUserGroupWidget::slotCompleterHighlighted(const QModelIndex & index)
+void ShareUserGroupWidget::slotCompleterHighlighted(const QModelIndex &index)
{
// By default the completer would set the text to EditRole,
// override that here.
_ui->shareeLineEdit->setText(index.data(Qt::DisplayRole).toString());
}
-void ShareUserGroupWidget::displayError(int code, const QString& message)
+void ShareUserGroupWidget::displayError(int code, const QString &message)
{
_pi_sharee.stopAnimation();
// Also remove the spinner in the widget list, if any
- foreach (auto pi, _ui->scrollArea->findChildren<QProgressIndicator*>()) {
+ foreach (auto pi, _ui->scrollArea->findChildren<QProgressIndicator *>()) {
delete pi;
}
}
ShareUserLine::ShareUserLine(QSharedPointer<Share> share,
- SharePermissions maxSharingPermissions,
- bool isFile,
- QWidget *parent) :
- QWidget(parent),
- _ui(new Ui::ShareUserLine),
- _share(share),
- _isFile(isFile)
+ SharePermissions maxSharingPermissions,
+ bool isFile,
+ QWidget *parent)
+ : QWidget(parent)
+ , _ui(new Ui::ShareUserLine)
+ , _share(share)
+ , _isFile(isFile)
{
_ui->setupUi(this);
_ui->sharedWith->setText(share->getShareWith()->format());
-
+
// Create detailed permissions menu
QMenu *menu = new QMenu(this);
_permissionCreate = new QAction(tr("create"), this);
_ui->permissionShare->setEnabled(maxSharingPermissions & SharePermissionShare);
_ui->permissionsEdit->setEnabled(maxSharingPermissions
- & (SharePermissionCreate | SharePermissionUpdate | SharePermissionDelete));
+ & (SharePermissionCreate | SharePermissionUpdate | SharePermissionDelete));
connect(_permissionUpdate, SIGNAL(triggered(bool)), SLOT(slotPermissionsChanged()));
connect(_permissionCreate, SIGNAL(triggered(bool)), SLOT(slotPermissionsChanged()));
connect(_permissionDelete, SIGNAL(triggered(bool)), SLOT(slotPermissionsChanged()));
- connect(_ui->permissionShare, SIGNAL(clicked(bool)), SLOT(slotPermissionsChanged()));
- connect(_ui->permissionsEdit, SIGNAL(clicked(bool)), SLOT(slotEditPermissionsChanged()));
+ connect(_ui->permissionShare, SIGNAL(clicked(bool)), SLOT(slotPermissionsChanged()));
+ connect(_ui->permissionsEdit, SIGNAL(clicked(bool)), SLOT(slotEditPermissionsChanged()));
/*
* We don't show permssion share for federated shares with server <9.1
* https://github.com/owncloud/client/issues/4996
*/
if (share->getShareType() == Share::TypeRemote
- && share->account()->serverVersionInt() < Account::makeServerVersion(9, 1, 0)) {
+ && share->account()->serverVersionInt() < Account::makeServerVersion(9, 1, 0)) {
_ui->permissionShare->setVisible(false);
_ui->permissionToolButton->setVisible(false);
}
connect(share.data(), SIGNAL(shareDeleted()), SLOT(slotShareDeleted()));
_ui->deleteShareButton->setIcon(QIcon::fromTheme(QLatin1String("user-trash"),
- QIcon(QLatin1String(":/client/resources/delete.png"))));
+ QIcon(QLatin1String(":/client/resources/delete.png"))));
if (!share->account()->capabilities().shareResharing()) {
_ui->permissionShare->hide();
void ShareUserLine::slotPermissionsChanged()
{
setEnabled(false);
-
+
Share::Permissions permissions = SharePermissionRead;
if (_permissionUpdate->isChecked()) {
// There is a painting bug where a small line of this widget isn't
// properly cleared. This explicit repaint() call makes sure any trace of
// the share widget is removed once it's destroyed. #4189
- connect(this, SIGNAL(destroyed(QObject*)), parentWidget(), SLOT(repaint()));
+ connect(this, SIGNAL(destroyed(QObject *)), parentWidget(), SLOT(repaint()));
}
void ShareUserLine::slotShareDeleted()
}
if (perm & SharePermissionUpdate
- && (_isFile
- || (perm & SharePermissionCreate
- && perm & SharePermissionDelete))) {
+ && (_isFile
+ || (perm & SharePermissionCreate
+ && perm & SharePermissionDelete))) {
_ui->permissionsEdit->setCheckState(Qt::Checked);
} else if (perm & (SharePermissionUpdate | SharePermissionCreate | SharePermissionDelete)) {
_ui->permissionsEdit->setCheckState(Qt::PartiallyChecked);
_ui->permissionShare->setCheckState(Qt::Checked);
}
}
-
}
namespace OCC {
namespace Ui {
-class ShareUserGroupWidget;
-class ShareUserLine;
+ class ShareUserGroupWidget;
+ class ShareUserLine;
}
class AbstractCredentials;
Q_OBJECT
public:
- explicit ShareUserGroupWidget(AccountPtr account,
- const QString &sharePath,
- const QString &localPath,
- SharePermissions maxSharingPermissions,
- QWidget *parent = 0);
+ explicit ShareUserGroupWidget(AccountPtr account,
+ const QString &sharePath,
+ const QString &localPath,
+ SharePermissions maxSharingPermissions,
+ QWidget *parent = 0);
~ShareUserGroupWidget();
public slots:
void slotLineEditTextEdited(const QString &text);
void slotLineEditReturn();
- void slotCompleterActivated(const QModelIndex & index);
- void slotCompleterHighlighted(const QModelIndex & index);
+ void slotCompleterActivated(const QModelIndex &index);
+ void slotCompleterHighlighted(const QModelIndex &index);
void slotShareesReady();
void slotAdjustScrollWidgetSize();
- void displayError(int code ,const QString &message);
+ void displayError(int code, const QString &message);
private:
Ui::ShareUserGroupWidget *_ui;
public:
explicit ShareUserLine(QSharedPointer<Share> Share,
- SharePermissions maxSharingPermissions,
- bool isFile,
- QWidget *parent = 0);
+ SharePermissions maxSharingPermissions,
+ bool isFile,
+ QWidget *parent = 0);
~ShareUserLine();
QSharedPointer<Share> share() const;
void slotShareDeleted();
void slotPermissionsSet();
+
private:
void displayPermissions();
QAction *_permissionUpdate;
QAction *_permissionDelete;
};
-
}
#endif // SHAREUSERGROUPWIDGET_H
static inline QString removeTrailingSlash(QString path)
{
Q_ASSERT(path.endsWith(QLatin1Char('/')));
- path.truncate(path.length()-1);
+ path.truncate(path.length() - 1);
return path;
}
-static QString buildMessage(const QString& verb, const QString &path, const QString &status = QString::null )
+static QString buildMessage(const QString &verb, const QString &path, const QString &status = QString::null)
{
QString msg(verb);
- if( !status.isEmpty() ) {
+ if (!status.isEmpty()) {
msg.append(QLatin1Char(':'));
msg.append(status);
}
- if( !path.isEmpty() ) {
+ if (!path.isEmpty()) {
msg.append(QLatin1Char(':'));
QFileInfo fi(path);
msg.append(QDir::toNativeSeparators(fi.absoluteFilePath()));
Q_LOGGING_CATEGORY(lcSocketApi, "gui.socketapi", QtInfoMsg)
-class BloomFilter {
+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.
const static int NumBits = 1024;
public:
- BloomFilter() : hashBits(NumBits) { }
+ BloomFilter()
+ : hashBits(NumBits)
+ {
+ }
- void storeHash(uint hash) {
+ void storeHash(uint hash)
+ {
hashBits.setBit((hash & 0xFFFF) % NumBits);
hashBits.setBit((hash >> 16) % NumBits);
}
- bool isHashMaybeStored(uint hash) const {
+ bool isHashMaybeStored(uint hash) const
+ {
return hashBits.testBit((hash & 0xFFFF) % NumBits)
&& hashBits.testBit((hash >> 16) % NumBits);
}
QBitArray hashBits;
};
-class SocketListener {
+class SocketListener
+{
public:
- QIODevice* socket;
+ QIODevice *socket;
- SocketListener(QIODevice* socket = 0) : socket(socket) { }
+ SocketListener(QIODevice *socket = 0)
+ : socket(socket)
+ {
+ }
- void sendMessage(const QString& message, bool doWait = false) const
+ void sendMessage(const QString &message, bool doWait = false) const
{
qCInfo(lcSocketApi) << "Sending SocketAPI message: " << message << "to" << socket;
QString localMessage = message;
- if( ! localMessage.endsWith(QLatin1Char('\n'))) {
+ if (!localMessage.endsWith(QLatin1Char('\n'))) {
localMessage.append(QLatin1Char('\n'));
}
QByteArray bytesToSend = localMessage.toUtf8();
qint64 sent = socket->write(bytesToSend);
- if( doWait ) {
+ if (doWait) {
socket->waitForBytesWritten(1000);
}
- if( sent != bytesToSend.length() ) {
+ if (sent != bytesToSend.length()) {
qCWarning(lcSocketApi) << "Could not send all data on socket for " << localMessage;
}
-
}
- void sendMessageIfDirectoryMonitored(const QString& message, uint systemDirectoryHash) const
+ void sendMessageIfDirectoryMonitored(const QString &message, uint systemDirectoryHash) const
{
if (_monitoredDirectoriesBloomFilter.isHashMaybeStored(systemDirectoryHash))
sendMessage(message, false);
{
_monitoredDirectoriesBloomFilter.storeHash(systemDirectoryHash);
}
+
private:
BloomFilter _monitoredDirectoriesBloomFilter;
};
-struct ListenerHasSocketPred {
+struct ListenerHasSocketPred
+{
QIODevice *socket;
- ListenerHasSocketPred(QIODevice *socket) : socket(socket) { }
+ ListenerHasSocketPred(QIODevice *socket)
+ : socket(socket)
+ {
+ }
bool operator()(const SocketListener &listener) const { return listener.socket == socket; }
};
-SocketApi::SocketApi(QObject* parent)
+SocketApi::SocketApi(QObject *parent)
: QObject(parent)
{
QString socketPath;
if (Utility::isWindows()) {
socketPath = QLatin1String("\\\\.\\pipe\\")
- + QLatin1String("ownCloud-")
- + QString::fromLocal8Bit(qgetenv("USERNAME"));
+ + QLatin1String("ownCloud-")
+ + QString::fromLocal8Bit(qgetenv("USERNAME"));
// TODO: once the windows extension supports multiple
// client connections, switch back to the theme name
// See issue #2388
// Example for developer builds (with ad-hoc signing identity): "" "com.owncloud.desktopclient" ".socketApi"
// Example for official signed packages: "9B5WD74GWJ." "com.owncloud.desktopclient" ".socketApi"
socketPath = SOCKETAPI_TEAM_IDENTIFIER_PREFIX APPLICATION_REV_DOMAIN ".socketApi";
- } else if( Utility::isLinux() || Utility::isBSD() ) {
+ } else if (Utility::isLinux() || Utility::isBSD()) {
QString runtimeDir;
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
runtimeDir = QStandardPaths::writableLocation(QStandardPaths::RuntimeLocation);
#endif
socketPath = runtimeDir + "/" + Theme::instance()->appName() + "/socket";
} else {
- qCWarning(lcSocketApi) << "An unexpected system detected, this probably won't work.";
+ qCWarning(lcSocketApi) << "An unexpected system detected, this probably won't work.";
}
SocketApiServer::removeServer(socketPath);
if (!info.dir().exists()) {
bool result = info.dir().mkpath(".");
qCDebug(lcSocketApi) << "creating" << info.dir().path() << result;
- if( result ) {
+ if (result) {
QFile::setPermissions(socketPath,
- QFile::Permissions(QFile::ReadOwner+QFile::WriteOwner+QFile::ExeOwner));
+ QFile::Permissions(QFile::ReadOwner + QFile::WriteOwner + QFile::ExeOwner));
}
}
- if(!_localServer.listen(socketPath)) {
+ if (!_localServer.listen(socketPath)) {
qCWarning(lcSocketApi) << "can't start server" << socketPath;
} else {
qCInfo(lcSocketApi) << "server started, listening at " << socketPath;
connect(&_localServer, SIGNAL(newConnection()), this, SLOT(slotNewConnection()));
// folder watcher
- connect(FolderMan::instance(), SIGNAL(folderSyncStateChange(Folder*)), this, SLOT(slotUpdateFolderView(Folder*)));
+ connect(FolderMan::instance(), SIGNAL(folderSyncStateChange(Folder *)), this, SLOT(slotUpdateFolderView(Folder *)));
}
SocketApi::~SocketApi()
void SocketApi::slotNewConnection()
{
- QIODevice* socket = _localServer.nextPendingConnection();
+ QIODevice *socket = _localServer.nextPendingConnection();
- if( ! socket ) {
+ if (!socket) {
return;
}
qCInfo(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*)));
+ connect(socket, SIGNAL(destroyed(QObject *)), this, SLOT(slotSocketDestroyed(QObject *)));
ASSERT(socket->readAll().isEmpty());
_listeners.append(SocketListener(socket));
SocketListener &listener = _listeners.last();
- foreach( Folder *f, FolderMan::instance()->map() ) {
+ foreach (Folder *f, FolderMan::instance()->map()) {
if (f->canSync()) {
QString message = buildRegisterPathMessage(removeTrailingSlash(f->path()));
listener.sendMessage(message);
sender()->deleteLater();
}
-void SocketApi::slotSocketDestroyed(QObject* obj)
+void SocketApi::slotSocketDestroyed(QObject *obj)
{
- QIODevice* socket = static_cast<QIODevice*>(obj);
+ QIODevice *socket = static_cast<QIODevice *>(obj);
_listeners.erase(std::remove_if(_listeners.begin(), _listeners.end(), ListenerHasSocketPred(socket)), _listeners.end());
}
void SocketApi::slotReadSocket()
{
- QIODevice* socket = qobject_cast<QIODevice*>(sender());
+ QIODevice *socket = qobject_cast<QIODevice *>(sender());
ASSERT(socket);
SocketListener *listener = &*std::find_if(_listeners.begin(), _listeners.end(), ListenerHasSocketPred(socket));
- while(socket->canReadLine()) {
+ while (socket->canReadLine()) {
// Make sure to normalize the input from the socket to
// make sure that the path will match, especially on OS X.
QString line = QString::fromUtf8(socket->readLine()).normalized(QString::NormalizationForm_C);
QByteArray functionWithArguments = "command_" + command + "(QString,SocketListener*)";
int indexOfMethod = staticMetaObject.indexOfMethod(functionWithArguments);
- QString argument = line.remove(0, command.length()+1);
- if(indexOfMethod != -1) {
- staticMetaObject.method(indexOfMethod).invoke(this, Q_ARG(QString, argument), Q_ARG(SocketListener*, listener));
+ QString argument = line.remove(0, command.length() + 1);
+ if (indexOfMethod != -1) {
+ staticMetaObject.method(indexOfMethod).invoke(this, Q_ARG(QString, argument), Q_ARG(SocketListener *, listener));
} else {
qCWarning(lcSocketApi) << "The command is not supported by this version of the client:" << command << "with argument:" << argument;
}
}
}
-void SocketApi::slotRegisterPath( const QString& alias )
+void SocketApi::slotRegisterPath(const QString &alias)
{
// Make sure not to register twice to each connected client
if (_registeredAliases.contains(alias))
_registeredAliases.insert(alias);
}
-void SocketApi::slotUnregisterPath( const QString& alias )
+void SocketApi::slotUnregisterPath(const QString &alias)
{
if (!_registeredAliases.contains(alias))
return;
if (f) {
// do only send UPDATE_VIEW for a couple of status
- if( f->syncResult().status() == SyncResult::SyncPrepare
- || f->syncResult().status() == SyncResult::Success
- || f->syncResult().status() == SyncResult::Paused
- || f->syncResult().status() == SyncResult::Problem
- || f->syncResult().status() == SyncResult::Error
- || f->syncResult().status() == SyncResult::SetupError ) {
-
+ if (f->syncResult().status() == SyncResult::SyncPrepare
+ || f->syncResult().status() == SyncResult::Success
+ || f->syncResult().status() == SyncResult::Paused
+ || f->syncResult().status() == SyncResult::Problem
+ || f->syncResult().status() == SyncResult::Error
+ || f->syncResult().status() == SyncResult::SetupError) {
QString rootPath = removeTrailingSlash(f->path());
broadcastStatusPushMessage(rootPath, f->syncEngine().syncFileStatusTracker().fileStatus(""));
}
}
-void SocketApi::broadcastMessage(const QString& msg, bool doWait)
+void SocketApi::broadcastMessage(const QString &msg, bool doWait)
{
foreach (auto &listener, _listeners) {
listener.sendMessage(msg, doWait);
}
}
-void SocketApi::broadcastStatusPushMessage(const QString& systemPath, SyncFileStatus fileStatus)
+void SocketApi::broadcastStatusPushMessage(const QString &systemPath, SyncFileStatus fileStatus)
{
QString msg = buildMessage(QLatin1String("STATUS"), systemPath, fileStatus.toSocketAPIString());
Q_ASSERT(!systemPath.endsWith('/'));
}
}
-void SocketApi::command_RETRIEVE_FOLDER_STATUS(const QString& argument, SocketListener* listener)
+void SocketApi::command_RETRIEVE_FOLDER_STATUS(const QString &argument, SocketListener *listener)
{
// This command is the same as RETRIEVE_FILE_STATUS
command_RETRIEVE_FILE_STATUS(argument, listener);
}
-void SocketApi::command_RETRIEVE_FILE_STATUS(const QString& argument, SocketListener* listener)
+void SocketApi::command_RETRIEVE_FILE_STATUS(const QString &argument, SocketListener *listener)
{
qCDebug(lcSocketApi) << argument;
QString statusString;
- Folder* syncFolder = FolderMan::instance()->folderForPath( argument );
+ Folder *syncFolder = FolderMan::instance()->folderForPath(argument);
if (!syncFolder) {
// this can happen in offline mode e.g.: nothing to worry about
statusString = QLatin1String("NOP");
} else {
QString systemPath = QDir::cleanPath(argument);
- if( systemPath.endsWith(QLatin1Char('/')) ) {
- systemPath.truncate(systemPath.length()-1);
+ if (systemPath.endsWith(QLatin1Char('/'))) {
+ systemPath.truncate(systemPath.length() - 1);
qCWarning(lcSocketApi) << "Removed trailing slash for directory: " << systemPath << "Status pushes won't have one.";
}
// The user probably visited this directory in the file shell.
QString directory = systemPath.left(systemPath.lastIndexOf('/'));
listener->registerMonitoredDirectory(qHash(directory));
- QString relativePath = systemPath.mid(syncFolder->cleanPath().length()+1);
+ QString relativePath = systemPath.mid(syncFolder->cleanPath().length() + 1);
SyncFileStatus fileStatus = syncFolder->syncEngine().syncFileStatusTracker().fileStatus(relativePath);
statusString = fileStatus.toSocketAPIString();
}
- const QString message = QLatin1String("STATUS:") % statusString % QLatin1Char(':') % QDir::toNativeSeparators(argument);
+ const QString message = QLatin1String("STATUS:") % statusString % QLatin1Char(':') % QDir::toNativeSeparators(argument);
listener->sendMessage(message);
}
-void SocketApi::command_SHARE(const QString& localFile, SocketListener* listener)
+void SocketApi::command_SHARE(const QString &localFile, SocketListener *listener)
{
qCDebug(lcSocketApi) << localFile;
Folder *shareFolder = FolderMan::instance()->folderForPath(localFile);
if (!shareFolder) {
- const QString message = QLatin1String("SHARE:NOP:")+QDir::toNativeSeparators(localFile);
+ const QString message = QLatin1String("SHARE:NOP:") + QDir::toNativeSeparators(localFile);
// files that are not within a sync folder are not synced.
listener->sendMessage(message);
} else if (!shareFolder->accountState()->isConnected()) {
- const QString message = QLatin1String("SHARE:NOTCONNECTED:")+QDir::toNativeSeparators(localFile);
+ const QString message = QLatin1String("SHARE:NOTCONNECTED:") + QDir::toNativeSeparators(localFile);
// if the folder isn't connected, don't open the share dialog
listener->sendMessage(message);
- } else if (!theme->linkSharing() && (
- !theme->userGroupSharing() ||
- shareFolder->accountState()->account()->serverVersionInt() < Account::makeServerVersion(8, 2, 0))) {
- const QString message = QLatin1String("SHARE:NOP:")+QDir::toNativeSeparators(localFile);
+ } else if (!theme->linkSharing() && (!theme->userGroupSharing() || shareFolder->accountState()->account()->serverVersionInt() < Account::makeServerVersion(8, 2, 0))) {
+ const QString message = QLatin1String("SHARE:NOP:") + QDir::toNativeSeparators(localFile);
listener->sendMessage(message);
} else {
const QString localFileClean = QDir::cleanPath(localFile);
- const QString file = localFileClean.mid(shareFolder->cleanPath().length()+1);
+ const QString file = localFileClean.mid(shareFolder->cleanPath().length() + 1);
SyncFileStatus fileStatus = shareFolder->syncEngine().syncFileStatusTracker().fileStatus(file);
// Verify the file is on the server (to our knowledge of course)
if (fileStatus.tag() != SyncFileStatus::StatusUpToDate) {
- const QString message = QLatin1String("SHARE:NOTSYNCED:")+QDir::toNativeSeparators(localFile);
+ const QString message = QLatin1String("SHARE:NOTSYNCED:") + QDir::toNativeSeparators(localFile);
listener->sendMessage(message);
return;
}
// Can't share root folder
if (remotePath == "/") {
- const QString message = QLatin1String("SHARE:CANNOTSHAREROOT:")+QDir::toNativeSeparators(localFile);
+ const QString message = QLatin1String("SHARE:CANNOTSHAREROOT:") + QDir::toNativeSeparators(localFile);
listener->sendMessage(message);
return;
}
SyncJournalFileRecord rec = shareFolder->journalDb()->getFileRecord(localFileClean);
bool allowReshare = true; // lets assume the good
- if( rec.isValid() ) {
+ if (rec.isValid()) {
// check the permission: Is resharing allowed?
- if( !rec._remotePerm.contains('R') ) {
+ if (!rec._remotePerm.contains('R')) {
allowReshare = false;
}
}
- const QString message = QLatin1String("SHARE:OK:")+QDir::toNativeSeparators(localFile);
+ const QString message = QLatin1String("SHARE:OK:") + QDir::toNativeSeparators(localFile);
listener->sendMessage(message);
emit shareCommandReceived(remotePath, localFileClean, allowReshare);
}
}
-void SocketApi::command_VERSION(const QString&, SocketListener* listener)
+void SocketApi::command_VERSION(const QString &, SocketListener *listener)
{
listener->sendMessage(QLatin1String("VERSION:" MIRALL_VERSION_STRING ":" MIRALL_SOCKET_API_VERSION));
}
-void SocketApi::command_SHARE_STATUS(const QString &localFile, SocketListener* listener)
+void SocketApi::command_SHARE_STATUS(const QString &localFile, SocketListener *listener)
{
qCDebug(lcSocketApi) << localFile;
Folder *shareFolder = FolderMan::instance()->folderForPath(localFile);
if (!shareFolder) {
- const QString message = QLatin1String("SHARE_STATUS:NOP:")+QDir::toNativeSeparators(localFile);
+ const QString message = QLatin1String("SHARE_STATUS:NOP:") + QDir::toNativeSeparators(localFile);
listener->sendMessage(message);
} else {
- const QString file = QDir::cleanPath(localFile).mid(shareFolder->cleanPath().length()+1);
+ const QString file = QDir::cleanPath(localFile).mid(shareFolder->cleanPath().length() + 1);
SyncFileStatus fileStatus = shareFolder->syncEngine().syncFileStatusTracker().fileStatus(file);
// Verify the file is on the server (to our knowledge of course)
if (fileStatus.tag() != SyncFileStatus::StatusUpToDate) {
- const QString message = QLatin1String("SHARE_STATUS:NOTSYNCED:")+QDir::toNativeSeparators(localFile);
+ const QString message = QLatin1String("SHARE_STATUS:NOTSYNCED:") + QDir::toNativeSeparators(localFile);
listener->sendMessage(message);
return;
}
const Capabilities capabilities = shareFolder->accountState()->account()->capabilities();
if (!capabilities.shareAPI()) {
- const QString message = QLatin1String("SHARE_STATUS:DISABLED:")+QDir::toNativeSeparators(localFile);
+ const QString message = QLatin1String("SHARE_STATUS:DISABLED:") + QDir::toNativeSeparators(localFile);
listener->sendMessage(message);
} else {
auto theme = Theme::instance();
}
}
-void SocketApi::command_SHARE_MENU_TITLE(const QString &, SocketListener* listener)
+void SocketApi::command_SHARE_MENU_TITLE(const QString &, SocketListener *listener)
{
listener->sendMessage(QLatin1String("SHARE_MENU_TITLE:") + tr("Share with %1", "parameter is ownCloud").arg(Theme::instance()->appNameGUI()));
}
-QString SocketApi::buildRegisterPathMessage(const QString& path)
+QString SocketApi::buildRegisterPathMessage(const QString &path)
{
QFileInfo fi(path);
QString message = QLatin1String("REGISTER_PATH:");
*/
class SocketApi : public QObject
{
-Q_OBJECT
+ Q_OBJECT
public:
- explicit SocketApi(QObject* parent = 0);
+ explicit SocketApi(QObject *parent = 0);
virtual ~SocketApi();
public slots:
void slotUpdateFolderView(Folder *f);
- void slotUnregisterPath( const QString& alias );
- void slotRegisterPath( const QString& alias );
+ void slotUnregisterPath(const QString &alias);
+ void slotRegisterPath(const QString &alias);
signals:
void shareCommandReceived(const QString &sharePath, const QString &localPath, bool resharingAllowed);
private slots:
void slotNewConnection();
void onLostConnection();
- void slotSocketDestroyed(QObject* obj);
+ void slotSocketDestroyed(QObject *obj);
void slotReadSocket();
- void broadcastStatusPushMessage(const QString& systemPath, SyncFileStatus fileStatus);
+ void broadcastStatusPushMessage(const QString &systemPath, SyncFileStatus fileStatus);
private:
- void broadcastMessage(const QString& msg, bool doWait = false);
+ void broadcastMessage(const QString &msg, bool doWait = false);
- Q_INVOKABLE void command_RETRIEVE_FOLDER_STATUS(const QString& argument, SocketListener* listener);
- Q_INVOKABLE void command_RETRIEVE_FILE_STATUS(const QString& argument, SocketListener* listener);
- Q_INVOKABLE void command_SHARE(const QString& localFile, SocketListener* listener);
+ Q_INVOKABLE void command_RETRIEVE_FOLDER_STATUS(const QString &argument, SocketListener *listener);
+ Q_INVOKABLE void command_RETRIEVE_FILE_STATUS(const QString &argument, SocketListener *listener);
+ Q_INVOKABLE void command_SHARE(const QString &localFile, SocketListener *listener);
- Q_INVOKABLE void command_VERSION(const QString& argument, SocketListener* listener);
+ Q_INVOKABLE void command_VERSION(const QString &argument, SocketListener *listener);
- Q_INVOKABLE void command_SHARE_STATUS(const QString& localFile, SocketListener* listener);
- Q_INVOKABLE void command_SHARE_MENU_TITLE(const QString& argument, SocketListener* listener);
- QString buildRegisterPathMessage(const QString& path);
+ Q_INVOKABLE void command_SHARE_STATUS(const QString &localFile, SocketListener *listener);
+ Q_INVOKABLE void command_SHARE_MENU_TITLE(const QString &argument, SocketListener *listener);
+ QString buildRegisterPathMessage(const QString &path);
QSet<QString> _registeredAliases;
QList<SocketListener> _listeners;
SocketApiServer _localServer;
};
-
}
#endif // SOCKETAPI_H
Q_LOGGING_CATEGORY(lcSsl, "gui.ssl", QtInfoMsg)
-SslButton::SslButton(QWidget *parent) :
- QToolButton(parent)
+SslButton::SslButton(QWidget *parent)
+ : QToolButton(parent)
{
setPopupMode(QToolButton::InstantPopup);
setAutoRaise(true);
_menu = new QMenu(this);
QObject::connect(_menu, SIGNAL(aboutToShow()),
- this, SLOT(slotUpdateMenu()));
+ this, SLOT(slotUpdateMenu()));
}
QString SslButton::protoToString(QSsl::SslProtocol proto)
{
- switch(proto) {
+ switch (proto) {
break;
case QSsl::SslV2:
return QLatin1String("SSL v2");
static bool isSelfSigned(const QSslCertificate &certificate)
{
return certificate.issuerInfo(QSslCertificate::CommonName) == certificate.subjectInfo(QSslCertificate::CommonName)
- && certificate.issuerInfo(QSslCertificate::OrganizationalUnitName) == certificate.subjectInfo(QSslCertificate::OrganizationalUnitName);
+ && certificate.issuerInfo(QSslCertificate::OrganizationalUnitName) == certificate.subjectInfo(QSslCertificate::OrganizationalUnitName);
}
-QMenu* SslButton::buildCertMenu(QMenu *parent, const QSslCertificate& cert,
- const QList<QSslCertificate>& userApproved, int pos)
+QMenu *SslButton::buildCertMenu(QMenu *parent, const QSslCertificate &cert,
+ const QList<QSslCertificate> &userApproved, int pos)
{
QString cn = QStringList(cert.subjectInfo(QSslCertificate::CommonName)).join(QChar(';'));
QString ou = QStringList(cert.subjectInfo(QSslCertificate::OrganizationalUnitName)).join(QChar(';'));
#else
QByteArray sha265hash = cert.digest(QCryptographicHash::Sha256).toHex();
QString sha256escaped =
- Utility::escape(Utility::formatFingerprint(sha265hash.left(sha265hash.length()/2), false))
- + QLatin1String("<br/>")
- + Utility::escape(Utility::formatFingerprint(sha265hash.mid(sha265hash.length()/2), false));
+ Utility::escape(Utility::formatFingerprint(sha265hash.left(sha265hash.length() / 2), false))
+ + QLatin1String("<br/>")
+ + Utility::escape(Utility::formatFingerprint(sha265hash.mid(sha265hash.length() / 2), false));
#endif
QString serial = QString::fromUtf8(cert.serialNumber());
QString effectiveDate = cert.effectiveDate().date().toString();
stream << QLatin1String("<table>");
stream << addCertDetailsField(tr("Common Name (CN):"), Utility::escape(cn));
- stream << addCertDetailsField(tr("Subject Alternative Names:"), Utility::escape(sna)
- .replace(" ", "<br/>"));
+ stream << addCertDetailsField(tr("Subject Alternative Names:"), Utility::escape(sna).replace(" ", "<br/>"));
stream << addCertDetailsField(tr("Organization (O):"), Utility::escape(org));
stream << addCertDetailsField(tr("Organizational Unit (OU):"), Utility::escape(ou));
stream << addCertDetailsField(tr("State/Province:"), Utility::escape(state));
QString txt;
if (pos > 0) {
- txt += QString(2*pos, ' ');
+ txt += QString(2 * pos, ' ');
if (!Utility::isWindows()) {
// doesn't seem to work reliably on Windows
txt += QChar(0x21AA); // nicer '->' symbol
menu->addAction(action);
return menu;
-
}
void SslButton::updateAccountState(AccountState *accountState)
}
}
-void SslButton::slotUpdateMenu() {
+void SslButton::slotUpdateMenu()
+{
_menu->clear();
if (!_accountState) {
if (account->url().scheme() == QLatin1String("https")) {
QString sslVersion = account->_sessionCipher.protocolString()
- + ", " + account->_sessionCipher.authenticationMethod()
- + ", " + account->_sessionCipher.keyExchangeMethod()
- + ", " + account->_sessionCipher.encryptionMethod();
+ + ", " + account->_sessionCipher.authenticationMethod()
+ + ", " + account->_sessionCipher.keyExchangeMethod()
+ + ", " + account->_sessionCipher.encryptionMethod();
_menu->addAction(sslVersion)->setEnabled(false);
#if QT_VERSION > QT_VERSION_CHECK(5, 2, 0)
_menu->addAction(tr("Certificate information:"))->setEnabled(false);
QList<QSslCertificate> tmpChain;
- foreach(QSslCertificate cert, chain) {
+ foreach (QSslCertificate cert, chain) {
tmpChain << cert;
if (QSslSocket::systemCaCertificates().contains(cert))
break;
chain = tmpChain;
// find trust anchor (informational only, verification is done by QSslSocket!)
- foreach(QSslCertificate rootCA, QSslSocket::systemCaCertificates()) {
+ foreach (QSslCertificate rootCA, QSslSocket::systemCaCertificates()) {
if (rootCA.issuerInfo(QSslCertificate::CommonName) == chain.last().issuerInfo(QSslCertificate::CommonName)
- && rootCA.issuerInfo(QSslCertificate::Organization) == chain.last().issuerInfo(QSslCertificate::Organization)) {
+ && rootCA.issuerInfo(QSslCertificate::Organization) == chain.last().issuerInfo(QSslCertificate::Organization)) {
chain.append(rootCA);
break;
}
void slotUpdateMenu();
private:
- QMenu* buildCertMenu(QMenu *parent, const QSslCertificate& cert,
- const QList<QSslCertificate>& userApproved, int pos);
+ QMenu *buildCertMenu(QMenu *parent, const QSslCertificate &cert,
+ const QList<QSslCertificate> &userApproved, int pos);
QPointer<AccountState> _accountState;
- QMenu* _menu;
+ QMenu *_menu;
};
} // namespace OCC
#include "ui_sslerrordialog.h"
-namespace OCC
-{
+namespace OCC {
Q_LOGGING_CATEGORY(lcSslErrorDialog, "gui.sslerrordialog", QtInfoMsg)
bool SslDialogErrorHandler::handleErrors(QList<QSslError> errors, const QSslConfiguration &conf, QList<QSslCertificate> *certs, AccountPtr account)
{
- (void) conf;
+ (void)conf;
if (!certs) {
qCCritical(lcSslErrorDialog) << "Certs parameter required but is NULL!";
return false;
return false;
}
-SslErrorDialog::SslErrorDialog(AccountPtr account, QWidget *parent) :
- QDialog(parent), _allTrusted(false), _ui(new Ui::SslErrorDialog), _account(account)
+SslErrorDialog::SslErrorDialog(AccountPtr account, QWidget *parent)
+ : QDialog(parent)
+ , _allTrusted(false)
+ , _ui(new Ui::SslErrorDialog)
+ , _account(account)
{
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
- _ui->setupUi( this );
- setWindowTitle( tr("Untrusted Certificate") );
+ _ui->setupUi(this);
+ setWindowTitle(tr("Untrusted Certificate"));
QPushButton *okButton =
- _ui->_dialogButtonBox->button( QDialogButtonBox::Ok );
+ _ui->_dialogButtonBox->button(QDialogButtonBox::Ok);
QPushButton *cancelButton =
- _ui->_dialogButtonBox->button( QDialogButtonBox::Cancel );
+ _ui->_dialogButtonBox->button(QDialogButtonBox::Cancel);
okButton->setEnabled(false);
connect(_ui->_cbTrustConnect, SIGNAL(clicked(bool)),
- okButton, SLOT(setEnabled(bool)));
+ okButton, SLOT(setEnabled(bool)));
- if( okButton ) {
+ if (okButton) {
okButton->setDefault(true);
- connect( okButton, SIGNAL(clicked()),SLOT(accept()));
- connect( cancelButton, SIGNAL(clicked()),SLOT(reject()));
+ connect(okButton, SIGNAL(clicked()), SLOT(accept()));
+ connect(cancelButton, SIGNAL(clicked()), SLOT(reject()));
}
}
QString SslErrorDialog::styleSheet() const
{
const QString style = QLatin1String(
- "#cert {margin-left: 5px;} "
- "#ca_error { color:#a00011; margin-left:5px; margin-right:5px; }"
- "#ca_error p { margin-top: 2px; margin-bottom:2px; }"
- "#ccert { margin-left: 5px; }"
- "#issuer { margin-left: 5px; }"
- "tt { font-size: small; }"
- );
+ "#cert {margin-left: 5px;} "
+ "#ca_error { color:#a00011; margin-left:5px; margin-right:5px; }"
+ "#ca_error p { margin-top: 2px; margin-bottom:2px; }"
+ "#ccert { margin-left: 5px; }"
+ "#issuer { margin-left: 5px; }"
+ "tt { font-size: small; }");
return style;
}
#define QL(x) QLatin1String(x)
-bool SslErrorDialog::checkFailingCertsKnown( const QList<QSslError> &errors )
+bool SslErrorDialog::checkFailingCertsKnown(const QList<QSslError> &errors)
{
// check if unknown certs caused errors.
_unknownCerts.clear();
for (int i = 0; i < errors.count(); ++i) {
QSslError error = errors.at(i);
- if (trustedCerts.contains(error.certificate()) ||
- _unknownCerts.contains(error.certificate() )) {
+ if (trustedCerts.contains(error.certificate()) || _unknownCerts.contains(error.certificate())) {
continue;
}
errorStrings += error.errorString();
}
QString msg = QL("<html><head>");
- msg += QL("<link rel='stylesheet' type='text/css' href='format.css'>");
- msg += QL("</head><body>");
+ msg += QL("<link rel='stylesheet' type='text/css' href='format.css'>");
+ msg += QL("</head><body>");
auto host = _account->url().host();
msg += QL("<h3>") + tr("Cannot connect securely to <i>%1</i>:").arg(host) + QL("</h3>");
// loop over the unknown certs and line up their errors.
msg += QL("<div id=\"ca_errors\">");
- foreach( const QSslCertificate& cert, _unknownCerts ) {
+ foreach (const QSslCertificate &cert, _unknownCerts) {
msg += QL("<div id=\"ca_error\">");
// add the errors for this cert
- foreach( QSslError err, errors ) {
- if( err.certificate() == cert ) {
+ foreach (QSslError err, errors) {
+ if (err.certificate() == cert) {
msg += QL("<p>") + err.errorString() + QL("</p>");
}
}
msg += QL("</div>");
- msg += certDiv( cert );
- if( _unknownCerts.count() > 1 ) {
+ msg += certDiv(cert);
+ if (_unknownCerts.count() > 1) {
msg += QL("<hr/>");
}
}
QTextDocument *doc = new QTextDocument(0);
QString style = styleSheet();
- doc->addResource( QTextDocument::StyleSheetResource, QUrl( QL("format.css") ), style);
- doc->setHtml( msg );
+ doc->addResource(QTextDocument::StyleSheetResource, QUrl(QL("format.css")), style);
+ doc->setHtml(msg);
- _ui->_tbErrors->setDocument( doc );
+ _ui->_tbErrors->setDocument(doc);
_ui->_tbErrors->show();
return false;
}
-QString SslErrorDialog::certDiv( QSslCertificate cert ) const
+QString SslErrorDialog::certDiv(QSslCertificate cert) const
{
QString msg;
msg += QL("<div id=\"cert\">");
- msg += QL("<h3>") + tr("with Certificate %1").arg( Utility::escape(cert.subjectInfo( QSslCertificate::CommonName ))) + QL("</h3>");
+ msg += QL("<h3>") + tr("with Certificate %1").arg(Utility::escape(cert.subjectInfo(QSslCertificate::CommonName))) + QL("</h3>");
msg += QL("<div id=\"ccert\">");
QStringList li;
- QString org = Utility::escape(cert.subjectInfo( QSslCertificate::Organization));
- QString unit = Utility::escape(cert.subjectInfo( QSslCertificate::OrganizationalUnitName));
- QString country = Utility::escape(cert.subjectInfo( QSslCertificate::CountryName));
- if (unit.isEmpty()) unit = tr("<not specified>");
- if (org.isEmpty()) org = tr("<not specified>");
- if (country.isEmpty()) country = tr("<not specified>");
+ QString org = Utility::escape(cert.subjectInfo(QSslCertificate::Organization));
+ QString unit = Utility::escape(cert.subjectInfo(QSslCertificate::OrganizationalUnitName));
+ QString country = Utility::escape(cert.subjectInfo(QSslCertificate::CountryName));
+ if (unit.isEmpty())
+ unit = tr("<not specified>");
+ if (org.isEmpty())
+ org = tr("<not specified>");
+ if (country.isEmpty())
+ country = tr("<not specified>");
li << tr("Organization: %1").arg(org);
li << tr("Unit: %1").arg(unit);
li << tr("Country: %1").arg(country);
msg += QL("<p>");
QString md5sum = Utility::formatFingerprint(cert.digest(QCryptographicHash::Md5).toHex());
- QString sha1sum = Utility::formatFingerprint(cert.digest(QCryptographicHash::Sha1).toHex());
+ QString sha1sum = Utility::formatFingerprint(cert.digest(QCryptographicHash::Sha1).toHex());
msg += tr("Fingerprint (MD5): <tt>%1</tt>").arg(md5sum) + QL("<br/>");
msg += tr("Fingerprint (SHA1): <tt>%1</tt>").arg(sha1sum) + QL("<br/>");
msg += QL("<br/>");
- msg += tr("Effective Date: %1").arg( cert.effectiveDate().toString()) + QL("<br/>");
- msg += tr("Expiration Date: %1").arg( cert.expiryDate().toString()) + QL("</p>");
+ msg += tr("Effective Date: %1").arg(cert.effectiveDate().toString()) + QL("<br/>");
+ msg += tr("Expiration Date: %1").arg(cert.expiryDate().toString()) + QL("</p>");
- msg += QL("</div>" );
+ msg += QL("</div>");
- msg += QL("<h3>") + tr("Issuer: %1").arg(Utility::escape(cert.issuerInfo( QSslCertificate::CommonName))) + QL("</h3>");
+ msg += QL("<h3>") + tr("Issuer: %1").arg(Utility::escape(cert.issuerInfo(QSslCertificate::CommonName))) + QL("</h3>");
msg += QL("<div id=\"issuer\">");
li.clear();
- li << tr("Organization: %1").arg(Utility::escape(cert.issuerInfo( QSslCertificate::Organization)));
- li << tr("Unit: %1").arg(Utility::escape(cert.issuerInfo( QSslCertificate::OrganizationalUnitName)));
- li << tr("Country: %1").arg(Utility::escape(cert.issuerInfo( QSslCertificate::CountryName)));
+ li << tr("Organization: %1").arg(Utility::escape(cert.issuerInfo(QSslCertificate::Organization)));
+ li << tr("Unit: %1").arg(Utility::escape(cert.issuerInfo(QSslCertificate::OrganizationalUnitName)));
+ li << tr("Country: %1").arg(Utility::escape(cert.issuerInfo(QSslCertificate::CountryName)));
msg += QL("<p>") + li.join(QL("<br/>")) + QL("</p>");
- msg += QL("</div>" );
- msg += QL("</div>" );
+ msg += QL("</div>");
+ msg += QL("</div>");
return msg;
}
bool SslErrorDialog::trustConnection()
{
- if( _allTrusted ) return true;
+ if (_allTrusted)
+ return true;
- bool stat = ( _ui->_cbTrustConnect->checkState() == Qt::Checked );
+ bool stat = (_ui->_cbTrustConnect->checkState() == Qt::Checked);
qCInfo(lcSslErrorDialog) << "SSL-Connection is trusted: " << stat;
return stat;
class QSslError;
class QSslCertificate;
-namespace OCC
-{
+namespace OCC {
namespace Ui {
-class SslErrorDialog;
+ class SslErrorDialog;
}
/**
* @brief The SslDialogErrorHandler class
* @ingroup gui
*/
-class SslDialogErrorHandler : public AbstractSslErrorHandler {
+class SslDialogErrorHandler : public AbstractSslErrorHandler
+{
public:
bool handleErrors(QList<QSslError> errors, const QSslConfiguration &conf, QList<QSslCertificate> *certs, AccountPtr) Q_DECL_OVERRIDE;
};
public:
explicit SslErrorDialog(AccountPtr account, QWidget *parent = 0);
~SslErrorDialog();
- bool checkFailingCertsKnown( const QList<QSslError> &errors );
+ bool checkFailingCertsKnown(const QList<QSslError> &errors);
bool trustConnection();
QList<QSslCertificate> unknownCerts() const { return _unknownCerts; }
QString styleSheet() const;
bool _allTrusted;
- QString certDiv( QSslCertificate ) const;
+ QString certDiv(QSslCertificate) const;
QList<QSslCertificate> _unknownCerts;
- QString _customConfigHandle;
- Ui::SslErrorDialog *_ui;
- AccountPtr _account;
+ QString _customConfigHandle;
+ Ui::SslErrorDialog *_ui;
+ AccountPtr _account;
};
} // end namespace
namespace OCC {
-SyncLogDialog::SyncLogDialog(QWidget *parent, ProtocolWidget *protoWidget) :
- QDialog(parent),
- _ui(new Ui::SyncLogDialog)
+SyncLogDialog::SyncLogDialog(QWidget *parent, ProtocolWidget *protoWidget)
+ : QDialog(parent)
+ , _ui(new Ui::SyncLogDialog)
{
setObjectName("SyncLogDialog"); // required as group for saveGeometry call
_ui->setupUi(this);
- if( protoWidget) {
+ if (protoWidget) {
_ui->logWidgetLayout->addWidget(protoWidget);
}
QPushButton *closeButton = _ui->buttonBox->button(QDialogButtonBox::Close);
- if( closeButton ) {
- connect( closeButton, SIGNAL(clicked()), this, SLOT(close()) );
+ if (closeButton) {
+ connect(closeButton, SIGNAL(clicked()), this, SLOT(close()));
}
}
SyncLogDialog::~SyncLogDialog()
{
-
}
-
}
namespace Ui {
-class SyncLogDialog;
+ class SyncLogDialog;
}
private slots:
private:
-
Ui::SyncLogDialog *_ui;
};
-
}
#endif // SyncLogDialog_H
{
}
-QString SyncRunFileLog::dateTimeStr( const QDateTime& dt )
+QString SyncRunFileLog::dateTimeStr(const QDateTime &dt)
{
return dt.toString(Qt::ISODate);
}
-QString SyncRunFileLog::directionToStr( SyncFileItem::Direction dir )
+QString SyncRunFileLog::directionToStr(SyncFileItem::Direction dir)
{
QString re("N");
- if( dir == SyncFileItem::Up ) {
+ if (dir == SyncFileItem::Up) {
re = QLatin1String("Up");
- } else if( dir == SyncFileItem::Down ) {
+ } else if (dir == SyncFileItem::Down) {
re = QLatin1String("Down");
}
return re;
}
-QString SyncRunFileLog::instructionToStr( csync_instructions_e inst )
+QString SyncRunFileLog::instructionToStr(csync_instructions_e inst)
{
QString re;
- switch( inst ) {
+ switch (inst) {
case CSYNC_INSTRUCTION_NONE:
re = "INST_NONE";
break;
void SyncRunFileLog::start(const QString &folderPath)
{
- const qint64 logfileMaxSize = 1024*1024; // 1MiB
+ const qint64 logfileMaxSize = 1024 * 1024; // 1MiB
// Note; this name is ignored in csync_exclude.c
const QString filename = folderPath + QLatin1String(".owncloudsync.log");
_file.reset(new QFile(filename));
_file->open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text);
- _out.setDevice( _file.data() );
+ _out.setDevice(_file.data());
if (!exists) {
_out << "# timestamp | duration | file | instruction | dir | modtime | etag | "
"size | fileId | status | errorString | http result code | "
"other size | other modtime | other etag | other fileId | "
- "other instruction" << endl;
+ "other instruction"
+ << endl;
FileSystem::setFileHidden(filename, true);
}
_out << "#=#=#=# Syncrun started " << dateTimeStr(QDateTime::currentDateTime()) << endl;
}
-void SyncRunFileLog::logItem( const SyncFileItem& item )
+void SyncRunFileLog::logItem(const SyncFileItem &item)
{
// don't log the directory items that are in the list
- if( item._direction == SyncFileItem::None ) {
+ if (item._direction == SyncFileItem::None) {
return;
}
- QString ts = QString::fromAscii(item._responseTimeStamp);
- if( ts.length() > 6 ) {
+ QString ts = QString::fromAscii(item._responseTimeStamp);
+ if (ts.length() > 6) {
QRegExp rx("(\\d\\d:\\d\\d:\\d\\d)");
- if( ts.contains(rx) ) {
+ if (ts.contains(rx)) {
ts = rx.cap(0);
}
}
const QChar L = QLatin1Char('|');
_out << ts << L;
_out << L;
- if( item._instruction != CSYNC_INSTRUCTION_RENAME ) {
+ if (item._instruction != CSYNC_INSTRUCTION_RENAME) {
_out << item._file << L;
} else {
_out << item._file << QLatin1String(" -> ") << item._renameTarget << L;
}
- _out << instructionToStr( item._instruction ) << L;
- _out << directionToStr( item._direction ) << L;
+ _out << instructionToStr(item._instruction) << L;
+ _out << directionToStr(item._direction) << L;
_out << QString::number(item._modtime) << L;
_out << item._etag << L;
_out << QString::number(item._size) << L;
_out << endl;
}
-void SyncRunFileLog::logLap(const QString& name)
+void SyncRunFileLog::logLap(const QString &name)
{
_out << "#=#=#=#=# " << name << " " << dateTimeStr(QDateTime::currentDateTime())
<< " (last step: " << _lapDuration.restart() << " msec"
<< ", total: " << _totalDuration.elapsed() << " msec)" << endl;
_file->close();
}
-
}
{
public:
SyncRunFileLog();
- void start( const QString& folderPath );
- void logItem( const SyncFileItem& item );
- void logLap( const QString& name );
+ void start(const QString &folderPath);
+ void logItem(const SyncFileItem &item);
+ void logLap(const QString &name);
void finish();
protected:
-
private:
- QString dateTimeStr( const QDateTime& dt );
- QString instructionToStr( csync_instructions_e inst );
- QString directionToStr( SyncFileItem::Direction dir );
+ QString dateTimeStr(const QDateTime &dt);
+ QString instructionToStr(csync_instructions_e inst);
+ QString directionToStr(SyncFileItem::Direction dir);
QScopedPointer<QFile> _file;
QTextStream _out;
namespace OCC {
-void Systray::showMessage(const QString & title, const QString & message, MessageIcon icon, int millisecondsTimeoutHint)
+void Systray::showMessage(const QString &title, const QString &message, MessageIcon icon, int millisecondsTimeoutHint)
{
-
#ifdef USE_FDO_NOTIFICATIONS
- if(QDBusInterface(NOTIFICATIONS_SERVICE, NOTIFICATIONS_PATH, NOTIFICATIONS_IFACE).isValid()) {
+ if (QDBusInterface(NOTIFICATIONS_SERVICE, NOTIFICATIONS_PATH, NOTIFICATIONS_IFACE).isValid()) {
QList<QVariant> args = QList<QVariant>() << "owncloud" << quint32(0) << "owncloud"
- << title << message << QStringList () << QVariantMap() << qint32(-1);
+ << title << message << QStringList() << QVariantMap() << qint32(-1);
QDBusMessage method = QDBusMessage::createMethodCall(NOTIFICATIONS_SERVICE, NOTIFICATIONS_PATH, NOTIFICATIONS_IFACE, "Notify");
method.setArguments(args);
QDBusConnection::sessionBus().asyncCall(method);
} else
#endif
#ifdef Q_OS_OSX
- if (canOsXSendUserNotification()) {
+ if (canOsXSendUserNotification()) {
sendOsXUserNotification(title, message);
} else
#endif
{
Q_OBJECT
public:
- void showMessage(const QString & title, const QString & message, MessageIcon icon = Information, int millisecondsTimeoutHint = 10000);
+ void showMessage(const QString &title, const QString &message, MessageIcon icon = Information, int millisecondsTimeoutHint = 10000);
void setToolTip(const QString &tip);
};
namespace OCC {
-ThumbnailJob::ThumbnailJob(const QString &path, AccountPtr account, QObject* parent)
-: AbstractNetworkJob(account, QLatin1String("index.php/apps/files/api/v1/thumbnail/150/150/") + path, parent)
+ThumbnailJob::ThumbnailJob(const QString &path, AccountPtr account, QObject *parent)
+ : AbstractNetworkJob(account, QLatin1String("index.php/apps/files/api/v1/thumbnail/150/150/") + path, parent)
{
setIgnoreCredentialFailure(true);
}
emit jobFinished(reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), reply()->readAll());
return true;
}
-
}
* Job that allows fetching a preview (of 150x150 for now) of a given file.
* Once the job has finished the jobFinished signal will be emitted.
*/
-class ThumbnailJob : public AbstractNetworkJob {
+class ThumbnailJob : public AbstractNetworkJob
+{
Q_OBJECT
public:
- explicit ThumbnailJob(const QString& path, AccountPtr account, QObject* parent = 0);
+ explicit ThumbnailJob(const QString &path, AccountPtr account, QObject *parent = 0);
public slots:
void start() Q_DECL_OVERRIDE;
signals:
private slots:
virtual bool finished() Q_DECL_OVERRIDE;
};
-
}
#endif // THUMBNAILJOB_H
using namespace OCC;
-ToolTipUpdater::ToolTipUpdater(QTreeView* treeView)
+ToolTipUpdater::ToolTipUpdater(QTreeView *treeView)
: QObject(treeView)
, _treeView(treeView)
{
- connect(_treeView->model(), SIGNAL(dataChanged(QModelIndex,QModelIndex,QVector<int>)),
- SLOT(dataChanged(QModelIndex,QModelIndex,QVector<int>)));
+ connect(_treeView->model(), SIGNAL(dataChanged(QModelIndex, QModelIndex, QVector<int>)),
+ SLOT(dataChanged(QModelIndex, QModelIndex, QVector<int>)));
_treeView->viewport()->installEventFilter(this);
}
-bool ToolTipUpdater::eventFilter(QObject* /*obj*/, QEvent* ev)
+bool ToolTipUpdater::eventFilter(QObject * /*obj*/, QEvent *ev)
{
- if (ev->type() == QEvent::ToolTip)
- {
+ if (ev->type() == QEvent::ToolTip) {
QHelpEvent *helpEvent = static_cast<QHelpEvent *>(ev);
_toolTipPos = helpEvent->globalPos();
}
return false;
}
-void ToolTipUpdater::dataChanged(const QModelIndex& topLeft,
- const QModelIndex& bottomRight,
- const QVector<int>& roles)
+void ToolTipUpdater::dataChanged(const QModelIndex &topLeft,
+ const QModelIndex &bottomRight,
+ const QVector<int> &roles)
{
if (!QToolTip::isVisible() || !roles.contains(Qt::ToolTipRole) || _toolTipPos.isNull()) {
return;
// Update the currently active tooltip
QToolTip::showText(_toolTipPos, _treeView->model()->data(index, Qt::ToolTipRole).toString());
}
-
{
Q_OBJECT
public:
- ToolTipUpdater(QTreeView* treeView);
+ ToolTipUpdater(QTreeView *treeView);
protected:
- bool eventFilter(QObject* obj, QEvent* ev) Q_DECL_OVERRIDE;
+ bool eventFilter(QObject *obj, QEvent *ev) Q_DECL_OVERRIDE;
private slots:
- void dataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight, const QVector<int>& roles);
+ void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles);
private:
- QTreeView* _treeView;
+ QTreeView *_treeView;
QPoint _toolTipPos;
};
static const char autoUpdateAttemptedC[] = "Updater/autoUpdateAttempted";
-UpdaterScheduler::UpdaterScheduler(QObject *parent) :
- QObject(parent)
+UpdaterScheduler::UpdaterScheduler(QObject *parent)
+ : QObject(parent)
{
- connect( &_updateCheckTimer, SIGNAL(timeout()),
- this, SLOT(slotTimerFired()) );
+ connect(&_updateCheckTimer, SIGNAL(timeout()),
+ this, SLOT(slotTimerFired()));
// Note: the sparkle-updater is not an OCUpdater
- if (OCUpdater *updater = qobject_cast<OCUpdater*>(Updater::instance())) {
- connect(updater, SIGNAL(newUpdateAvailable(QString,QString)),
- this, SIGNAL(updaterAnnouncement(QString,QString)) );
+ if (OCUpdater *updater = qobject_cast<OCUpdater *>(Updater::instance())) {
+ connect(updater, SIGNAL(newUpdateAvailable(QString, QString)),
+ this, SIGNAL(updaterAnnouncement(QString, QString)));
connect(updater, SIGNAL(requestRestart()), SIGNAL(requestRestart()));
}
// re-set the check interval if it changed in the config file meanwhile
auto checkInterval = cfg.updateCheckInterval();
- if( checkInterval != _updateCheckTimer.interval() ) {
+ if (checkInterval != _updateCheckTimer.interval()) {
_updateCheckTimer.setInterval(checkInterval);
qCInfo(lcUpdater) << "Setting new update check interval " << checkInterval;
}
// consider the skipUpdateCheck flag in the config.
- if( cfg.skipUpdateCheck() ) {
+ if (cfg.skipUpdateCheck()) {
qCInfo(lcUpdater) << "Skipping update check because of config file";
return;
}
/* ----------------------------------------------------------------- */
-OCUpdater::OCUpdater(const QUrl &url) :
- Updater()
- , _updateUrl(url)
- , _state(Unknown)
- , _accessManager(new AccessManager(this))
- , _timeoutWatchdog(new QTimer(this))
+OCUpdater::OCUpdater(const QUrl &url)
+ : Updater()
+ , _updateUrl(url)
+ , _state(Unknown)
+ , _accessManager(new AccessManager(this))
+ , _timeoutWatchdog(new QTimer(this))
{
-
}
bool OCUpdater::performUpdate()
QSettings settings(cfg.configFile(), QSettings::IniFormat);
QString updateFile = settings.value(updateAvailableC).toString();
if (!updateFile.isEmpty() && QFile(updateFile).exists()
- && !updateSucceeded() /* Someone might have run the updater manually between restarts */ ) {
+ && !updateSucceeded() /* Someone might have run the updater manually between restarts */) {
const QString name = Theme::instance()->appNameGUI();
if (QMessageBox::information(0, tr("New %1 Update Ready").arg(name),
- tr("A new update for %1 is about to be installed. The updater may ask\n"
- "for additional privileges during the process.").arg(name), QMessageBox::Ok)) {
+ tr("A new update for %1 is about to be installed. The updater may ask\n"
+ "for additional privileges during the process.")
+ .arg(name),
+ QMessageBox::Ok)) {
slotStartInstaller();
return true;
}
int dlState = downloadState();
// do the real update check depending on the internal state of updater.
- switch( dlState ) {
+ switch (dlState) {
case Unknown:
case UpToDate:
case DownloadFailed:
case Unknown:
return tr("Update status is unknown: Did not check for new updates.");
case UpToDate:
- // fall through
+ // fall through
default:
return tr("No updates available. Your installation is at the latest version.");
}
// show the notification if the download is complete (on every check)
// or once for system based updates.
- if( _state == OCUpdater::DownloadComplete ||
- (oldState != OCUpdater::UpdateOnlyAvailableThroughSystem
- && _state == OCUpdater::UpdateOnlyAvailableThroughSystem) ) {
- emit newUpdateAvailable(tr("Update Check"), statusString() );
+ if (_state == OCUpdater::DownloadComplete || (oldState != OCUpdater::UpdateOnlyAvailableThroughSystem
+ && _state == OCUpdater::UpdateOnlyAvailableThroughSystem)) {
+ emit newUpdateAvailable(tr("Update Check"), statusString());
}
}
settings.setValue(autoUpdateAttemptedC, true);
settings.sync();
qCInfo(lcUpdater) << "Running updater" << updateFile;
- QProcess::startDetached(updateFile, QStringList() << "/S" << "/launch");
+ QProcess::startDetached(updateFile, QStringList() << "/S"
+ << "/launch");
}
void OCUpdater::checkForUpdate()
{
QNetworkReply *reply = _accessManager->get(QNetworkRequest(_updateUrl));
connect(_timeoutWatchdog, SIGNAL(timeout()), this, SLOT(slotTimedOut()));
- _timeoutWatchdog->start(30*1000);
+ _timeoutWatchdog->start(30 * 1000);
connect(reply, SIGNAL(finished()), this, SLOT(slotVersionInfoArrived()));
setDownloadState(CheckingServer);
void OCUpdater::slotVersionInfoArrived()
{
_timeoutWatchdog->stop();
- QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
+ QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
reply->deleteLater();
- if( reply->error() != QNetworkReply::NoError ) {
+ if (reply->error() != QNetworkReply::NoError) {
qCWarning(lcUpdater) << "Failed to reach version check url: " << reply->errorString();
return;
}
QString xml = QString::fromUtf8(reply->readAll());
bool ok;
- _updateInfo = UpdateInfo::parseString( xml, &ok );
- if( ok ) {
+ _updateInfo = UpdateInfo::parseString(xml, &ok);
+ if (ok) {
versionInfoArrived(_updateInfo);
} else {
qCWarning(lcUpdater) << "Could not parse update information.";
void NSISUpdater::slotWriteFile()
{
- QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
- if(_file->isOpen()) {
+ QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
+ if (_file->isOpen()) {
_file->write(reply->readAll());
}
}
void NSISUpdater::slotDownloadFinished()
{
- QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
+ QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
reply->deleteLater();
if (reply->error() != QNetworkReply::NoError) {
setDownloadState(DownloadFailed);
qint64 infoVersion = Helper::stringVersionToInt(info.version());
qint64 seenVersion = Helper::stringVersionToInt(settings.value(seenVersionC).toString());
qint64 currVersion = Helper::currentVersionToInt();
- if(info.version().isEmpty()
- || infoVersion <= currVersion
- || infoVersion <= seenVersion)
- {
+ if (info.version().isEmpty()
+ || infoVersion <= currVersion
+ || infoVersion <= seenVersion) {
qCInfo(lcUpdater) << "Client is on latest version!";
setDownloadState(UpToDate);
} else {
QString url = info.downloadUrl();
qint64 autoUpdateFailedVersion =
- Helper::stringVersionToInt(settings.value(autoUpdateFailedVersionC).toString());
+ Helper::stringVersionToInt(settings.value(autoUpdateFailedVersionC).toString());
if (url.isEmpty() || _showFallbackMessage || infoVersion == autoUpdateFailedVersion) {
showDialog(info);
}
QString txt = tr("<p>A new version of the %1 Client is available.</p>"
"<p><b>%2</b> is available for download. The installed version is %3.</p>")
.arg(Utility::escape(Theme::instance()->appNameGUI()),
- Utility::escape(info.versionString()), Utility::escape(clientVersion()));
+ Utility::escape(info.versionString()), Utility::escape(clientVersion()));
lbl->setText(txt);
lbl->setTextFormat(Qt::RichText);
bb->setWindowFlags(bb->windowFlags() & ~Qt::WindowContextHelpButtonHint);
QPushButton *skip = bb->addButton(tr("Skip this version"), QDialogButtonBox::ResetRole);
QPushButton *reject = bb->addButton(tr("Skip this time"), QDialogButtonBox::AcceptRole);
- QPushButton *getupdate = bb->addButton(tr("Get update"), QDialogButtonBox::AcceptRole);
+ QPushButton *getupdate = bb->addButton(tr("Get update"), QDialogButtonBox::AcceptRole);
connect(skip, SIGNAL(clicked()), msgBox, SLOT(reject()));
connect(reject, SIGNAL(clicked()), msgBox, SLOT(reject()));
}
}
}
- return NoUpdate;
+ return NoUpdate;
}
bool NSISUpdater::handleStartup()
void PassiveUpdateNotifier::backgroundCheckForUpdate()
{
-
- if( Utility::isLinux() ) {
+ if (Utility::isLinux()) {
// 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();
- if( !(fsVersion.isEmpty() || _runningAppVersion.isEmpty()) && fsVersion != _runningAppVersion ) {
+ if (!(fsVersion.isEmpty() || _runningAppVersion.isEmpty()) && fsVersion != _runningAppVersion) {
emit requestRestart();
}
}
qint64 currentVer = Helper::currentVersionToInt();
qint64 remoteVer = Helper::stringVersionToInt(info.version());
- if( info.version().isEmpty() ||
- currentVer >= remoteVer ) {
+ if (info.version().isEmpty() || currentVer >= remoteVer) {
qCInfo(lcUpdater) << "Client is on latest version!";
setDownloadState(UpToDate);
} else {
UpdaterScheduler(QObject *parent);
signals:
- void updaterAnnouncement(const QString& title, const QString& msg);
+ void updaterAnnouncement(const QString &title, const QString &msg);
void requestRestart();
private slots:
private:
QTimer _updateCheckTimer; /** Timer for the regular update check. */
-
};
/**
{
Q_OBJECT
public:
- enum DownloadState { Unknown = 0, CheckingServer, UpToDate,
- Downloading, DownloadComplete,
- DownloadFailed, DownloadTimedOut,
- UpdateOnlyAvailableThroughSystem };
+ enum DownloadState { Unknown = 0,
+ CheckingServer,
+ UpToDate,
+ Downloading,
+ DownloadComplete,
+ DownloadFailed,
+ DownloadTimedOut,
+ UpdateOnlyAvailableThroughSystem };
explicit OCUpdater(const QUrl &url);
bool performUpdate();
signals:
void downloadStateChanged();
- void newUpdateAvailable(const QString& header, const QString& message);
+ void newUpdateAvailable(const QString &header, const QString &message);
void requestRestart();
public slots:
protected:
virtual void versionInfoArrived(const UpdateInfo &info) = 0;
bool updateSucceeded() const;
- QNetworkAccessManager* qnam() const { return _accessManager; }
+ QNetworkAccessManager *qnam() const { return _accessManager; }
UpdateInfo updateInfo() const { return _updateInfo; }
+
private:
QUrl _updateUrl;
int _state;
QNetworkAccessManager *_accessManager;
- QTimer *_timeoutWatchdog; /** Timer to guard the timeout of an individual network request */
+ QTimer *_timeoutWatchdog; /** Timer to guard the timeout of an individual network request */
UpdateInfo _updateInfo;
};
* @brief Windows Updater Using NSIS
* @ingroup gui
*/
-class NSISUpdater : public OCUpdater {
+class NSISUpdater : public OCUpdater
+{
Q_OBJECT
public:
- enum UpdateState { NoUpdate = 0, UpdateAvailable, UpdateFailed };
+ enum UpdateState { NoUpdate = 0,
+ UpdateAvailable,
+ UpdateFailed };
explicit NSISUpdater(const QUrl &url);
bool handleStartup() Q_DECL_OVERRIDE;
private slots:
void slotSetSeenVersion();
void slotDownloadFinished();
void slotWriteFile();
+
private:
NSISUpdater::UpdateState updateStateOnStart();
void showDialog(const UpdateInfo &info);
QScopedPointer<QTemporaryFile> _file;
QString _targetFile;
bool _showFallbackMessage;
-
};
/**
*
* @ingroup gui
*/
-class PassiveUpdateNotifier : public OCUpdater {
+class PassiveUpdateNotifier : public OCUpdater
+{
Q_OBJECT
public:
explicit PassiveUpdateNotifier(const QUrl &url);
private:
void versionInfoArrived(const UpdateInfo &info) Q_DECL_OVERRIDE;
- QByteArray _runningAppVersion;
+ QByteArray _runningAppVersion;
};
-
-
-
}
#endif // OC_UPDATER
namespace OCC {
-class SparkleUpdater : public Updater {
+class SparkleUpdater : public Updater
+{
public:
- SparkleUpdater(const QString& appCastUrl);
+ SparkleUpdater(const QString &appCastUrl);
~SparkleUpdater();
// unused in this updater
void checkForUpdate() Q_DECL_OVERRIDE;
void backgroundCheckForUpdate() Q_DECL_OVERRIDE;
bool handleStartup() Q_DECL_OVERRIDE { return false; }
+
private:
class Private;
Private *d;
namespace OCC {
-void UpdateInfo::setVersion( const QString &v )
+void UpdateInfo::setVersion(const QString &v)
{
- mVersion = v;
+ mVersion = v;
}
QString UpdateInfo::version() const
{
- return mVersion;
+ return mVersion;
}
-void UpdateInfo::setVersionString( const QString &v )
+void UpdateInfo::setVersionString(const QString &v)
{
- mVersionString = v;
+ mVersionString = v;
}
QString UpdateInfo::versionString() const
{
- return mVersionString;
+ return mVersionString;
}
-void UpdateInfo::setWeb( const QString &v )
+void UpdateInfo::setWeb(const QString &v)
{
- mWeb = v;
+ mWeb = v;
}
QString UpdateInfo::web() const
{
- return mWeb;
+ return mWeb;
}
-void UpdateInfo::setDownloadUrl( const QString &v )
+void UpdateInfo::setDownloadUrl(const QString &v)
{
- mDownloadUrl = v;
+ mDownloadUrl = v;
}
QString UpdateInfo::downloadUrl() const
{
- return mDownloadUrl;
+ return mDownloadUrl;
}
-UpdateInfo UpdateInfo::parseElement( const QDomElement &element, bool *ok )
+UpdateInfo UpdateInfo::parseElement(const QDomElement &element, bool *ok)
{
- if ( element.tagName() != QLatin1String("owncloudclient") ) {
- qCCritical(lcUpdater) << "Expected 'owncloudclient', got '" << element.tagName() << "'.";
- if ( ok ) *ok = false;
- return UpdateInfo();
- }
-
- UpdateInfo result = UpdateInfo();
-
- QDomNode n;
- for( n = element.firstChild(); !n.isNull(); n = n.nextSibling() ) {
- QDomElement e = n.toElement();
- if ( e.tagName() == QLatin1String("version") ) {
- result.setVersion( e.text() );
+ if (element.tagName() != QLatin1String("owncloudclient")) {
+ qCCritical(lcUpdater) << "Expected 'owncloudclient', got '" << element.tagName() << "'.";
+ if (ok)
+ *ok = false;
+ return UpdateInfo();
}
- else if ( e.tagName() == QLatin1String("versionstring") ) {
- result.setVersionString( e.text() );
- }
- else if ( e.tagName() == QLatin1String("web") ) {
- result.setWeb( e.text() );
- }
- else if ( e.tagName() == QLatin1String("downloadurl") ) {
- result.setDownloadUrl( e.text() );
+
+ UpdateInfo result = UpdateInfo();
+
+ QDomNode n;
+ for (n = element.firstChild(); !n.isNull(); n = n.nextSibling()) {
+ QDomElement e = n.toElement();
+ if (e.tagName() == QLatin1String("version")) {
+ result.setVersion(e.text());
+ } else if (e.tagName() == QLatin1String("versionstring")) {
+ result.setVersionString(e.text());
+ } else if (e.tagName() == QLatin1String("web")) {
+ result.setWeb(e.text());
+ } else if (e.tagName() == QLatin1String("downloadurl")) {
+ result.setDownloadUrl(e.text());
+ }
}
- }
- if ( ok ) *ok = true;
- return result;
+ if (ok)
+ *ok = true;
+ return result;
}
-void UpdateInfo::writeElement( QXmlStreamWriter &xml )
+void UpdateInfo::writeElement(QXmlStreamWriter &xml)
{
- xml.writeStartElement( QLatin1String("owncloudclient") );
- if ( !version().isEmpty() ) {
- xml.writeTextElement( QLatin1String("version"), version() );
- }
- if ( !versionString().isEmpty() ) {
- xml.writeTextElement( QLatin1String("versionstring"), versionString() );
- }
- if ( !web().isEmpty() ) {
- xml.writeTextElement( QLatin1String("web"), web() );
- }
- if ( !downloadUrl().isEmpty() ) {
- xml.writeTextElement( QLatin1String("downloadurl"), web() );
- }
- xml.writeEndElement();
+ xml.writeStartElement(QLatin1String("owncloudclient"));
+ if (!version().isEmpty()) {
+ xml.writeTextElement(QLatin1String("version"), version());
+ }
+ if (!versionString().isEmpty()) {
+ xml.writeTextElement(QLatin1String("versionstring"), versionString());
+ }
+ if (!web().isEmpty()) {
+ xml.writeTextElement(QLatin1String("web"), web());
+ }
+ if (!downloadUrl().isEmpty()) {
+ xml.writeTextElement(QLatin1String("downloadurl"), web());
+ }
+ xml.writeEndElement();
}
-UpdateInfo UpdateInfo::parseFile( const QString &filename, bool *ok )
+UpdateInfo UpdateInfo::parseFile(const QString &filename, bool *ok)
{
- QFile file( filename );
- if ( !file.open( QIODevice::ReadOnly ) ) {
- qCCritical(lcUpdater) << "Unable to open file '" << filename << "'";
- if ( ok ) *ok = false;
- return UpdateInfo();
- }
-
- QString errorMsg;
- int errorLine, errorCol;
- QDomDocument doc;
- if ( !doc.setContent( &file, false, &errorMsg, &errorLine, &errorCol ) ) {
- qCCritical(lcUpdater) << errorMsg << " at " << errorLine << "," << errorCol;
- if ( ok ) *ok = false;
- return UpdateInfo();
- }
-
- bool documentOk;
- UpdateInfo c = parseElement( doc.documentElement(), &documentOk );
- if ( ok ) {
- *ok = documentOk;
- }
- return c;
+ QFile file(filename);
+ if (!file.open(QIODevice::ReadOnly)) {
+ qCCritical(lcUpdater) << "Unable to open file '" << filename << "'";
+ if (ok)
+ *ok = false;
+ return UpdateInfo();
+ }
+
+ QString errorMsg;
+ int errorLine, errorCol;
+ QDomDocument doc;
+ if (!doc.setContent(&file, false, &errorMsg, &errorLine, &errorCol)) {
+ qCCritical(lcUpdater) << errorMsg << " at " << errorLine << "," << errorCol;
+ if (ok)
+ *ok = false;
+ return UpdateInfo();
+ }
+
+ bool documentOk;
+ UpdateInfo c = parseElement(doc.documentElement(), &documentOk);
+ if (ok) {
+ *ok = documentOk;
+ }
+ return c;
}
-UpdateInfo UpdateInfo::parseString( const QString &xml, bool *ok )
+UpdateInfo UpdateInfo::parseString(const QString &xml, bool *ok)
{
- QString errorMsg;
- int errorLine, errorCol;
- QDomDocument doc;
- if ( !doc.setContent( xml, false, &errorMsg, &errorLine, &errorCol ) ) {
- qCCritical(lcUpdater) << errorMsg << " at " << errorLine << "," << errorCol;
- if ( ok ) *ok = false;
- return UpdateInfo();
- }
-
- bool documentOk;
- UpdateInfo c = parseElement( doc.documentElement(), &documentOk );
- if ( ok ) {
- *ok = documentOk;
- }
- return c;
+ QString errorMsg;
+ int errorLine, errorCol;
+ QDomDocument doc;
+ if (!doc.setContent(xml, false, &errorMsg, &errorLine, &errorCol)) {
+ qCCritical(lcUpdater) << errorMsg << " at " << errorLine << "," << errorCol;
+ if (ok)
+ *ok = false;
+ return UpdateInfo();
+ }
+
+ bool documentOk;
+ UpdateInfo c = parseElement(doc.documentElement(), &documentOk);
+ if (ok) {
+ *ok = documentOk;
+ }
+ return c;
}
-bool UpdateInfo::writeFile( const QString &filename )
+bool UpdateInfo::writeFile(const QString &filename)
{
- QFile file( filename );
- if ( !file.open( QIODevice::WriteOnly ) ) {
- qCCritical(lcUpdater) << "Unable to open file '" << filename << "'";
- return false;
- }
-
- QXmlStreamWriter xml( &file );
- xml.setAutoFormatting( true );
- xml.setAutoFormattingIndent( 2 );
- xml.writeStartDocument( QLatin1String("1.0") );
- writeElement( xml );
- xml.writeEndDocument();
- file.close();
-
- return true;
+ QFile file(filename);
+ if (!file.open(QIODevice::WriteOnly)) {
+ qCCritical(lcUpdater) << "Unable to open file '" << filename << "'";
+ return false;
+ }
+
+ QXmlStreamWriter xml(&file);
+ xml.setAutoFormatting(true);
+ xml.setAutoFormattingIndent(2);
+ xml.writeStartDocument(QLatin1String("1.0"));
+ writeElement(xml);
+ xml.writeEndDocument();
+ file.close();
+
+ return true;
}
} // namespace OCC
class UpdateInfo
{
- public:
- void setVersion( const QString &v );
+public:
+ void setVersion(const QString &v);
QString version() const;
- void setVersionString( const QString &v );
+ void setVersionString(const QString &v);
QString versionString() const;
- void setWeb( const QString &v );
+ void setWeb(const QString &v);
QString web() const;
- void setDownloadUrl( const QString &v );
+ void setDownloadUrl(const QString &v);
QString downloadUrl() const;
/**
Parse XML object from DOM element.
*/
- static UpdateInfo parseElement( const QDomElement &element, bool *ok );
- void writeElement( QXmlStreamWriter &xml );
- static UpdateInfo parseFile( const QString &filename, bool *ok );
- static UpdateInfo parseString( const QString &xml, bool *ok );
- bool writeFile( const QString &filename );
+ static UpdateInfo parseElement(const QDomElement &element, bool *ok);
+ void writeElement(QXmlStreamWriter &xml);
+ static UpdateInfo parseFile(const QString &filename, bool *ok);
+ static UpdateInfo parseString(const QString &xml, bool *ok);
+ bool writeFile(const QString &filename);
- private:
+private:
QString mVersion;
QString mVersionString;
QString mWeb;
Updater *Updater::_instance = 0;
-Updater * Updater::instance()
+Updater *Updater::instance()
{
- if(!_instance) {
+ if (!_instance) {
_instance = create();
}
return _instance;
if (Utility::isLinux()) {
platform = QLatin1String("linux");
} else if (Utility::isBSD()) {
- platform = QLatin1String("bsd");
+ platform = QLatin1String("bsd");
} else if (Utility::isWindows()) {
platform = QLatin1String("win32");
} else if (Utility::isMac()) {
}
QString sysInfo = getSystemInfo();
- if( !sysInfo.isEmpty() ) {
- paramUrl.addQueryItem(QLatin1String("client"), sysInfo );
+ if (!sysInfo.isEmpty()) {
+ paramUrl.addQueryItem(QLatin1String("client"), sysInfo);
}
- paramUrl.addQueryItem( QLatin1String("version"), clientVersion() );
- paramUrl.addQueryItem( QLatin1String("platform"), platform );
- paramUrl.addQueryItem( QLatin1String("oem"), theme->appName() );
+ paramUrl.addQueryItem(QLatin1String("version"), clientVersion());
+ paramUrl.addQueryItem(QLatin1String("platform"), platform);
+ paramUrl.addQueryItem(QLatin1String("oem"), theme->appName());
return paramUrl;
}
{
#ifdef Q_OS_LINUX
QProcess process;
- process.start( QLatin1String("lsb_release -a") );
+ process.start(QLatin1String("lsb_release -a"));
process.waitForFinished();
QByteArray output = process.readAllStandardOutput();
qCDebug(lcUpdater) << "Sys Info size: " << output.length();
- if( output.length() > 1024 ) output.clear(); // don't send too much.
+ if (output.length() > 1024)
+ output.clear(); // don't send too much.
- return QString::fromLocal8Bit( output.toBase64() );
+ return QString::fromLocal8Bit(output.toBase64());
#else
return QString::null;
#endif
}
updateBaseUrl = addQueryParams(updateBaseUrl);
#if defined(Q_OS_MAC) && defined(HAVE_SPARKLE)
- updateBaseUrl.addQueryItem( QLatin1String("sparkle"), QLatin1String("true"));
+ updateBaseUrl.addQueryItem(QLatin1String("sparkle"), QLatin1String("true"));
return new SparkleUpdater(updateBaseUrl.toString());
-#elif defined (Q_OS_WIN32)
+#elif defined(Q_OS_WIN32)
// the best we can do is notify about updates
return new NSISUpdater(updateBaseUrl);
#else
return new PassiveUpdateNotifier(QUrl(updateBaseUrl));
#endif
-
}
qint64 Updater::Helper::currentVersionToInt()
{
return versionToInt(MIRALL_VERSION_MAJOR, MIRALL_VERSION_MINOR,
- MIRALL_VERSION_PATCH, MIRALL_VERSION_BUILD);
+ MIRALL_VERSION_PATCH, MIRALL_VERSION_BUILD);
}
-qint64 Updater::Helper::stringVersionToInt(const QString& version)
+qint64 Updater::Helper::stringVersionToInt(const QString &version)
{
if (version.isEmpty())
return 0;
Q_DECLARE_LOGGING_CATEGORY(lcUpdater)
-class Updater : public QObject {
+class Updater : public QObject
+{
Q_OBJECT
public:
- struct Helper {
- static qint64 stringVersionToInt(const QString& version);
+ struct Helper
+ {
+ static qint64 stringVersionToInt(const QString &version);
static qint64 currentVersionToInt();
static qint64 versionToInt(qint64 major, qint64 minor, qint64 patch, qint64 build);
};
protected:
static QString clientVersion();
- Updater() : QObject(0) {}
+ Updater()
+ : QObject(0)
+ {
+ }
private:
static QString getSystemInfo();
{
// Reset the credentials when the 'Back' button is used.
- AccountPtr account = static_cast<OwncloudWizard*>(wizard())->account();
+ AccountPtr account = static_cast<OwncloudWizard *>(wizard())->account();
AbstractCredentials *creds = account->credentials();
if (creds) {
if (!creds->inherits("DummyCredentials")) {
}
}
}
-
}
#include <QWizardPage>
-namespace OCC
-{
+namespace OCC {
class AbstractCredentials;
{
public:
void cleanupPage() Q_DECL_OVERRIDE;
- virtual AbstractCredentials* getCredentials() const = 0;
+ virtual AbstractCredentials *getCredentials() const = 0;
};
} // namespace OCC
#include "creds/abstractcredentials.h"
#include "networkjobs.h"
-namespace OCC
-{
+namespace OCC {
OwncloudAdvancedSetupPage::OwncloudAdvancedSetupPage()
- : QWizardPage(),
- _ui(),
- _checking(false),
- _created(false),
- _localFolderValid(false),
- _progressIndi(new QProgressIndicator (this)),
- _remoteFolder()
+ : QWizardPage()
+ , _ui()
+ , _checking(false)
+ , _created(false)
+ , _localFolderValid(false)
+ , _progressIndi(new QProgressIndicator(this))
+ , _remoteFolder()
{
_ui.setupUi(this);
setTitle(WizardCommon::titleTemplate().arg(tr("Connect to %1").arg(theme->appNameGUI())));
setSubTitle(WizardCommon::subTitleTemplate().arg(tr("Setup local folder options")));
- registerField( QLatin1String("OCSyncFromScratch"), _ui.cbSyncFromScratch);
+ registerField(QLatin1String("OCSyncFromScratch"), _ui.cbSyncFromScratch);
- _ui.resultLayout->addWidget( _progressIndi );
+ _ui.resultLayout->addWidget(_progressIndi);
stopSpinner();
setupCustomization();
- connect( _ui.pbSelectLocalFolder, SIGNAL(clicked()), SLOT(slotSelectFolder()));
+ connect(_ui.pbSelectLocalFolder, SIGNAL(clicked()), SLOT(slotSelectFolder()));
setButtonText(QWizard::NextButton, tr("Connect..."));
- connect( _ui.rSyncEverything, SIGNAL(clicked()), SLOT(slotSyncEverythingClicked()));
- connect( _ui.rSelectiveSync, SIGNAL(clicked()), SLOT(slotSelectiveSyncClicked()));
- connect( _ui.bSelectiveSync, SIGNAL(clicked()), SLOT(slotSelectiveSyncClicked()));
+ connect(_ui.rSyncEverything, SIGNAL(clicked()), SLOT(slotSyncEverythingClicked()));
+ connect(_ui.rSelectiveSync, SIGNAL(clicked()), SLOT(slotSelectiveSyncClicked()));
+ connect(_ui.bSelectiveSync, SIGNAL(clicked()), SLOT(slotSelectiveSyncClicked()));
QIcon appIcon = theme->applicationIcon();
_ui.lServerIcon->setText(QString());
_ui.bottomLabel->hide();
Theme *theme = Theme::instance();
- QVariant variant = theme->customMedia( Theme::oCSetupTop );
- if( !variant.isNull() ) {
- WizardCommon::setupCustomMedia( variant, _ui.topLabel );
+ QVariant variant = theme->customMedia(Theme::oCSetupTop);
+ if (!variant.isNull()) {
+ WizardCommon::setupCustomMedia(variant, _ui.topLabel);
}
- variant = theme->customMedia( Theme::oCSetupBottom );
- WizardCommon::setupCustomMedia( variant, _ui.bottomLabel );
+ variant = theme->customMedia(Theme::oCSetupBottom);
+ WizardCommon::setupCustomMedia(variant, _ui.bottomLabel);
}
bool OwncloudAdvancedSetupPage::isComplete() const
{
WizardCommon::initErrorLabel(_ui.errorLabel);
- _checking = false;
+ _checking = false;
_ui.lSelectiveSyncSizeLabel->setText(QString());
_ui.lSyncEverythingSizeLabel->setText(QString());
_ui.pbSelectLocalFolder->setText(QDir::toNativeSeparators(locFolder));
if (dataChanged()) {
- if( _remoteFolder.isEmpty() || _remoteFolder == QLatin1String("/") ) {
+ if (_remoteFolder.isEmpty() || _remoteFolder == QLatin1String("/")) {
t = "";
} else {
t = Utility::escape(tr("%1 folder '%2' is synced to local folder '%3'")
.arg(Theme::instance()->appName(), _remoteFolder,
- QDir::toNativeSeparators(locFolder)));
+ QDir::toNativeSeparators(locFolder)));
_ui.rSyncEverything->setText(tr("Sync the folder '%1'").arg(_remoteFolder));
}
const bool dirNotEmpty(QDir(locFolder).entryList(QDir::AllEntries | QDir::NoDotAndDotDot).count() > 0);
- if(dirNotEmpty) {
+ if (dirNotEmpty) {
t += tr("<p><small><strong>Warning:</strong> The local folder is not empty. "
"Pick a resolution!</small></p>");
}
bool OwncloudAdvancedSetupPage::validatePage()
{
- if(!_created) {
+ if (!_created) {
setErrorString(QString::null);
_checking = true;
startSpinner();
if (_ui.rSyncEverything->isChecked()) {
ConfigFile cfgFile;
cfgFile.setNewBigFolderSizeLimit(_ui.confCheckBoxSize->isChecked(),
- _ui.confSpinBox->value());
+ _ui.confSpinBox->value());
cfgFile.setConfirmExternalStorage(_ui.confCheckBoxExternal->isChecked());
}
}
}
-void OwncloudAdvancedSetupPage::setErrorString( const QString& err )
+void OwncloudAdvancedSetupPage::setErrorString(const QString &err)
{
- if( err.isEmpty()) {
+ if (err.isEmpty()) {
_ui.errorLabel->setVisible(false);
} else {
_ui.errorLabel->setVisible(true);
emit completeChanged();
}
-void OwncloudAdvancedSetupPage::setRemoteFolder( const QString& remoteFolder )
+void OwncloudAdvancedSetupPage::setRemoteFolder(const QString &remoteFolder)
{
- if( !remoteFolder.isEmpty() ) {
+ if (!remoteFolder.isEmpty()) {
_remoteFolder = remoteFolder;
}
}
void OwncloudAdvancedSetupPage::slotSelectFolder()
{
QString dir = QFileDialog::getExistingDirectory(0, tr("Local Sync Folder"), QDir::homePath());
- if( !dir.isEmpty() ) {
+ if (!dir.isEmpty()) {
_ui.pbSelectLocalFolder->setText(dir);
wizard()->setProperty("localFolder", dir);
updateStatus();
_ui.rSelectiveSync->setChecked(true);
_ui.rSelectiveSync->blockSignals(false);
auto s = dlg->estimatedSize();
- if (s > 0 ) {
+ if (s > 0) {
_ui.lSelectiveSyncSizeLabel->setText(tr("(%1)").arg(Utility::octetsToString(s)));
} else {
_ui.lSelectiveSyncSizeLabel->setText(QString());
void OwncloudAdvancedSetupPage::slotQuotaRetrieved(const QVariantMap &result)
{
_ui.lSyncEverythingSizeLabel->setText(tr("(%1)").arg(Utility::octetsToString(result["size"].toDouble())));
-
}
} // namespace OCC
-
* @brief The OwncloudAdvancedSetupPage class
* @ingroup gui
*/
-class OwncloudAdvancedSetupPage: public QWizardPage
+class OwncloudAdvancedSetupPage : public QWizardPage
{
Q_OBJECT
public:
- OwncloudAdvancedSetupPage();
+ OwncloudAdvancedSetupPage();
- virtual bool isComplete() const Q_DECL_OVERRIDE;
- virtual void initializePage() Q_DECL_OVERRIDE;
- virtual int nextId() const Q_DECL_OVERRIDE;
- bool validatePage() Q_DECL_OVERRIDE;
- QString localFolder() const;
- QStringList selectiveSyncBlacklist() const;
- bool isConfirmBigFolderChecked() const;
- void setRemoteFolder( const QString& remoteFolder);
- void setMultipleFoldersExist( bool exist );
- void directoriesCreated();
+ virtual bool isComplete() const Q_DECL_OVERRIDE;
+ virtual void initializePage() Q_DECL_OVERRIDE;
+ virtual int nextId() const Q_DECL_OVERRIDE;
+ bool validatePage() Q_DECL_OVERRIDE;
+ QString localFolder() const;
+ QStringList selectiveSyncBlacklist() const;
+ bool isConfirmBigFolderChecked() const;
+ void setRemoteFolder(const QString &remoteFolder);
+ void setMultipleFoldersExist(bool exist);
+ void directoriesCreated();
signals:
- void createLocalAndRemoteFolders(const QString&, const QString&);
+ void createLocalAndRemoteFolders(const QString &, const QString &);
public slots:
- void setErrorString( const QString& );
+ void setErrorString(const QString &);
private slots:
- void slotSelectFolder();
- void slotSyncEverythingClicked();
- void slotSelectiveSyncClicked();
- void slotQuotaRetrieved(const QVariantMap& result);
+ void slotSelectFolder();
+ void slotSyncEverythingClicked();
+ void slotSelectiveSyncClicked();
+ void slotQuotaRetrieved(const QVariantMap &result);
private:
- void setupCustomization();
- void updateStatus();
- bool dataChanged();
- void startSpinner();
- void stopSpinner();
- QUrl serverUrl() const;
+ void setupCustomization();
+ void updateStatus();
+ bool dataChanged();
+ void startSpinner();
+ void stopSpinner();
+ QUrl serverUrl() const;
- Ui_OwncloudAdvancedSetupPage _ui;
- bool _checking;
- bool _created;
- bool _localFolderValid;
- QProgressIndicator* _progressIndi;
- QString _remoteFolder;
- QStringList _selectiveSyncBlacklist;
+ Ui_OwncloudAdvancedSetupPage _ui;
+ bool _checking;
+ bool _created;
+ bool _localFolderValid;
+ QProgressIndicator *_progressIndi;
+ QString _remoteFolder;
+ QStringList _selectiveSyncBlacklist;
};
} // namespace OCC
namespace OCC {
-OwncloudConnectionMethodDialog::OwncloudConnectionMethodDialog(QWidget *parent) :
- QDialog(parent, Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint | Qt::MSWindowsFixedSizeDialogHint),
- ui(new Ui::OwncloudConnectionMethodDialog)
+OwncloudConnectionMethodDialog::OwncloudConnectionMethodDialog(QWidget *parent)
+ : QDialog(parent, Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint | Qt::MSWindowsFixedSizeDialogHint)
+ , ui(new Ui::OwncloudConnectionMethodDialog)
{
ui->setupUi(this);
{
ui->label->setText(tr("<html><head/><body><p>Failed to connect to the secure server address <em>%1</em>. How do you wish to proceed?</p></body></html>")
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
- .arg(OCC::Utility::escape(url.toString())));
+ .arg(OCC::Utility::escape(url.toString())));
#else
- .arg(url.toDisplayString().toHtmlEscaped()));
+ .arg(url.toDisplayString().toHtmlEscaped()));
#endif
}
{
delete ui;
}
-
}
namespace OCC {
namespace Ui {
-class OwncloudConnectionMethodDialog;
+ class OwncloudConnectionMethodDialog;
}
/**
Client_Side_TLS,
Back
};
-
+
// The URL that was tried
void setUrl(const QUrl &);
private:
Ui::OwncloudConnectionMethodDialog *ui;
};
-
}
#endif // OWNCLOUDCONNECTIONMETHODDIALOG_H
#include "wizard/owncloudwizardcommon.h"
#include "wizard/owncloudwizard.h"
-namespace OCC
-{
+namespace OCC {
-OwncloudHttpCredsPage::OwncloudHttpCredsPage(QWidget* parent)
- : AbstractCredentialsWizardPage(),
- _ui(),
- _connected(false),
- _progressIndi(new QProgressIndicator (this))
+OwncloudHttpCredsPage::OwncloudHttpCredsPage(QWidget *parent)
+ : AbstractCredentialsWizardPage()
+ , _ui()
+ , _connected(false)
+ , _progressIndi(new QProgressIndicator(this))
{
_ui.setupUi(this);
- if(parent){
+ if (parent) {
_ocWizard = qobject_cast<OwncloudWizard *>(parent);
}
- registerField( QLatin1String("OCUser*"), _ui.leUsername);
- registerField( QLatin1String("OCPasswd*"), _ui.lePassword);
+ registerField(QLatin1String("OCUser*"), _ui.leUsername);
+ registerField(QLatin1String("OCPasswd*"), _ui.lePassword);
Theme *theme = Theme::instance();
- switch(theme->userIDType()) {
+ switch (theme->userIDType()) {
case Theme::UserIDUserName:
// default, handled in ui file
break;
setTitle(WizardCommon::titleTemplate().arg(tr("Connect to %1").arg(Theme::instance()->appNameGUI())));
setSubTitle(WizardCommon::subTitleTemplate().arg(tr("Enter user credentials")));
- _ui.resultLayout->addWidget( _progressIndi );
+ _ui.resultLayout->addWidget(_progressIndi);
stopSpinner();
setupCustomization();
}
_ui.bottomLabel->hide();
Theme *theme = Theme::instance();
- QVariant variant = theme->customMedia( Theme::oCSetupTop );
- if( !variant.isNull() ) {
- WizardCommon::setupCustomMedia( variant, _ui.topLabel );
+ QVariant variant = theme->customMedia(Theme::oCSetupTop);
+ if (!variant.isNull()) {
+ WizardCommon::setupCustomMedia(variant, _ui.topLabel);
}
- variant = theme->customMedia( Theme::oCSetupBottom );
- WizardCommon::setupCustomMedia( variant, _ui.bottomLabel );
+ variant = theme->customMedia(Theme::oCSetupBottom);
+ WizardCommon::setupCustomMedia(variant, _ui.bottomLabel);
}
void OwncloudHttpCredsPage::initializePage()
{
WizardCommon::initErrorLabel(_ui.errorLabel);
- OwncloudWizard* ocWizard = qobject_cast< OwncloudWizard* >(wizard());
+ OwncloudWizard *ocWizard = qobject_cast<OwncloudWizard *>(wizard());
AbstractCredentials *cred = ocWizard->account()->credentials();
- HttpCredentials *httpCreds = qobject_cast<HttpCredentials*>(cred);
+ HttpCredentials *httpCreds = qobject_cast<HttpCredentials *>(cred);
if (httpCreds) {
const QString user = httpCreds->fetchUser();
if (!user.isEmpty()) {
const QString user = url.userName();
const QString password = url.password();
- if(!user.isEmpty()) {
+ if (!user.isEmpty()) {
_ui.leUsername->setText(user);
}
- if(!password.isEmpty()) {
+ if (!password.isEmpty()) {
_ui.lePassword->setText(password);
}
}
startSpinner();
// Reset cookies to ensure the username / password is actually used
- OwncloudWizard* ocWizard = qobject_cast< OwncloudWizard* >(wizard());
+ OwncloudWizard *ocWizard = qobject_cast<OwncloudWizard *>(wizard());
ocWizard->account()->clearCookieJar();
emit completeChanged();
void OwncloudHttpCredsPage::setConnected()
{
_connected = true;
- stopSpinner ();
+ stopSpinner();
}
void OwncloudHttpCredsPage::startSpinner()
_progressIndi->stopAnimation();
}
-void OwncloudHttpCredsPage::setErrorString(const QString& err)
+void OwncloudHttpCredsPage::setErrorString(const QString &err)
{
- if( err.isEmpty()) {
+ if (err.isEmpty()) {
_ui.errorLabel->setVisible(false);
} else {
_ui.errorLabel->setVisible(true);
stopSpinner();
}
-AbstractCredentials* OwncloudHttpCredsPage::getCredentials() const
+AbstractCredentials *OwncloudHttpCredsPage::getCredentials() const
{
return new HttpCredentialsGui(_ui.leUsername->text(), _ui.lePassword->text(), _ocWizard->_clientSslCertificate, _ocWizard->_clientSslKey);
}
*/
class OwncloudHttpCredsPage : public AbstractCredentialsWizardPage
{
- Q_OBJECT
+ Q_OBJECT
public:
- OwncloudHttpCredsPage(QWidget* parent);
+ OwncloudHttpCredsPage(QWidget *parent);
- AbstractCredentials* getCredentials() const Q_DECL_OVERRIDE;
+ AbstractCredentials *getCredentials() const Q_DECL_OVERRIDE;
- void initializePage() Q_DECL_OVERRIDE;
- void cleanupPage() Q_DECL_OVERRIDE;
- bool validatePage() Q_DECL_OVERRIDE;
- int nextId() const Q_DECL_OVERRIDE;
- void setConnected();
- void setErrorString( const QString& err );
+ void initializePage() Q_DECL_OVERRIDE;
+ void cleanupPage() Q_DECL_OVERRIDE;
+ bool validatePage() Q_DECL_OVERRIDE;
+ int nextId() const Q_DECL_OVERRIDE;
+ void setConnected();
+ void setErrorString(const QString &err);
Q_SIGNALS:
- void connectToOCUrl(const QString&);
+ void connectToOCUrl(const QString &);
private:
- void startSpinner();
- void stopSpinner();
- void setupCustomization();
-
- Ui_OwncloudHttpCredsPage _ui;
- bool _connected;
- QProgressIndicator* _progressIndi;
- OwncloudWizard* _ocWizard;
+ void startSpinner();
+ void stopSpinner();
+ void setupCustomization();
+
+ Ui_OwncloudHttpCredsPage _ui;
+ bool _connected;
+ QProgressIndicator *_progressIndi;
+ OwncloudWizard *_ocWizard;
};
} // namespace OCC
#include "theme.h"
#include "account.h"
-namespace OCC
-{
+namespace OCC {
OwncloudSetupPage::OwncloudSetupPage(QWidget *parent)
- : QWizardPage(),
- _ui(),
- _oCUrl(),
- _ocUser(),
- _authTypeKnown(false),
- _checking(false),
- _authType(WizardCommon::HttpCreds),
- _progressIndi(new QProgressIndicator (this))
+ : QWizardPage()
+ , _ui()
+ , _oCUrl()
+ , _ocUser()
+ , _authTypeKnown(false)
+ , _checking(false)
+ , _authType(WizardCommon::HttpCreds)
+ , _progressIndi(new QProgressIndicator(this))
{
_ui.setupUi(this);
_ocWizard = qobject_cast<OwncloudWizard *>(parent);
}
- registerField( QLatin1String("OCUrl*"), _ui.leUrl );
+ registerField(QLatin1String("OCUrl*"), _ui.leUrl);
- _ui.resultLayout->addWidget( _progressIndi );
+ _ui.resultLayout->addWidget(_progressIndi);
stopSpinner();
setupCustomization();
addCertDial = new AddCertificateDialog(this);
}
-void OwncloudSetupPage::setServerUrl( const QString& newUrl )
+void OwncloudSetupPage::setServerUrl(const QString &newUrl)
{
_oCUrl = newUrl;
- if( _oCUrl.isEmpty() ) {
+ if (_oCUrl.isEmpty()) {
_ui.leUrl->clear();
return;
}
- _ui.leUrl->setText( _oCUrl );
+ _ui.leUrl->setText(_oCUrl);
}
void OwncloudSetupPage::setupCustomization()
_ui.bottomLabel->hide();
Theme *theme = Theme::instance();
- QVariant variant = theme->customMedia( Theme::oCSetupTop );
- if( !variant.isNull() ) {
- WizardCommon::setupCustomMedia( variant, _ui.topLabel );
+ QVariant variant = theme->customMedia(Theme::oCSetupTop);
+ if (!variant.isNull()) {
+ WizardCommon::setupCustomMedia(variant, _ui.topLabel);
}
- variant = theme->customMedia( Theme::oCSetupBottom );
- WizardCommon::setupCustomMedia( variant, _ui.bottomLabel );
+ variant = theme->customMedia(Theme::oCSetupBottom);
+ WizardCommon::setupCustomMedia(variant, _ui.bottomLabel);
}
// slot hit from textChanged of the url entry field.
-void OwncloudSetupPage::slotUrlChanged(const QString& url)
+void OwncloudSetupPage::slotUrlChanged(const QString &url)
{
_authTypeKnown = false;
if (url.endsWith("index.php")) {
newUrl.chop(9);
}
- if( _ocWizard && _ocWizard->account() ) {
+ if (_ocWizard && _ocWizard->account()) {
QString webDavPath = _ocWizard->account()->davPath();
if (url.endsWith(webDavPath)) {
- newUrl.chop( webDavPath.length() );
+ newUrl.chop(webDavPath.length());
}
- if( webDavPath.endsWith(QLatin1Char('/')) ) {
+ if (webDavPath.endsWith(QLatin1Char('/'))) {
webDavPath.chop(1); // cut off the slash
- if( url.endsWith(webDavPath)) {
+ if (url.endsWith(webDavPath)) {
newUrl.chop(webDavPath.length());
}
}
WizardCommon::initErrorLabel(_ui.errorLabel);
_authTypeKnown = false;
- _checking = false;
+ _checking = false;
QAbstractButton *nextButton = wizard()->button(QWizard::NextButton);
- QPushButton *pushButton = qobject_cast<QPushButton*>(nextButton);
+ QPushButton *pushButton = qobject_cast<QPushButton *>(nextButton);
if (pushButton)
pushButton->setDefault(true);
bool change = false;
const QChar slash('/');
- QUrl currentUrl( url() );
- QUrl initialUrl( _oCUrl );
+ QUrl currentUrl(url());
+ QUrl initialUrl(_oCUrl);
QString currentPath = currentUrl.path();
QString initialPath = initialUrl.path();
// add a trailing slash.
- if( ! currentPath.endsWith( slash )) currentPath += slash;
- if( ! initialPath.endsWith( slash )) initialPath += slash;
+ if (!currentPath.endsWith(slash))
+ currentPath += slash;
+ if (!initialPath.endsWith(slash))
+ initialPath += slash;
- if( currentUrl.host() != initialUrl.host() ||
- currentUrl.port() != initialUrl.port() ||
- currentPath != initialPath ) {
+ if (currentUrl.host() != initialUrl.host() || currentUrl.port() != initialUrl.port() || currentPath != initialPath) {
change = true;
}
bool OwncloudSetupPage::validatePage()
{
- if( ! _authTypeKnown) {
+ if (!_authTypeKnown) {
setErrorString(QString::null, false);
_checking = true;
- startSpinner ();
+ startSpinner();
emit completeChanged();
emit determineAuthType(url());
}
}
-void OwncloudSetupPage::setAuthType (WizardCommon::AuthType type)
+void OwncloudSetupPage::setAuthType(WizardCommon::AuthType type)
{
- _authTypeKnown = true;
- _authType = type;
- stopSpinner();
+ _authTypeKnown = true;
+ _authType = type;
+ stopSpinner();
}
-void OwncloudSetupPage::setErrorString( const QString& err, bool retryHTTPonly )
+void OwncloudSetupPage::setErrorString(const QString &err, bool retryHTTPonly)
{
- if( err.isEmpty()) {
+ if (err.isEmpty()) {
_ui.errorLabel->setVisible(false);
} else {
if (retryHTTPonly) {
int retVal = dialog.exec();
switch (retVal) {
- case OwncloudConnectionMethodDialog::No_TLS:
- {
- url.setScheme("http");
- _ui.leUrl->setFullText(url.toString());
- // skip ahead to next page, since the user would expect us to retry automatically
- wizard()->next();
- }
- break;
+ case OwncloudConnectionMethodDialog::No_TLS: {
+ url.setScheme("http");
+ _ui.leUrl->setFullText(url.toString());
+ // skip ahead to next page, since the user would expect us to retry automatically
+ wizard()->next();
+ } break;
case OwncloudConnectionMethodDialog::Client_Side_TLS:
#if QT_VERSION >= QT_VERSION_CHECK(5, 4, 0)
addCertDial->show();
- connect(addCertDial, SIGNAL(accepted()),this,SLOT(slotCertificateAccepted()));
+ connect(addCertDial, SIGNAL(accepted()), this, SLOT(slotCertificateAccepted()));
#endif
break;
case OwncloudConnectionMethodDialog::Closed:
_progressIndi->stopAnimation();
}
-QString subjectInfoHelper(const QSslCertificate& cert, const QByteArray &qa)
+QString subjectInfoHelper(const QSslCertificate &cert, const QByteArray &qa)
{
-#if QT_VERSION < QT_VERSION_CHECK(5,0,0)
+#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
return cert.subjectInfo(qa);
#else
return cert.subjectInfo(qa).join(QLatin1Char('/'));
QList<QSslCertificate> clientCaCertificates;
QFile certFile(addCertDial->getCertificatePath());
certFile.open(QFile::ReadOnly);
- if(QSslCertificate::importPkcs12(&certFile,
- &_ocWizard->_clientSslKey, &_ocWizard->_clientSslCertificate,
- &clientCaCertificates,
- addCertDial->getCertificatePasswd().toLocal8Bit())){
+ if (QSslCertificate::importPkcs12(&certFile,
+ &_ocWizard->_clientSslKey, &_ocWizard->_clientSslCertificate,
+ &clientCaCertificates,
+ addCertDial->getCertificatePasswd().toLocal8Bit())) {
AccountPtr acc = _ocWizard->account();
// to re-create the session ticket because we added a key/cert
* @brief The OwncloudSetupPage class
* @ingroup gui
*/
-class OwncloudSetupPage: public QWizardPage
+class OwncloudSetupPage : public QWizardPage
{
Q_OBJECT
public:
- OwncloudSetupPage(QWidget *parent=0);
- ~OwncloudSetupPage();
-
- virtual bool isComplete() const Q_DECL_OVERRIDE;
- virtual void initializePage() Q_DECL_OVERRIDE;
- virtual int nextId() const Q_DECL_OVERRIDE;
- void setServerUrl( const QString& );
- void setAllowPasswordStorage( bool );
- bool validatePage() Q_DECL_OVERRIDE;
- QString url() const;
- QString localFolder() const;
- void setRemoteFolder( const QString& remoteFolder);
- void setMultipleFoldersExist( bool exist );
- void setAuthType(WizardCommon::AuthType type);
+ OwncloudSetupPage(QWidget *parent = 0);
+ ~OwncloudSetupPage();
+
+ virtual bool isComplete() const Q_DECL_OVERRIDE;
+ virtual void initializePage() Q_DECL_OVERRIDE;
+ virtual int nextId() const Q_DECL_OVERRIDE;
+ void setServerUrl(const QString &);
+ void setAllowPasswordStorage(bool);
+ bool validatePage() Q_DECL_OVERRIDE;
+ QString url() const;
+ QString localFolder() const;
+ void setRemoteFolder(const QString &remoteFolder);
+ void setMultipleFoldersExist(bool exist);
+ void setAuthType(WizardCommon::AuthType type);
public slots:
- void setErrorString( const QString&, bool retryHTTPonly );
- void startSpinner();
- void stopSpinner();
- void slotCertificateAccepted();
+ void setErrorString(const QString &, bool retryHTTPonly);
+ void startSpinner();
+ void stopSpinner();
+ void slotCertificateAccepted();
protected slots:
- void slotUrlChanged(const QString&);
- void slotUrlEditFinished();
+ void slotUrlChanged(const QString &);
+ void slotUrlEditFinished();
- void setupCustomization();
+ void setupCustomization();
signals:
- void determineAuthType(const QString&);
+ void determineAuthType(const QString &);
private:
- bool urlHasChanged();
-
- Ui_OwncloudSetupPage _ui;
-
- QString _oCUrl;
- QString _ocUser;
- bool _authTypeKnown;
- bool _checking;
- bool _multipleFoldersExist;
- WizardCommon::AuthType _authType;
-
- QProgressIndicator* _progressIndi;
- QButtonGroup* _selectiveSyncButtons;
- QString _remoteFolder;
- AddCertificateDialog* addCertDial;
- OwncloudWizard* _ocWizard;
+ bool urlHasChanged();
+
+ Ui_OwncloudSetupPage _ui;
+
+ QString _oCUrl;
+ QString _ocUser;
+ bool _authTypeKnown;
+ bool _checking;
+ bool _multipleFoldersExist;
+ WizardCommon::AuthType _authType;
+
+ QProgressIndicator *_progressIndi;
+ QButtonGroup *_selectiveSyncButtons;
+ QString _remoteFolder;
+ AddCertificateDialog *addCertDial;
+ OwncloudWizard *_ocWizard;
};
} // namespace OCC
#include "creds/shibbolethcredentials.h"
#include "creds/shibboleth/shibbolethwebview.h"
-namespace OCC
-{
+namespace OCC {
OwncloudShibbolethCredsPage::OwncloudShibbolethCredsPage()
- : AbstractCredentialsWizardPage(),
- _browser(0),
- _afterInitialSetup(false)
-{}
+ : AbstractCredentialsWizardPage()
+ , _browser(0)
+ , _afterInitialSetup(false)
+{
+}
void OwncloudShibbolethCredsPage::setupBrowser()
{
if (!_browser.isNull()) {
return;
}
- OwncloudWizard *ocWizard = qobject_cast<OwncloudWizard*>(wizard());
+ OwncloudWizard *ocWizard = qobject_cast<OwncloudWizard *>(wizard());
AccountPtr account = ocWizard->account();
// we need to reset the cookie jar to drop temporary cookies (like the shib cookie)
qnam->setCookieJar(jar);
_browser = new ShibbolethWebView(account);
- connect(_browser, SIGNAL(shibbolethCookieReceived(const QNetworkCookie&)),
- this, SLOT(slotShibbolethCookieReceived(const QNetworkCookie&)), Qt::QueuedConnection);
+ connect(_browser, SIGNAL(shibbolethCookieReceived(const QNetworkCookie &)),
+ this, SLOT(slotShibbolethCookieReceived(const QNetworkCookie &)), Qt::QueuedConnection);
connect(_browser, SIGNAL(rejected()),
- this, SLOT(slotBrowserRejected()));
+ this, SLOT(slotBrowserRejected()));
_browser->move(ocWizard->x(), ocWizard->y());
_browser->show();
int OwncloudShibbolethCredsPage::nextId() const
{
- return WizardCommon::Page_AdvancedSetup;
+ return WizardCommon::Page_AdvancedSetup;
}
void OwncloudShibbolethCredsPage::setConnected()
wizard()->show();
}
-AbstractCredentials* OwncloudShibbolethCredsPage::getCredentials() const
+AbstractCredentials *OwncloudShibbolethCredsPage::getCredentials() const
{
return new ShibbolethCredentials(_cookie);
}
*/
class OwncloudShibbolethCredsPage : public AbstractCredentialsWizardPage
{
- Q_OBJECT
+ Q_OBJECT
public:
- OwncloudShibbolethCredsPage();
+ OwncloudShibbolethCredsPage();
- AbstractCredentials* getCredentials() const Q_DECL_OVERRIDE;
+ AbstractCredentials *getCredentials() const Q_DECL_OVERRIDE;
- void initializePage() Q_DECL_OVERRIDE;
- int nextId() const Q_DECL_OVERRIDE;
- void setConnected();
+ void initializePage() Q_DECL_OVERRIDE;
+ int nextId() const Q_DECL_OVERRIDE;
+ void setConnected();
Q_SIGNALS:
- void connectToOCUrl(const QString&);
+ void connectToOCUrl(const QString &);
public Q_SLOTS:
- void setVisible(bool visible) Q_DECL_OVERRIDE;
+ void setVisible(bool visible) Q_DECL_OVERRIDE;
private Q_SLOTS:
- void slotShibbolethCookieReceived(const QNetworkCookie&);
- void slotBrowserRejected();
+ void slotShibbolethCookieReceived(const QNetworkCookie &);
+ void slotBrowserRejected();
private:
- void setupBrowser();
+ void setupBrowser();
- QPointer<ShibbolethWebView> _browser;
- bool _afterInitialSetup;
- QNetworkCookie _cookie;
+ QPointer<ShibbolethWebView> _browser;
+ bool _afterInitialSetup;
+ QNetworkCookie _cookie;
};
} // namespace OCC
#include <stdlib.h>
-namespace OCC
-{
+namespace OCC {
Q_LOGGING_CATEGORY(lcWizard, "gui.wizard", QtInfoMsg)
OwncloudWizard::OwncloudWizard(QWidget *parent)
- : QWizard(parent),
- _account(0),
- _setupPage(new OwncloudSetupPage(this)),
- _httpCredsPage(new OwncloudHttpCredsPage(this)),
+ : QWizard(parent)
+ , _account(0)
+ , _setupPage(new OwncloudSetupPage(this))
+ , _httpCredsPage(new OwncloudHttpCredsPage(this))
+ ,
#ifndef NO_SHIBBOLETH
- _shibbolethCredsPage(new OwncloudShibbolethCredsPage),
+ _shibbolethCredsPage(new OwncloudShibbolethCredsPage)
+ ,
#endif
- _advancedSetupPage(new OwncloudAdvancedSetupPage),
- _resultPage(new OwncloudWizardResultPage),
- _credentialsPage(0),
- _setupLog()
+ _advancedSetupPage(new OwncloudAdvancedSetupPage)
+ , _resultPage(new OwncloudWizardResultPage)
+ , _credentialsPage(0)
+ , _setupLog()
{
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
setPage(WizardCommon::Page_ServerSetup, _setupPage);
// note: start Id is set by the calling class depending on if the
// welcome text is to be shown or not.
- setWizardStyle( QWizard::ModernStyle );
+ setWizardStyle(QWizard::ModernStyle);
- connect( this, SIGNAL(currentIdChanged(int)), SLOT(slotCurrentPageChanged(int)));
- connect( _setupPage, SIGNAL(determineAuthType(QString)), SIGNAL(determineAuthType(QString)));
- connect( _httpCredsPage, SIGNAL(connectToOCUrl(QString)), SIGNAL(connectToOCUrl(QString)));
+ connect(this, SIGNAL(currentIdChanged(int)), SLOT(slotCurrentPageChanged(int)));
+ connect(_setupPage, SIGNAL(determineAuthType(QString)), SIGNAL(determineAuthType(QString)));
+ connect(_httpCredsPage, SIGNAL(connectToOCUrl(QString)), SIGNAL(connectToOCUrl(QString)));
#ifndef NO_SHIBBOLETH
- connect( _shibbolethCredsPage, SIGNAL(connectToOCUrl(QString)), SIGNAL(connectToOCUrl(QString)));
+ connect(_shibbolethCredsPage, SIGNAL(connectToOCUrl(QString)), SIGNAL(connectToOCUrl(QString)));
#endif
- connect( _advancedSetupPage, SIGNAL(createLocalAndRemoteFolders(QString, QString)),
- SIGNAL(createLocalAndRemoteFolders(QString, QString)));
+ connect(_advancedSetupPage, SIGNAL(createLocalAndRemoteFolders(QString, QString)),
+ SIGNAL(createLocalAndRemoteFolders(QString, QString)));
connect(this, SIGNAL(customButtonClicked(int)), this, SIGNAL(skipFolderConfiguration()));
Theme *theme = Theme::instance();
- setWindowTitle( tr("%1 Connection Wizard").arg(theme->appNameGUI()));
+ setWindowTitle(tr("%1 Connection Wizard").arg(theme->appNameGUI()));
setWizardStyle(QWizard::ModernStyle);
- setPixmap( QWizard::BannerPixmap, theme->wizardHeaderBanner() );
- setPixmap( QWizard::LogoPixmap, theme->wizardHeaderLogo() );
- setOption( QWizard::NoBackButtonOnStartPage );
- setOption( QWizard::NoBackButtonOnLastPage );
- setOption( QWizard::NoCancelButton );
+ setPixmap(QWizard::BannerPixmap, theme->wizardHeaderBanner());
+ setPixmap(QWizard::LogoPixmap, theme->wizardHeaderLogo());
+ setOption(QWizard::NoBackButtonOnStartPage);
+ setOption(QWizard::NoBackButtonOnLastPage);
+ setOption(QWizard::NoCancelButton);
setTitleFormat(Qt::RichText);
setSubTitleFormat(Qt::RichText);
setButtonText(QWizard::CustomButton1, tr("Skip folders configuration"));
QString OwncloudWizard::localFolder() const
{
- return(_advancedSetupPage->localFolder());
+ return (_advancedSetupPage->localFolder());
}
QStringList OwncloudWizard::selectiveSyncBlacklist() const
_resultPage->setComplete(enable);
}
-void OwncloudWizard::setRemoteFolder( const QString& remoteFolder )
+void OwncloudWizard::setRemoteFolder(const QString &remoteFolder)
{
- _advancedSetupPage->setRemoteFolder( remoteFolder );
- _resultPage->setRemoteFolder( remoteFolder );
+ _advancedSetupPage->setRemoteFolder(remoteFolder);
+ _resultPage->setRemoteFolder(remoteFolder);
}
void OwncloudWizard::successfulStep()
void OwncloudWizard::setAuthType(WizardCommon::AuthType type)
{
- _setupPage->setAuthType(type);
+ _setupPage->setAuthType(type);
#ifndef NO_SHIBBOLETH
- if (type == WizardCommon::Shibboleth) {
- _credentialsPage = _shibbolethCredsPage;
- } else
+ if (type == WizardCommon::Shibboleth) {
+ _credentialsPage = _shibbolethCredsPage;
+ } else
#endif
- {
- _credentialsPage = _httpCredsPage;
- }
- next();
+ {
+ _credentialsPage = _httpCredsPage;
+ }
+ next();
}
// TODO: update this function
-void OwncloudWizard::slotCurrentPageChanged( int id )
+void OwncloudWizard::slotCurrentPageChanged(int id)
{
qCDebug(lcWizard) << "Current Wizard page changed to " << id;
- if( id == WizardCommon::Page_ServerSetup ) {
+ if (id == WizardCommon::Page_ServerSetup) {
emit clearPendingRequests();
}
- if( id == WizardCommon::Page_Result ) {
+ if (id == WizardCommon::Page_Result) {
disconnect(this, SIGNAL(finished(int)), this, SIGNAL(basicSetupFinished(int)));
emit basicSetupFinished(QDialog::Accepted);
- appendToConfigurationLog( QString::null );
+ appendToConfigurationLog(QString::null);
// Immediately close on show, we currently don't want this page anymore
done(Accepted);
}
setOption(QWizard::HaveCustomButton1, id == WizardCommon::Page_AdvancedSetup);
}
-void OwncloudWizard::displayError( const QString& msg, bool retryHTTPonly )
+void OwncloudWizard::displayError(const QString &msg, bool retryHTTPonly)
{
switch (currentId()) {
case WizardCommon::Page_ServerSetup:
- _setupPage->setErrorString( msg, retryHTTPonly );
+ _setupPage->setErrorString(msg, retryHTTPonly);
break;
case WizardCommon::Page_HttpCreds:
}
}
-void OwncloudWizard::appendToConfigurationLog( const QString& msg, LogType /*type*/ )
+void OwncloudWizard::appendToConfigurationLog(const QString &msg, LogType /*type*/)
{
_setupLog << msg;
qCDebug(lcWizard) << "Setup-Log: " << msg;
}
-void OwncloudWizard::setOCUrl( const QString& url )
+void OwncloudWizard::setOCUrl(const QString &url)
{
- _setupPage->setServerUrl( url );
+ _setupPage->setServerUrl(url);
}
-AbstractCredentials* OwncloudWizard::getCredentials() const
+AbstractCredentials *OwncloudWizard::getCredentials() const
{
- if (_credentialsPage) {
- return _credentialsPage->getCredentials();
- }
+ if (_credentialsPage) {
+ return _credentialsPage->getCredentials();
+ }
- return 0;
+ return 0;
}
} // end namespace
{
Q_OBJECT
public:
-
enum LogType {
- LogPlain,
- LogParagraph
+ LogPlain,
+ LogParagraph
};
OwncloudWizard(QWidget *parent = 0);
void setAccount(AccountPtr account);
AccountPtr account() const;
- void setOCUrl( const QString& );
+ void setOCUrl(const QString &);
- void setupCustomMedia( QVariant, QLabel* );
+ void setupCustomMedia(QVariant, QLabel *);
QString ocUrl() const;
QString localFolder() const;
QStringList selectiveSyncBlacklist() const;
void enableFinishOnResultWidget(bool enable);
- void displayError( const QString&, bool retryHTTPonly);
- AbstractCredentials* getCredentials() const;
+ void displayError(const QString &, bool retryHTTPonly);
+ AbstractCredentials *getCredentials() const;
// FIXME: Can those be local variables?
// Set from the OwncloudSetupPage, later used from OwncloudHttpCredsPage
public slots:
void setAuthType(WizardCommon::AuthType type);
- void setRemoteFolder( const QString& );
- void appendToConfigurationLog( const QString& msg, LogType type = LogParagraph );
- void slotCurrentPageChanged( int );
+ void setRemoteFolder(const QString &);
+ void appendToConfigurationLog(const QString &msg, LogType type = LogParagraph);
+ void slotCurrentPageChanged(int);
void successfulStep();
signals:
void clearPendingRequests();
- void determineAuthType(const QString&);
- void connectToOCUrl( const QString& );
- void createLocalAndRemoteFolders(const QString&, const QString&);
+ void determineAuthType(const QString &);
+ void connectToOCUrl(const QString &);
+ void createLocalAndRemoteFolders(const QString &, const QString &);
// make sure to connect to this, rather than finished(int)!!
- void basicSetupFinished( int );
+ void basicSetupFinished(int);
void skipFolderConfiguration();
void needCertificate();
private:
AccountPtr _account;
- OwncloudSetupPage* _setupPage;
- OwncloudHttpCredsPage* _httpCredsPage;
+ OwncloudSetupPage *_setupPage;
+ OwncloudHttpCredsPage *_httpCredsPage;
#ifndef NO_SHIBBOLETH
- OwncloudShibbolethCredsPage* _shibbolethCredsPage;
+ OwncloudShibbolethCredsPage *_shibbolethCredsPage;
#endif
- OwncloudAdvancedSetupPage* _advancedSetupPage;
- OwncloudWizardResultPage* _resultPage;
- AbstractCredentialsWizardPage* _credentialsPage;
+ OwncloudAdvancedSetupPage *_advancedSetupPage;
+ OwncloudWizardResultPage *_resultPage;
+ AbstractCredentialsWizardPage *_credentialsPage;
QStringList _setupLog;
};
#include "wizard/owncloudwizardcommon.h"
#include "theme.h"
-namespace OCC
-{
+namespace OCC {
-namespace WizardCommon
-{
+namespace WizardCommon {
-void setupCustomMedia( const QVariant& variant, QLabel *label )
-{
- if( !label ) return;
+ void setupCustomMedia(const QVariant &variant, QLabel *label)
+ {
+ if (!label)
+ return;
- QPixmap pix = variant.value<QPixmap>();
- if( !pix.isNull() ) {
- label->setPixmap(pix);
- label->setAlignment( Qt::AlignTop | Qt::AlignRight );
- label->setVisible(true);
- } else {
- QString str = variant.toString();
- if( !str.isEmpty() ) {
- label->setText( str );
- label->setTextFormat( Qt::RichText );
+ QPixmap pix = variant.value<QPixmap>();
+ if (!pix.isNull()) {
+ label->setPixmap(pix);
+ label->setAlignment(Qt::AlignTop | Qt::AlignRight);
label->setVisible(true);
- label->setOpenExternalLinks(true);
+ } else {
+ QString str = variant.toString();
+ if (!str.isEmpty()) {
+ label->setText(str);
+ label->setTextFormat(Qt::RichText);
+ label->setVisible(true);
+ label->setOpenExternalLinks(true);
+ }
}
}
-}
-QString titleTemplate()
-{
- return QString::fromLatin1("<font color=\"%1\" size=\"5\">").arg(Theme::instance()->wizardHeaderTitleColor().name()) + QString::fromLatin1("%1</font>");
-}
+ QString titleTemplate()
+ {
+ return QString::fromLatin1("<font color=\"%1\" size=\"5\">").arg(Theme::instance()->wizardHeaderTitleColor().name()) + QString::fromLatin1("%1</font>");
+ }
-QString subTitleTemplate()
-{
- return QString::fromLatin1("<font color=\"%1\">").arg(Theme::instance()->wizardHeaderTitleColor().name()) + QString::fromLatin1("%1</font>");
-}
+ QString subTitleTemplate()
+ {
+ return QString::fromLatin1("<font color=\"%1\">").arg(Theme::instance()->wizardHeaderTitleColor().name()) + QString::fromLatin1("%1</font>");
+ }
-void initErrorLabel(QLabel* errorLabel)
-{
- QString style = QLatin1String("border: 1px solid #eed3d7; border-radius: 5px; padding: 3px;"
- "background-color: #f2dede; color: #b94a48;");
+ void initErrorLabel(QLabel *errorLabel)
+ {
+ QString style = QLatin1String("border: 1px solid #eed3d7; border-radius: 5px; padding: 3px;"
+ "background-color: #f2dede; color: #b94a48;");
- errorLabel->setStyleSheet(style);
- errorLabel->setWordWrap(true);
- errorLabel->setVisible(false);
-}
+ errorLabel->setStyleSheet(style);
+ errorLabel->setWordWrap(true);
+ errorLabel->setVisible(false);
+ }
} // ns WizardCommon
class QVariant;
class QLabel;
-namespace OCC
-{
-
-namespace WizardCommon
-{
-
-void setupCustomMedia( const QVariant& variant, QLabel *label );
-QString titleTemplate();
-QString subTitleTemplate();
-void initErrorLabel(QLabel* errorLabel);
-
-enum AuthType {
- HttpCreds,
- Shibboleth
-};
-
-enum SyncMode {
- SelectiveMode,
- BoxMode
-};
-
-enum Pages {
- Page_ServerSetup,
- Page_HttpCreds,
- Page_ShibbolethCreds,
- Page_AdvancedSetup,
- Page_Result
-};
+namespace OCC {
+
+namespace WizardCommon {
+
+ void setupCustomMedia(const QVariant &variant, QLabel *label);
+ QString titleTemplate();
+ QString subTitleTemplate();
+ void initErrorLabel(QLabel *errorLabel);
+
+ enum AuthType {
+ HttpCreds,
+ Shibboleth
+ };
+
+ enum SyncMode {
+ SelectiveMode,
+ BoxMode
+ };
+
+ enum Pages {
+ Page_ServerSetup,
+ Page_HttpCreds,
+ Page_ShibbolethCreds,
+ Page_AdvancedSetup,
+ Page_Result
+ };
} // ns WizardCommon
#include "wizard/owncloudwizardcommon.h"
#include "theme.h"
-namespace OCC
-{
+namespace OCC {
OwncloudWizardResultPage::OwncloudWizardResultPage()
- : QWizardPage(),
- _localFolder(),
- _remoteFolder(),
- _complete(false),
- _ui()
+ : QWizardPage()
+ , _localFolder()
+ , _remoteFolder()
+ , _complete(false)
+ , _ui()
{
_ui.setupUi(this);
// no fields to register.
setTitle(WizardCommon::subTitleTemplate().arg(tr("Everything set up!")));
// required to show header in QWizard's modern style
- setSubTitle( QLatin1String(" ") );
+ setSubTitle(QLatin1String(" "));
_ui.pbOpenLocal->setText(tr("Open Local Folder"));
_ui.pbOpenLocal->setIcon(QIcon(QLatin1String(":/client/resources/folder-sync.png")));
_ui.pbOpenLocal->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
connect(_ui.pbOpenLocal, SIGNAL(clicked()), SLOT(slotOpenLocal()));
- Theme* theme = Theme::instance();
+ Theme *theme = Theme::instance();
QIcon appIcon = theme->applicationIcon();
_ui.pbOpenServer->setText(tr("Open %1 in Browser").arg(theme->appNameGUI()));
_ui.pbOpenServer->setIcon(appIcon.pixmap(48));
}
OwncloudWizardResultPage::~OwncloudWizardResultPage()
-{}
+{
+}
void OwncloudWizardResultPage::setComplete(bool complete)
{
void OwncloudWizardResultPage::initializePage()
{
- _ui.localFolderLabel->setText( QString::null );
+ _ui.localFolderLabel->setText(QString::null);
}
void OwncloudWizardResultPage::setRemoteFolder(const QString &remoteFolder)
void OwncloudWizardResultPage::setupCustomization()
{
// set defaults for the customize labels.
- _ui.topLabel->setText( QString::null );
+ _ui.topLabel->setText(QString::null);
_ui.topLabel->hide();
- QVariant variant = Theme::instance()->customMedia( Theme::oCSetupResultTop );
- WizardCommon::setupCustomMedia( variant, _ui.topLabel );
+ QVariant variant = Theme::instance()->customMedia(Theme::oCSetupResultTop);
+ WizardCommon::setupCustomMedia(variant, _ui.topLabel);
}
void OwncloudWizardResultPage::slotOpenLocal()
void OwncloudWizardResultPage::slotOpenServer()
{
- Theme* theme = Theme::instance();
+ Theme *theme = Theme::instance();
QUrl url = QUrl(field("OCUrl").toString() + theme->wizardUrlPostfix());
QDesktopServices::openUrl(url);
}
*/
class OwncloudWizardResultPage : public QWizardPage
{
- Q_OBJECT
+ Q_OBJECT
public:
- OwncloudWizardResultPage();
- ~OwncloudWizardResultPage();
+ OwncloudWizardResultPage();
+ ~OwncloudWizardResultPage();
- bool isComplete() const Q_DECL_OVERRIDE;
- void initializePage() Q_DECL_OVERRIDE;
- void setRemoteFolder( const QString& remoteFolder);
+ bool isComplete() const Q_DECL_OVERRIDE;
+ void initializePage() Q_DECL_OVERRIDE;
+ void setRemoteFolder(const QString &remoteFolder);
public slots:
- void setComplete(bool complete);
+ void setComplete(bool complete);
protected slots:
- void slotOpenLocal();
- void slotOpenServer();
+ void slotOpenLocal();
+ void slotOpenServer();
protected:
- void setupCustomization();
+ void setupCustomization();
private:
- QString _localFolder;
- QString _remoteFolder;
- bool _complete;
+ QString _localFolder;
+ QString _remoteFolder;
+ bool _complete;
- Ui_OwncloudWizardResultPage _ui;
+ Ui_OwncloudWizardResultPage _ui;
};
} // namespace OCC
const int verticalMargin(4);
PostfixLineEdit::PostfixLineEdit(QWidget *parent)
- : QLineEdit(parent)
+ : QLineEdit(parent)
{
}
_postfix = postfix;
QFontMetricsF fm(font());
QMargins tm = textMargins();
- tm.setRight(tm.right()+fm.width(_postfix)+verticalMargin);
+ tm.setRight(tm.right() + fm.width(_postfix) + verticalMargin);
setTextMargins(tm);
}
void PostfixLineEdit::paintEvent(QPaintEvent *pe)
{
-
QLineEdit::paintEvent(pe);
QPainter p(this);
//
p.setPen(palette().color(QPalette::Disabled, QPalette::Text));
QFontMetricsF fm(font());
- int start = rect().right()-fm.width(_postfix);
+ int start = rect().right() - fm.width(_postfix);
QStyleOptionFrame panel;
initStyleOption(&panel);
QRect r = style()->subElementRect(QStyle::SE_LineEditContents, &panel, this);
- r.setTop(r.top()+horizontalMargin-1);
+ r.setTop(r.top() + horizontalMargin - 1);
QRect postfixRect(r);
- postfixRect.setLeft(start-verticalMargin);
+ postfixRect.setLeft(start - verticalMargin);
p.drawText(postfixRect, _postfix);
}
PostfixLineEdit(QWidget *parent);
/** @brief sets an optional postfix shown greyed out */
- void setPostfix(const QString& postfix);
+ void setPostfix(const QString &postfix);
/** @brief retrives the postfix */
QString postfix() const;
/** @brief retrieves combined text() and postfix() */
protected:
void paintEvent(QPaintEvent *pe);
+
private:
QString _postfix;
};
#include "creds/abstractcredentials.h"
-Q_DECLARE_METATYPE(QTimer*)
+Q_DECLARE_METATYPE(QTimer *)
namespace OCC {
#if QT_VERSION >= QT_VERSION_CHECK(5, 1, 0)
connect(reply, SIGNAL(encrypted()), SIGNAL(networkActivity()));
#endif
- connect(reply->manager(), SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)), SIGNAL(networkActivity()));
+ connect(reply->manager(), SIGNAL(proxyAuthenticationRequired(QNetworkProxy, QAuthenticator *)), SIGNAL(networkActivity()));
connect(reply, SIGNAL(sslErrors(QList<QSslError>)), SIGNAL(networkActivity()));
connect(reply, SIGNAL(metaDataChanged()), SIGNAL(networkActivity()));
- connect(reply, SIGNAL(downloadProgress(qint64,qint64)), SIGNAL(networkActivity()));
- connect(reply, SIGNAL(uploadProgress(qint64,qint64)), SIGNAL(networkActivity()));
+ connect(reply, SIGNAL(downloadProgress(qint64, qint64)), SIGNAL(networkActivity()));
+ connect(reply, SIGNAL(uploadProgress(qint64, qint64)), SIGNAL(networkActivity()));
}
-QNetworkReply* AbstractNetworkJob::addTimer(QNetworkReply *reply)
+QNetworkReply *AbstractNetworkJob::addTimer(QNetworkReply *reply)
{
reply->setProperty("timer", QVariant::fromValue(&_timer));
return reply;
}
QNetworkReply *AbstractNetworkJob::sendRequest(const QByteArray &verb, const QUrl &url,
- QNetworkRequest req, QIODevice *requestBody)
+ QNetworkRequest req, QIODevice *requestBody)
{
auto reply = _account->sendRequest(verb, url, req, requestBody);
_requestBody = requestBody;
return reply;
}
-QUrl AbstractNetworkJob::makeAccountUrl(const QString& relativePath) const
+QUrl AbstractNetworkJob::makeAccountUrl(const QString &relativePath) const
{
return Utility::concatUrlPath(_account->url(), relativePath);
}
-QUrl AbstractNetworkJob::makeDavUrl(const QString& relativePath) const
+QUrl AbstractNetworkJob::makeDavUrl(const QString &relativePath) const
{
return Utility::concatUrlPath(_account->davUrl(), relativePath);
}
{
_timer.stop();
- if( _reply->error() == QNetworkReply::SslHandshakeFailedError ) {
+ if (_reply->error() == QNetworkReply::SslHandshakeFailedError) {
qCWarning(lcNetworkJob) << "SslHandshakeFailedError: " << errorString() << " : can be caused by a webserver wanting SSL client certificates";
}
- if( _reply->error() != QNetworkReply::NoError ) {
+ if (_reply->error() != QNetworkReply::NoError) {
qCWarning(lcNetworkJob) << _reply->error() << errorString()
- << _reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
+ << _reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
if (_reply->error() == QNetworkReply::ProxyAuthenticationRequiredError) {
qCWarning(lcNetworkJob) << _reply->rawHeader("Proxy-Authenticate");
}
// ### some of the qWarnings here should be exported via displayErrors() so they
// ### can be presented to the user if the job executor has a GUI
QByteArray verb = requestVerb(*reply());
- if (requestedUrl.scheme() == QLatin1String("https") &&
- redirectUrl.scheme() == QLatin1String("http")) {
+ if (requestedUrl.scheme() == QLatin1String("https") && redirectUrl.scheme() == QLatin1String("http")) {
qCWarning(lcNetworkJob) << this << "HTTPS->HTTP downgrade detected!";
} else if (requestedUrl == redirectUrl || _redirectCount >= maxRedirects()) {
qCWarning(lcNetworkJob) << this << "Redirect loop detected!";
_requestBody->seek(0);
}
sendRequest(
- verb,
- redirectUrl,
- reply()->request(),
- _requestBody);
+ verb,
+ redirectUrl,
+ reply()->request(),
+ _requestBody);
return;
}
}
AbstractCredentials *creds = _account->credentials();
- if (!creds->stillValid(_reply) && ! _ignoreCredentialFailure) {
+ if (!creds->stillValid(_reply) && !_ignoreCredentialFailure) {
_account->handleInvalidCredentials();
}
}
}
-QString AbstractNetworkJob::errorStringParsingBody(QByteArray* body)
+QString AbstractNetworkJob::errorStringParsingBody(QByteArray *body)
{
QString base = errorString();
if (base.isEmpty() || !reply()) {
_timer.start();
const QUrl url = account()->url();
- const QString displayUrl = QString( "%1://%2%3").arg(url.scheme()).arg(url.host()).arg(url.path());
+ const QString displayUrl = QString("%1://%2%3").arg(url.scheme()).arg(url.host()).arg(url.path());
QString parentMetaObjectName = parent() ? parent()->metaObject()->className() : "";
qCInfo(lcNetworkJob) << metaObject()->className() << "created for" << displayUrl << "+" << path() << parentMetaObjectName;
NetworkJobTimeoutPauser::NetworkJobTimeoutPauser(QNetworkReply *reply)
{
- _timer = reply->property("timer").value<QTimer*>();
- if(!_timer.isNull()) {
+ _timer = reply->property("timer").value<QTimer *>();
+ if (!_timer.isNull()) {
_timer->stop();
}
}
NetworkJobTimeoutPauser::~NetworkJobTimeoutPauser()
{
- if(!_timer.isNull()) {
+ if (!_timer.isNull()) {
_timer->start();
}
}
-QString extractErrorMessage(const QByteArray& errorResponse)
+QString extractErrorMessage(const QByteArray &errorResponse)
{
QXmlStreamReader reader(errorResponse);
reader.readNextStartElement();
} else if (reader.name() == QLatin1String("exception")) {
exception = reader.readElementText();
}
-
}
// Fallback, if message could not be found
return exception;
}
-QString errorMessage(const QString& baseError, const QByteArray& body)
+QString errorMessage(const QString &baseError, const QByteArray &body)
{
QString msg = baseError;
QString extra = extractErrorMessage(body);
return msg;
}
-QByteArray requestVerb(const QNetworkReply& reply)
+QByteArray requestVerb(const QNetworkReply &reply)
{
switch (reply.operation()) {
case QNetworkAccessManager::HeadOperation:
return QByteArray();
}
-QString networkReplyErrorString(const QNetworkReply& reply)
+QString networkReplyErrorString(const QNetworkReply &reply)
{
QString base = reply.errorString();
int httpStatus = reply.attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
return base;
}
- return AbstractNetworkJob::tr("Server replied \"%1 %2\" to \"%3 %4\"").arg(
- QString::number(httpStatus),
- httpReason,
- requestVerb(reply),
+ return AbstractNetworkJob::tr("Server replied \"%1 %2\" to \"%3 %4\"").arg(QString::number(httpStatus), httpReason, requestVerb(reply),
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
- reply.request().url().toString()
+ reply.request().url().toString()
#else
- reply.request().url().toDisplayString()
+ reply.request().url().toDisplayString()
#endif
);
}
* @brief The AbstractNetworkJob class
* @ingroup libsync
*/
-class OWNCLOUDSYNC_EXPORT AbstractNetworkJob : public QObject {
+class OWNCLOUDSYNC_EXPORT AbstractNetworkJob : public QObject
+{
Q_OBJECT
public:
- explicit AbstractNetworkJob(AccountPtr account, const QString &path, QObject* parent = 0);
+ explicit AbstractNetworkJob(AccountPtr account, const QString &path, QObject *parent = 0);
virtual ~AbstractNetworkJob();
virtual void start();
QString path() const { return _path; }
void setReply(QNetworkReply *reply);
- QNetworkReply* reply() const { return _reply; }
+ QNetworkReply *reply() const { return _reply; }
void setIgnoreCredentialFailure(bool ignore);
bool ignoreCredentialFailure() const { return _ignoreCredentialFailure; }
*
* Warning: Needs to call reply()->readAll().
*/
- QString errorStringParsingBody(QByteArray* body = 0);
+ QString errorStringParsingBody(QByteArray *body = 0);
public slots:
void setTimeout(qint64 msec);
*/
void networkError(QNetworkReply *reply);
void networkActivity();
+
protected:
void setupConnections(QNetworkReply *reply);
*
* Takes ownership of the requestBody (to allow redirects).
*/
- QNetworkReply* sendRequest(const QByteArray& verb, const QUrl &url,
- QNetworkRequest req = QNetworkRequest(),
- QIODevice *requestBody = 0);
+ QNetworkReply *sendRequest(const QByteArray &verb, const QUrl &url,
+ QNetworkRequest req = QNetworkRequest(),
+ QIODevice *requestBody = 0);
// sendRequest does not take a relative path instead of an url,
// but the old API allowed that. We have this undefined overload
// to help catch usage errors
- QNetworkReply* sendRequest(const QByteArray& verb, const QString &relativePath,
- QNetworkRequest req = QNetworkRequest(),
- QIODevice *requestBody = 0);
+ QNetworkReply *sendRequest(const QByteArray &verb, const QString &relativePath,
+ QNetworkRequest req = QNetworkRequest(),
+ QIODevice *requestBody = 0);
/// Creates a url for the account from a relative path
- QUrl makeAccountUrl(const QString& relativePath) const;
+ QUrl makeAccountUrl(const QString &relativePath) const;
/// Like makeAccountUrl() but uses the account's dav base path
- QUrl makeDavUrl(const QString& relativePath) const;
+ QUrl makeDavUrl(const QString &relativePath) const;
int maxRedirects() const { return 10; }
*/
virtual void onTimedOut();
- QByteArray _responseTimestamp;
- bool _timedout; // set to true when the timeout slot is received
+ QByteArray _responseTimestamp;
+ bool _timedout; // set to true when the timeout slot is received
// Automatically follows redirects. Note that this only works for
// GET requests that don't set up any HTTP body or other flags.
- bool _followRedirects;
+ bool _followRedirects;
private slots:
void slotFinished();
AccountPtr _account;
private:
- QNetworkReply* addTimer(QNetworkReply *reply);
+ QNetworkReply *addTimer(QNetworkReply *reply);
bool _ignoreCredentialFailure;
QPointer<QNetworkReply> _reply; // (QPointer because the NetworkManager may be destroyed before the jobs at exit)
QString _path;
/**
* @brief Internal Helper class
*/
-class NetworkJobTimeoutPauser {
+class NetworkJobTimeoutPauser
+{
public:
NetworkJobTimeoutPauser(QNetworkReply *reply);
~NetworkJobTimeoutPauser();
+
private:
QPointer<QTimer> _timer;
};
*
* Returns a null string if no message was found.
*/
-QString OWNCLOUDSYNC_EXPORT extractErrorMessage(const QByteArray& errorResponse);
+QString OWNCLOUDSYNC_EXPORT extractErrorMessage(const QByteArray &errorResponse);
/** Builds a error message based on the error and the reply body. */
-QString OWNCLOUDSYNC_EXPORT errorMessage(const QString& baseError, const QByteArray& body);
+QString OWNCLOUDSYNC_EXPORT errorMessage(const QString &baseError, const QByteArray &body);
/** Helper to construct the HTTP verb used in the request
*
* Returns an empty QByteArray for UnknownOperation.
*/
-QByteArray OWNCLOUDSYNC_EXPORT requestVerb(const QNetworkReply& reply);
+QByteArray OWNCLOUDSYNC_EXPORT requestVerb(const QNetworkReply &reply);
/** Nicer errorString() for QNetworkReply
*
*
* This function produces clearer error messages for HTTP errors.
*/
-QString OWNCLOUDSYNC_EXPORT networkReplyErrorString(const QNetworkReply& reply);
+QString OWNCLOUDSYNC_EXPORT networkReplyErrorString(const QNetworkReply &reply);
} // namespace OCC
-
-
#include "accessmanager.h"
#include "utility.h"
-namespace OCC
-{
+namespace OCC {
Q_LOGGING_CATEGORY(lcAccessManager, "sync.accessmanager", QtInfoMsg)
-AccessManager::AccessManager(QObject* parent)
- : QNetworkAccessManager (parent)
+AccessManager::AccessManager(QObject *parent)
+ : QNetworkAccessManager(parent)
{
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) && defined(Q_OS_MAC)
// FIXME Workaround http://stackoverflow.com/a/15707366/2941 https://bugreports.qt-project.org/browse/QTBUG-30434
setCookieJar(new CookieJar);
}
-void AccessManager::setRawCookie(const QByteArray &rawCookie, const QUrl &url)
+void AccessManager::setRawCookie(const QByteArray &rawCookie, const QUrl &url)
{
QNetworkCookie cookie(rawCookie.left(rawCookie.indexOf('=')),
- rawCookie.mid(rawCookie.indexOf('=')+1));
+ rawCookie.mid(rawCookie.indexOf('=') + 1));
qCDebug(lcAccessManager) << cookie.name() << cookie.value();
QList<QNetworkCookie> cookieList;
cookieList.append(cookie);
jar->setCookiesFromUrl(cookieList, url);
}
-QNetworkReply* AccessManager::createRequest(QNetworkAccessManager::Operation op, const QNetworkRequest& request, QIODevice* outgoingData)
+QNetworkReply *AccessManager::createRequest(QNetworkAccessManager::Operation op, const QNetworkRequest &request, QIODevice *outgoingData)
{
QNetworkRequest newRequest(request);
// For PROPFIND (assumed to be a WebDAV op), set xml/utf8 as content type/encoding
// This needs extension
if (verb == "PROPFIND") {
- newRequest.setHeader( QNetworkRequest::ContentTypeHeader, QLatin1String("text/xml; charset=utf-8"));
+ newRequest.setHeader(QNetworkRequest::ContentTypeHeader, QLatin1String("text/xml; charset=utf-8"));
}
return QNetworkAccessManager::createRequest(op, newRequest, outgoingData);
}
class QByteArray;
class QUrl;
-namespace OCC
-{
+namespace OCC {
/**
* @brief The AccessManager class
Q_OBJECT
public:
- AccessManager(QObject* parent = 0);
+ AccessManager(QObject *parent = 0);
- void setRawCookie(const QByteArray &rawCookie, const QUrl &url);
+ void setRawCookie(const QByteArray &rawCookie, const QUrl &url);
protected:
- QNetworkReply* createRequest(QNetworkAccessManager::Operation op, const QNetworkRequest& request, QIODevice* outgoingData = 0) Q_DECL_OVERRIDE;
+ QNetworkReply *createRequest(QNetworkAccessManager::Operation op, const QNetworkRequest &request, QIODevice *outgoingData = 0) Q_DECL_OVERRIDE;
};
} // namespace OCC
Account::Account(QObject *parent)
: QObject(parent)
, _capabilities(QVariantMap())
- , _davPath( Theme::instance()->webDavPath() )
+ , _davPath(Theme::instance()->webDavPath())
{
qRegisterMetaType<AccountPtr>("AccountPtr");
}
}
// make sure to have a trailing slash
- if( !_davPath.endsWith('/') ) {
+ if (!_davPath.endsWith('/')) {
QString dp(_davPath);
dp.append('/');
return dp;
if (jar) {
_am->setCookieJar(jar);
}
- connect(_am.data(), SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)),
- SLOT(slotHandleSslErrors(QNetworkReply*,QList<QSslError>)));
- connect(_am.data(), SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)),
- SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)));
+ connect(_am.data(), SIGNAL(sslErrors(QNetworkReply *, QList<QSslError>)),
+ SLOT(slotHandleSslErrors(QNetworkReply *, QList<QSslError>)));
+ connect(_am.data(), SIGNAL(proxyAuthenticationRequired(QNetworkProxy, QAuthenticator *)),
+ SIGNAL(proxyAuthenticationRequired(QNetworkProxy, QAuthenticator *)));
connect(_credentials.data(), SIGNAL(fetched()),
- SLOT(slotCredentialsFetched()));
+ SLOT(slotCredentialsFetched()));
connect(_credentials.data(), SIGNAL(asked()),
- SLOT(slotCredentialsAsked()));
+ SLOT(slotCredentialsAsked()));
}
QUrl Account::davUrl() const
*/
void Account::clearCookieJar()
{
- auto jar = qobject_cast<CookieJar*>(_am->cookieJar());
+ auto jar = qobject_cast<CookieJar *>(_am->cookieJar());
ASSERT(jar);
jar->setAllCookies(QList<QNetworkCookie>());
emit wantsAccountSaved(this);
}
qCDebug(lcAccount) << "Resetting QNAM";
- QNetworkCookieJar* jar = _am->cookieJar();
+ QNetworkCookieJar *jar = _am->cookieJar();
// Use a QSharedPointer to allow locking the life of the QNAM on the stack.
// Make it call deleteLater to make sure that we can return to any QNAM stack frames safely.
_am = QSharedPointer<QNetworkAccessManager>(_credentials->getQNAM(), &QObject::deleteLater);
_am->setCookieJar(jar); // takes ownership of the old cookie jar
- connect(_am.data(), SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)),
- SLOT(slotHandleSslErrors(QNetworkReply*,QList<QSslError>)));
- connect(_am.data(), SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)),
- SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)));
+ connect(_am.data(), SIGNAL(sslErrors(QNetworkReply *, QList<QSslError>)),
+ SLOT(slotHandleSslErrors(QNetworkReply *, QList<QSslError>)));
+ connect(_am.data(), SIGNAL(proxyAuthenticationRequired(QNetworkProxy, QAuthenticator *)),
+ SIGNAL(proxyAuthenticationRequired(QNetworkProxy, QAuthenticator *)));
}
QNetworkAccessManager *Account::networkAccessManager()
{
if (_credentials) {
QString prefix = _credentials->authType();
- QString value = _settingsMap.value(prefix+"_"+key).toString();
+ QString value = _settingsMap.value(prefix + "_" + key).toString();
if (value.isEmpty()) {
value = _settingsMap.value(key).toString();
}
{
if (_credentials) {
QString prefix = _credentials->authType();
- _settingsMap.insert(prefix+"_"+key, value);
+ _settingsMap.insert(prefix + "_" + key, value);
}
}
-void Account::slotHandleSslErrors(QNetworkReply *reply , QList<QSslError> errors)
+void Account::slotHandleSslErrors(QNetworkReply *reply, QList<QSslError> errors)
{
NetworkJobTimeoutPauser pauser(reply);
QString out;
QDebug(&out) << "SSL-Errors happened for url " << reply->url().toString();
- foreach(const QSslError &error, errors) {
+ foreach (const QSslError &error, errors) {
QDebug(&out) << "\tError in " << error.certificate() << ":"
- << error.errorString() << "("<< error.error() << ")" << "\n";
+ << error.errorString() << "(" << error.error() << ")"
+ << "\n";
}
bool allPreviouslyRejected = true;
}
// If all certs have previously been rejected by the user, don't ask again.
- if( allPreviouslyRejected ) {
+ if (allPreviouslyRejected) {
qCInfo(lcAccount) << out << "Certs not trusted by user decision, returning.";
return;
}
QList<QSslCertificate> approvedCerts;
- if (_sslErrorHandler.isNull() ) {
+ if (_sslErrorHandler.isNull()) {
qCWarning(lcAccount) << out << "called without valid SSL error handler for account" << url();
return;
}
QPointer<QObject> guard = reply;
if (_sslErrorHandler->handleErrors(errors, reply->sslConfiguration(), &approvedCerts, sharedFromThis())) {
- if (!guard) return;
+ if (!guard)
+ return;
QSslSocket::addDefaultCaCertificates(approvedCerts);
addApprovedCerts(approvedCerts);
// certificate changes.
reply->ignoreSslErrors(errors);
} else {
- if (!guard) return;
+ if (!guard)
+ return;
// Mark all involved certificates as rejected, so we don't ask the user again.
foreach (const QSslError &error, errors) {
// FIXME: Use Qt 5.5 QVersionNumber
auto components = serverVersion().split('.');
return makeServerVersion(components.value(0).toInt(),
- components.value(1).toInt(),
- components.value(2).toInt());
+ components.value(1).toInt(),
+ components.value(2).toInt());
}
int Account::makeServerVersion(int majorVersion, int minorVersion, int patchVersion)
return serverVersionInt() < makeServerVersion(7, 0, 0);
}
-void Account::setServerVersion(const QString& version)
+void Account::setServerVersion(const QString &version)
{
if (version == _serverVersion) {
return;
void Account::setNonShib(bool nonShib)
{
- if( nonShib ) {
+ if (nonShib) {
_davPath = Theme::instance()->webDavPathNonShib();
} else {
_davPath = Theme::instance()->webDavPath();
}
-
} // namespace OCC
* @brief Reimplement this to handle SSL errors from libsync
* @ingroup libsync
*/
-class AbstractSslErrorHandler {
+class AbstractSslErrorHandler
+{
public:
virtual ~AbstractSslErrorHandler() {}
- virtual bool handleErrors(QList<QSslError>, const QSslConfiguration &conf, QList<QSslCertificate>*, AccountPtr) = 0;
+ virtual bool handleErrors(QList<QSslError>, const QSslConfiguration &conf, QList<QSslCertificate> *, AccountPtr) = 0;
};
/**
* The Account has a name and url. It also has information about credentials,
* SSL errors and certificates.
*/
-class OWNCLOUDSYNC_EXPORT Account : public QObject {
+class OWNCLOUDSYNC_EXPORT Account : public QObject
+{
Q_OBJECT
public:
static AccountPtr create();
void setDavUser(const QString &newDavUser);
QImage avatar() const;
- void setAvatar(const QImage& img);
+ void setAvatar(const QImage &img);
/// The name of the account as shown in the toolbar
QString displayName() const;
* @returns the (themeable) dav path for the account.
*/
QString davPath() const;
- void setDavPath(const QString&s) { _davPath = s; }
+ void setDavPath(const QString &s) { _davPath = s; }
void setNonShib(bool nonShib);
/** Returns webdav entry URL, based on url() */
QUrl davUrl() const;
/** Holds the accounts credentials */
- AbstractCredentials* credentials() const;
+ AbstractCredentials *credentials() const;
void setCredentials(AbstractCredentials *cred);
// For creating various network requests
- QNetworkReply* sendRequest(const QByteArray &verb,
- const QUrl &url,
- QNetworkRequest req = QNetworkRequest(),
- QIODevice *data = 0);
+ QNetworkReply *sendRequest(const QByteArray &verb,
+ const QUrl &url,
+ QNetworkRequest req = QNetworkRequest(),
+ QIODevice *data = 0);
/** The ssl configuration during the first connection */
QSslConfiguration getOrCreateSslConfig();
void setSslErrorHandler(AbstractSslErrorHandler *handler);
// To be called by credentials only, for storing username and the like
- QVariant credentialSetting(const QString& key) const;
- void setCredentialSetting(const QString& key, const QVariant &value);
+ QVariant credentialSetting(const QString &key) const;
+ void setCredentialSetting(const QString &key, const QVariant &value);
/** Assign a client certificate */
void setCertificate(const QByteArray certficate = QByteArray(), const QString privateKey = QString());
QString cookieJarPath();
void resetNetworkAccessManager();
- QNetworkAccessManager* networkAccessManager();
+ QNetworkAccessManager *networkAccessManager();
QSharedPointer<QNetworkAccessManager> sharedNetworkAccessManager();
/// Called by network jobs on credential errors, emits invalidCredentials()
/// Triggered by handleInvalidCredentials()
void invalidCredentials();
- void credentialsFetched(AbstractCredentials* credentials);
- void credentialsAsked(AbstractCredentials* credentials);
+ void credentialsFetched(AbstractCredentials *credentials);
+ void credentialsAsked(AbstractCredentials *credentials);
/// Forwards from QNetworkAccessManager::proxyAuthenticationRequired().
- void proxyAuthenticationRequired(const QNetworkProxy&, QAuthenticator*);
+ void proxyAuthenticationRequired(const QNetworkProxy &, QAuthenticator *);
// e.g. when the approved SSL certificates changed
- void wantsAccountSaved(Account* acc);
+ void wantsAccountSaved(Account *acc);
- void serverVersionChanged(Account* account, const QString& newVersion, const QString& oldVersion);
+ void serverVersionChanged(Account *account, const QString &newVersion, const QString &oldVersion);
void accountChangedAvatar();
protected Q_SLOTS:
- void slotHandleSslErrors(QNetworkReply*,QList<QSslError>);
+ void slotHandleSslErrors(QNetworkReply *, QList<QSslError>);
void slotCredentialsFetched();
void slotCredentialsAsked();
QString _davPath; // defaults to value from theme, might be overwritten in brandings
friend class AccountManager;
};
-
}
Q_DECLARE_METATYPE(OCC::AccountPtr)
// For overloading macros by argument count
// See stackoverflow.com/questions/16683146/can-macros-be-overloaded-by-number-of-arguments
-#define OC_ASSERT_CAT(A, B) A ## B
-#define OC_ASSERT_SELECT(NAME, NUM) OC_ASSERT_CAT(NAME ## _, NUM)
+#define OC_ASSERT_CAT(A, B) A##B
+#define OC_ASSERT_SELECT(NAME, NUM) OC_ASSERT_CAT(NAME##_, NUM)
#define OC_ASSERT_GET_COUNT(_1, _2, _3, COUNT, ...) COUNT
#define OC_ASSERT_VA_SIZE(...) OC_ASSERT_GET_COUNT(__VA_ARGS__, 3, 2, 1, 0)
-#define OC_ASSERT_OVERLOAD(NAME, ...) OC_ASSERT_SELECT(NAME, OC_ASSERT_VA_SIZE(__VA_ARGS__))(__VA_ARGS__)
+#define OC_ASSERT_OVERLOAD(NAME, ...) OC_ASSERT_SELECT(NAME, OC_ASSERT_VA_SIZE(__VA_ARGS__)) \
+ (__VA_ARGS__)
// Default assert: If the condition is false in debug builds, terminate.
//
// Prints a message on failure, even in release builds.
#define ASSERT(...) OC_ASSERT_OVERLOAD(ASSERT, __VA_ARGS__)
-#define ASSERT_1(cond) \
- if (!(cond)) { \
+#define ASSERT_1(cond) \
+ if (!(cond)) { \
OC_ASSERT_MSG("ASSERT: \"%s\" in file %s, line %d", #cond, __FILE__, __LINE__); \
- } else {}
-#define ASSERT_2(cond, message) \
- if (!(cond)) { \
+ } else { \
+ }
+#define ASSERT_2(cond, message) \
+ if (!(cond)) { \
OC_ASSERT_MSG("ASSERT: \"%s\" in file %s, line %d with message: %s", #cond, __FILE__, __LINE__, message); \
- } else {}
+ } else { \
+ }
// Enforce condition to be true, even in release builds.
//
// Prints 'message' and aborts execution if 'cond' is false.
#define ENFORCE(...) OC_ASSERT_OVERLOAD(ENFORCE, __VA_ARGS__)
-#define ENFORCE_1(cond) \
- if (!(cond)) { \
+#define ENFORCE_1(cond) \
+ if (!(cond)) { \
qFatal("ENFORCE: \"%s\" in file %s, line %d", #cond, __FILE__, __LINE__); \
- } else {}
-#define ENFORCE_2(cond, message) \
- if (!(cond)) { \
+ } else { \
+ }
+#define ENFORCE_2(cond, message) \
+ if (!(cond)) { \
qFatal("ENFORCE: \"%s\" in file %s, line %d with message: %s", #cond, __FILE__, __LINE__, message); \
- } else {}
+ } else { \
+ }
// An assert that is only present in debug builds: typically used for
// asserts that are too expensive for release mode.
// 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.
-static qint64 relativeLimitMeasuringTimerIntervalMsec = 1000*2;
+static qint64 relativeLimitMeasuringTimerIntervalMsec = 1000 * 2;
// See also WritingState in http://code.woboq.org/qt5/qtbase/src/network/access/qhttpprotocolhandler.cpp.html#_ZN20QHttpProtocolHandler11sendRequestEv
// FIXME At some point:
// * For relative limiting, do less measuring and more delaying+giving quota
// * For relative limiting, smoothen measurements
-BandwidthManager::BandwidthManager(OwncloudPropagator *p) : QObject(),
- _propagator(p),
- _relativeLimitCurrentMeasuredDevice(0),
- _relativeUploadLimitProgressAtMeasuringRestart(0),
- _currentUploadLimit(0),
- _relativeLimitCurrentMeasuredJob(0),
- _currentDownloadLimit(0)
+BandwidthManager::BandwidthManager(OwncloudPropagator *p)
+ : QObject()
+ , _propagator(p)
+ , _relativeLimitCurrentMeasuredDevice(0)
+ , _relativeUploadLimitProgressAtMeasuringRestart(0)
+ , _currentUploadLimit(0)
+ , _relativeLimitCurrentMeasuredJob(0)
+ , _currentDownloadLimit(0)
{
_currentUploadLimit = _propagator->_uploadLimit.fetchAndAddAcquire(0);
_currentDownloadLimit = _propagator->_downloadLimit.fetchAndAddAcquire(0);
QObject::connect(&_switchingTimer, SIGNAL(timeout()), this, SLOT(switchingTimerExpired()));
- _switchingTimer.setInterval(10*1000);
+ _switchingTimer.setInterval(10 * 1000);
_switchingTimer.start();
QMetaObject::invokeMethod(this, "switchingTimerExpired", Qt::QueuedConnection);
_absoluteLimitTimer.start();
// Relative uploads
- QObject::connect(&_relativeUploadMeasuringTimer,SIGNAL(timeout()),
- this, SLOT(relativeUploadMeasuringTimerExpired()));
+ QObject::connect(&_relativeUploadMeasuringTimer, SIGNAL(timeout()),
+ this, SLOT(relativeUploadMeasuringTimerExpired()));
_relativeUploadMeasuringTimer.setInterval(relativeLimitMeasuringTimerIntervalMsec);
_relativeUploadMeasuringTimer.start();
_relativeUploadMeasuringTimer.setSingleShot(true); // will be restarted from the delay timer
QObject::connect(&_relativeUploadDelayTimer, SIGNAL(timeout()),
- this, SLOT(relativeUploadDelayTimerExpired()));
+ this, SLOT(relativeUploadDelayTimerExpired()));
_relativeUploadDelayTimer.setSingleShot(true); // will be restarted from the measuring timer
// Relative downloads
- QObject::connect(&_relativeDownloadMeasuringTimer,SIGNAL(timeout()),
- this, SLOT(relativeDownloadMeasuringTimerExpired()));
+ QObject::connect(&_relativeDownloadMeasuringTimer, SIGNAL(timeout()),
+ this, SLOT(relativeDownloadMeasuringTimerExpired()));
_relativeDownloadMeasuringTimer.setInterval(relativeLimitMeasuringTimerIntervalMsec);
_relativeDownloadMeasuringTimer.start();
_relativeDownloadMeasuringTimer.setSingleShot(true); // will be restarted from the delay timer
QObject::connect(&_relativeDownloadDelayTimer, SIGNAL(timeout()),
- this, SLOT(relativeDownloadDelayTimerExpired()));
+ this, SLOT(relativeDownloadDelayTimerExpired()));
_relativeDownloadDelayTimer.setSingleShot(true); // will be restarted from the measuring timer
}
{
_absoluteUploadDeviceList.append(p);
_relativeUploadDeviceList.append(p);
- QObject::connect(p, SIGNAL(destroyed(QObject*)), this, SLOT(unregisterUploadDevice(QObject*)));
+ QObject::connect(p, SIGNAL(destroyed(QObject *)), this, SLOT(unregisterUploadDevice(QObject *)));
if (usingAbsoluteUploadLimit()) {
p->setBandwidthLimited(true);
void BandwidthManager::unregisterUploadDevice(QObject *o)
{
- UploadDevice *p = qobject_cast<UploadDevice*>(o);
+ UploadDevice *p = qobject_cast<UploadDevice *>(o);
if (p) {
unregisterUploadDevice(p);
}
}
-void BandwidthManager::unregisterUploadDevice(UploadDevice* p)
+void BandwidthManager::unregisterUploadDevice(UploadDevice *p)
{
_absoluteUploadDeviceList.removeAll(p);
_relativeUploadDeviceList.removeAll(p);
}
}
-void BandwidthManager::registerDownloadJob(GETFileJob* j)
+void BandwidthManager::registerDownloadJob(GETFileJob *j)
{
_downloadJobList.append(j);
- QObject::connect(j, SIGNAL(destroyed(QObject*)), this, SLOT(unregisterDownloadJob(QObject*)));
+ QObject::connect(j, SIGNAL(destroyed(QObject *)), this, SLOT(unregisterDownloadJob(QObject *)));
if (usingAbsoluteDownloadLimit()) {
j->setBandwidthLimited(true);
}
}
-void BandwidthManager::unregisterDownloadJob(GETFileJob* j)
+void BandwidthManager::unregisterDownloadJob(GETFileJob *j)
{
_downloadJobList.removeAll(j);
if (_relativeLimitCurrentMeasuredJob == j) {
}
}
-void BandwidthManager::unregisterDownloadJob(QObject* o)
+void BandwidthManager::unregisterDownloadJob(QObject *o)
{
- GETFileJob *p = qobject_cast<GETFileJob*>(o);
+ GETFileJob *p = qobject_cast<GETFileJob *>(o);
if (p) {
unregisterDownloadJob(p);
}
return;
}
- qCDebug(lcBandwidthManager) << _relativeUploadDeviceList.count() << "Starting Delay";
+ qCDebug(lcBandwidthManager) << _relativeUploadDeviceList.count() << "Starting Delay";
qint64 relativeLimitProgressMeasured = (_relativeLimitCurrentMeasuredDevice->_readWithProgress
- + _relativeLimitCurrentMeasuredDevice->_read) / 2;
+ + _relativeLimitCurrentMeasuredDevice->_read)
+ / 2;
qint64 relativeLimitProgressDifference = relativeLimitProgressMeasured - _relativeUploadLimitProgressAtMeasuringRestart;
qCDebug(lcBandwidthManager) << _relativeUploadLimitProgressAtMeasuringRestart
- << relativeLimitProgressMeasured << relativeLimitProgressDifference;
+ << relativeLimitProgressMeasured << relativeLimitProgressDifference;
- 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 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;
- qCDebug(lcBandwidthManager) << waitTimeMsec << " - "<< realWaitTimeMsec <<
- " msec for " << uploadLimitPercent << "%";
+ 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;
- Q_FOREACH(UploadDevice *ud, _relativeUploadDeviceList) {
+ Q_FOREACH (UploadDevice *ud, _relativeUploadDeviceList) {
ud->setBandwidthLimited(true);
ud->setChoked(false);
ud->giveBandwidthQuota(quotaPerDevice);
- qCDebug(lcBandwidthManager) << "Gave" << quotaPerDevice/1024.0 << "kB to" << ud;
+ qCDebug(lcBandwidthManager) << "Gave" << quotaPerDevice / 1024.0 << "kB to" << ud;
}
_relativeLimitCurrentMeasuredDevice = 0;
}
_relativeUploadDeviceList.append(_relativeLimitCurrentMeasuredDevice);
_relativeUploadLimitProgressAtMeasuringRestart = (_relativeLimitCurrentMeasuredDevice->_readWithProgress
- + _relativeLimitCurrentMeasuredDevice->_read) / 2;
+ + _relativeLimitCurrentMeasuredDevice->_read)
+ / 2;
_relativeLimitCurrentMeasuredDevice->setBandwidthLimited(false);
_relativeLimitCurrentMeasuredDevice->setChoked(false);
// choke all other UploadDevices
- Q_FOREACH(UploadDevice *ud, _relativeUploadDeviceList) {
+ Q_FOREACH (UploadDevice *ud, _relativeUploadDeviceList) {
if (ud != _relativeLimitCurrentMeasuredDevice) {
ud->setBandwidthLimited(true);
ud->setChoked(true);
qint64 relativeLimitProgressMeasured = _relativeLimitCurrentMeasuredJob->currentDownloadPosition();
qint64 relativeLimitProgressDifference = relativeLimitProgressMeasured - _relativeDownloadLimitProgressAtMeasuringRestart;
qCDebug(lcBandwidthManager) << _relativeDownloadLimitProgressAtMeasuringRestart
- << relativeLimitProgressMeasured << relativeLimitProgressDifference;
+ << relativeLimitProgressMeasured << relativeLimitProgressDifference;
- qint64 speedkBPerSec = (relativeLimitProgressDifference / relativeLimitMeasuringTimerIntervalMsec*1000.0) / 1024.0;
- qCDebug(lcBandwidthManager) << 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;
- qCDebug(lcBandwidthManager) << waitTimeMsec << " - "<< realWaitTimeMsec <<
- " msec for " << downloadLimitPercent << "%";
+ 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) {
- qCInfo(lcBandwidthManager) << "ADJUSTING QUOTA FROM " << quota << " TO " << quota - 20*1024;
- quota -= 20*1024;
+ if (quota > 20 * 1024) {
+ qCInfo(lcBandwidthManager) << "ADJUSTING QUOTA FROM " << quota << " TO " << quota - 20 * 1024;
+ quota -= 20 * 1024;
}
qint64 quotaPerJob = quota / jobCount + 1.0;
- Q_FOREACH(GETFileJob *gfj, _downloadJobList) {
+ Q_FOREACH (GETFileJob *gfj, _downloadJobList) {
gfj->setBandwidthLimited(true);
gfj->setChoked(false);
gfj->giveBandwidthQuota(quotaPerJob);
- qCDebug(lcBandwidthManager) << "Gave" << quotaPerJob/1024.0 << "kB to" << gfj;
+ qCDebug(lcBandwidthManager) << "Gave" << quotaPerJob / 1024.0 << "kB to" << gfj;
}
_relativeLimitCurrentMeasuredDevice = 0;
}
_relativeLimitCurrentMeasuredJob->setChoked(false);
// choke all other download jobs
- Q_FOREACH(GETFileJob *gfj, _downloadJobList) {
+ Q_FOREACH (GETFileJob *gfj, _downloadJobList) {
if (gfj != _relativeLimitCurrentMeasuredJob) {
gfj->setBandwidthLimited(true);
gfj->setChoked(true);
// end downloads
-void BandwidthManager::switchingTimerExpired() {
+void BandwidthManager::switchingTimerExpired()
+{
qint64 newUploadLimit = _propagator->_uploadLimit.fetchAndAddAcquire(0);
if (newUploadLimit != _currentUploadLimit) {
qCInfo(lcBandwidthManager) << "Upload Bandwidth limit changed" << _currentUploadLimit << newUploadLimit;
_currentUploadLimit = newUploadLimit;
- Q_FOREACH(UploadDevice *ud, _relativeUploadDeviceList) {
+ Q_FOREACH (UploadDevice *ud, _relativeUploadDeviceList) {
if (newUploadLimit == 0) {
ud->setBandwidthLimited(false);
ud->setChoked(false);
if (newDownloadLimit != _currentDownloadLimit) {
qCInfo(lcBandwidthManager) << "Download Bandwidth limit changed" << _currentDownloadLimit << newDownloadLimit;
_currentDownloadLimit = newDownloadLimit;
- Q_FOREACH(GETFileJob *j, _downloadJobList) {
+ Q_FOREACH (GETFileJob *j, _downloadJobList) {
if (usingAbsoluteDownloadLimit()) {
j->setBandwidthLimited(true);
j->setChoked(false);
{
if (usingAbsoluteUploadLimit() && _absoluteUploadDeviceList.count() > 0) {
qint64 quotaPerDevice = _currentUploadLimit / qMax(1, _absoluteUploadDeviceList.count());
- qCDebug(lcBandwidthManager) << quotaPerDevice << _absoluteUploadDeviceList.count() << _currentUploadLimit;
- Q_FOREACH(UploadDevice *device, _absoluteUploadDeviceList) {
+ qCDebug(lcBandwidthManager) << quotaPerDevice << _absoluteUploadDeviceList.count() << _currentUploadLimit;
+ Q_FOREACH (UploadDevice *device, _absoluteUploadDeviceList) {
device->giveBandwidthQuota(quotaPerDevice);
- qCDebug(lcBandwidthManager) << "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());
- qCDebug(lcBandwidthManager) << quotaPerJob << _downloadJobList.count() << _currentDownloadLimit;
- Q_FOREACH(GETFileJob *j, _downloadJobList) {
+ qCDebug(lcBandwidthManager) << quotaPerJob << _downloadJobList.count() << _currentDownloadLimit;
+ Q_FOREACH (GETFileJob *j, _downloadJobList) {
j->giveBandwidthQuota(quotaPerJob);
- qCDebug(lcBandwidthManager) << "Gave " << quotaPerJob/1024.0 << " kB to" << j;
+ qCDebug(lcBandwidthManager) << "Gave " << quotaPerJob / 1024.0 << " kB to" << j;
}
}
}
-
-
}
* @brief The BandwidthManager class
* @ingroup libsync
*/
-class BandwidthManager : public QObject {
+class BandwidthManager : public QObject
+{
Q_OBJECT
public:
BandwidthManager(OwncloudPropagator *p);
public slots:
- void registerUploadDevice(UploadDevice*);
- void unregisterUploadDevice(UploadDevice*);
- void unregisterUploadDevice(QObject*);
+ void registerUploadDevice(UploadDevice *);
+ void unregisterUploadDevice(UploadDevice *);
+ void unregisterUploadDevice(QObject *);
- void registerDownloadJob(GETFileJob*);
- void unregisterDownloadJob(GETFileJob*);
- void unregisterDownloadJob(QObject*);
+ void registerDownloadJob(GETFileJob *);
+ void unregisterDownloadJob(GETFileJob *);
+ void unregisterDownloadJob(QObject *);
void absoluteLimitTimerExpired();
void switchingTimerExpired();
QTimer _absoluteLimitTimer;
// FIXME merge these two lists
- QLinkedList<UploadDevice*> _absoluteUploadDeviceList;
- QLinkedList<UploadDevice*> _relativeUploadDeviceList;
+ QLinkedList<UploadDevice *> _absoluteUploadDeviceList;
+ QLinkedList<UploadDevice *> _relativeUploadDeviceList;
QTimer _relativeUploadMeasuringTimer;
qint64 _relativeUploadLimitProgressAtMeasuringRestart;
qint64 _currentUploadLimit;
- QLinkedList<GETFileJob*> _downloadJobList;
+ QLinkedList<GETFileJob *> _downloadJobList;
QTimer _relativeDownloadMeasuringTimer;
// for relative bw limiting, we need to wait this amount before measuring again
qint64 _currentDownloadLimit;
};
-
}
#endif
bool Capabilities::sharePublicLinkAllowUpload() const
{
- return _capabilities["files_sharing"].toMap()["public"].toMap()["upload"].toBool();
+ return _capabilities["files_sharing"].toMap()["public"].toMap()["upload"].toBool();
}
bool Capabilities::sharePublicLinkEnforcePassword() const
QList<QByteArray> Capabilities::supportedChecksumTypes() const
{
QList<QByteArray> list;
- foreach (const auto & t, _capabilities["checksums"].toMap()["supportedTypes"].toList()) {
+ foreach (const auto &t, _capabilities["checksums"].toMap()["supportedTypes"].toList()) {
list.push_back(t.toByteArray());
}
return list;
bool Capabilities::chunkingNg() const
{
static const auto chunkng = qgetenv("OWNCLOUD_CHUNKING_NG");
- if (chunkng == "0") return false;
- if (chunkng == "1") return true;
+ if (chunkng == "0")
+ return false;
+ if (chunkng == "1")
+ return true;
return _capabilities["dav"].toMap()["chunking"].toByteArray() >= "1.0";
}
QList<int> Capabilities::httpErrorCodesThatResetFailingChunkedUploads() const
{
QList<int> list;
- foreach (const auto & t, _capabilities["dav"].toMap()["httpErrorCodesThatResetFailingChunkedUploads"].toList()) {
+ foreach (const auto &t, _capabilities["dav"].toMap()["httpErrorCodesThatResetFailingChunkedUploads"].toList()) {
list.push_back(t.toInt());
}
return list;
}
-
}
* server
* @ingroup libsync
*/
-class OWNCLOUDSYNC_EXPORT Capabilities {
-
+class OWNCLOUDSYNC_EXPORT Capabilities
+{
public:
Capabilities(const QVariantMap &capabilities);
bool sharePublicLinkAllowUpload() const;
bool sharePublicLinkEnforcePassword() const;
bool sharePublicLinkEnforceExpireDate() const;
- int sharePublicLinkExpireDateDays() const;
+ int sharePublicLinkExpireDateDays() const;
bool sharePublicLinkMultiple() const;
bool shareResharing() const;
bool chunkingNg() const;
private:
QVariantMap _capabilities;
};
-
}
#endif //CAPABILITIES_H
Q_LOGGING_CATEGORY(lcChecksums, "sync.checksums", QtInfoMsg)
-QByteArray makeChecksumHeader(const QByteArray& checksumType, const QByteArray& checksum)
+QByteArray makeChecksumHeader(const QByteArray &checksumType, const QByteArray &checksum)
{
QByteArray header = checksumType;
header.append(':');
return header;
}
-bool parseChecksumHeader(const QByteArray& header, QByteArray* type, QByteArray* checksum)
+bool parseChecksumHeader(const QByteArray &header, QByteArray *type, QByteArray *checksum)
{
if (header.isEmpty()) {
type->clear();
return type;
}
-ComputeChecksum::ComputeChecksum(QObject* parent)
+ComputeChecksum::ComputeChecksum(QObject *parent)
: QObject(parent)
{
}
-void ComputeChecksum::setChecksumType(const QByteArray& type)
+void ComputeChecksum::setChecksumType(const QByteArray &type)
{
_checksumType = type;
}
return _checksumType;
}
-void ComputeChecksum::start(const QString& filePath)
+void ComputeChecksum::start(const QString &filePath)
{
// Calculate the checksum in a different thread first.
- connect( &_watcher, SIGNAL(finished()),
- this, SLOT(slotCalculationDone()),
- Qt::UniqueConnection );
+ connect(&_watcher, SIGNAL(finished()),
+ this, SLOT(slotCalculationDone()),
+ Qt::UniqueConnection);
_watcher.setFuture(QtConcurrent::run(ComputeChecksum::computeNow, filePath, checksumType()));
}
-QByteArray ComputeChecksum::computeNow(const QString& filePath, const QByteArray& checksumType)
+QByteArray ComputeChecksum::computeNow(const QString &filePath, const QByteArray &checksumType)
{
- if( checksumType == checkSumMD5C ) {
+ if (checksumType == checkSumMD5C) {
return FileSystem::calcMd5(filePath);
- } else if( checksumType == checkSumSHA1C ) {
+ } else if (checksumType == checkSumSHA1C) {
return FileSystem::calcSha1(filePath);
}
#ifdef ZLIB_FOUND
- else if( checksumType == checkSumAdlerC) {
+ else if (checksumType == checkSumAdlerC) {
return FileSystem::calcAdler32(filePath);
}
#endif
// for an unknown checksum or no checksum, we're done right now
- if( !checksumType.isEmpty() ) {
+ if (!checksumType.isEmpty()) {
qCWarning(lcChecksums) << "Unknown checksum type:" << checksumType;
}
return QByteArray();
{
}
-void ValidateChecksumHeader::start(const QString& filePath, const QByteArray& checksumHeader)
+void ValidateChecksumHeader::start(const QString &filePath, const QByteArray &checksumHeader)
{
// If the incoming header is empty no validation can happen. Just continue.
- if( checksumHeader.isEmpty() ) {
+ if (checksumHeader.isEmpty()) {
emit validated(QByteArray(), QByteArray());
return;
}
- if( !parseChecksumHeader(checksumHeader, &_expectedChecksumType, &_expectedChecksum) ) {
+ if (!parseChecksumHeader(checksumHeader, &_expectedChecksumType, &_expectedChecksum)) {
qCWarning(lcChecksums) << "Checksum header malformed:" << checksumHeader;
emit validationFailed(tr("The checksum header is malformed."));
return;
auto calculator = new ComputeChecksum(this);
calculator->setChecksumType(_expectedChecksumType);
- connect(calculator, SIGNAL(done(QByteArray,QByteArray)),
- SLOT(slotChecksumCalculated(QByteArray,QByteArray)));
+ connect(calculator, SIGNAL(done(QByteArray, QByteArray)),
+ SLOT(slotChecksumCalculated(QByteArray, QByteArray)));
calculator->start(filePath);
}
-void ValidateChecksumHeader::slotChecksumCalculated(const QByteArray& checksumType,
- const QByteArray& checksum)
+void ValidateChecksumHeader::slotChecksumCalculated(const QByteArray &checksumType,
+ const QByteArray &checksum)
{
- if( checksumType != _expectedChecksumType ) {
- emit validationFailed(tr("The checksum header contained an unknown checksum type '%1'").arg(
- QString::fromLatin1(_expectedChecksumType)));
+ if (checksumType != _expectedChecksumType) {
+ emit validationFailed(tr("The checksum header contained an unknown checksum type '%1'").arg(QString::fromLatin1(_expectedChecksumType)));
return;
}
- if( checksum != _expectedChecksum ) {
+ if (checksum != _expectedChecksum) {
emit validationFailed(tr("The downloaded file does not match the checksum, it will be resumed."));
return;
}
{
}
-const char* CSyncChecksumHook::hook(const char* path, uint32_t checksumTypeId, void *this_obj)
+const char *CSyncChecksumHook::hook(const char *path, uint32_t checksumTypeId, void *this_obj)
{
- CSyncChecksumHook* checksumHook = static_cast<CSyncChecksumHook*>(this_obj);
+ CSyncChecksumHook *checksumHook = static_cast<CSyncChecksumHook *>(this_obj);
QByteArray checksum = checksumHook->compute(QString::fromUtf8(path), checksumTypeId);
if (checksum.isNull()) {
return NULL;
}
- char* result = (char*)malloc(checksum.size() + 1);
+ char *result = (char *)malloc(checksum.size() + 1);
memcpy(result, checksum.constData(), checksum.size());
result[checksum.size()] = 0;
return result;
}
-QByteArray CSyncChecksumHook::compute(const QString& path, int checksumTypeId)
+QByteArray CSyncChecksumHook::compute(const QString &path, int checksumTypeId)
{
QByteArray checksumType = _journal->getChecksumType(checksumTypeId);
if (checksumType.isEmpty()) {
return checksum;
}
-
-
}
class SyncJournalDb;
/// Creates a checksum header from type and value.
-QByteArray makeChecksumHeader(const QByteArray& checksumType, const QByteArray& checksum);
+QByteArray makeChecksumHeader(const QByteArray &checksumType, const QByteArray &checksum);
/// Parses a checksum header
-bool parseChecksumHeader(const QByteArray& header, QByteArray* type, QByteArray* checksum);
+bool parseChecksumHeader(const QByteArray &header, QByteArray *type, QByteArray *checksum);
/// Checks OWNCLOUD_DISABLE_CHECKSUM_UPLOAD
bool uploadChecksumEnabled();
{
Q_OBJECT
public:
- explicit ComputeChecksum(QObject* parent = 0);
+ explicit ComputeChecksum(QObject *parent = 0);
/**
* Sets the checksum type to be used. The default is empty.
*/
- void setChecksumType(const QByteArray& type);
+ void setChecksumType(const QByteArray &type);
QByteArray checksumType() const;
*
* done() is emitted when the calculation finishes.
*/
- void start(const QString& filePath);
+ void start(const QString &filePath);
/**
* Computes the checksum synchronously.
*/
- static QByteArray computeNow(const QString& filePath, const QByteArray& checksumType);
+ static QByteArray computeNow(const QString &filePath, const QByteArray &checksumType);
signals:
- void done(const QByteArray& checksumType, const QByteArray& checksum);
+ void done(const QByteArray &checksumType, const QByteArray &checksum);
private slots:
void slotCalculationDone();
* will be emitted. In case of any kind of error, the signal validationFailed() will
* be emitted.
*/
- void start(const QString& filePath, const QByteArray& checksumHeader);
+ void start(const QString &filePath, const QByteArray &checksumHeader);
signals:
- void validated(const QByteArray& checksumType, const QByteArray& checksum);
- void validationFailed( const QString& errMsg );
+ void validated(const QByteArray &checksumType, const QByteArray &checksum);
+ void validationFailed(const QString &errMsg);
private slots:
- void slotChecksumCalculated(const QByteArray& checksumType, const QByteArray& checksum);
+ void slotChecksumCalculated(const QByteArray &checksumType, const QByteArray &checksum);
private:
QByteArray _expectedChecksumType;
{
Q_OBJECT
public:
- explicit CSyncChecksumHook(SyncJournalDb* journal);
+ explicit CSyncChecksumHook(SyncJournalDb *journal);
/**
* Returns the checksum value for \a path for the given \a checksumTypeId.
* to be set as userdata.
* The return value will be owned by csync.
*/
- static const char* hook(const char* path, uint32_t checksumTypeId, void* this_obj);
+ static const char *hook(const char *path, uint32_t checksumTypeId, void *this_obj);
- QByteArray compute(const QString& path, int checksumTypeId);
+ QByteArray compute(const QString &path, int checksumTypeId);
private:
- SyncJournalDb* _journal;
+ SyncJournalDb *_journal;
};
-
}
Q_LOGGING_CATEGORY(lcClientProxy, "sync.clientproxy", QtInfoMsg)
-ClientProxy::ClientProxy(QObject *parent) :
- QObject(parent)
+ClientProxy::ClientProxy(QObject *parent)
+ : QObject(parent)
{
}
-static QNetworkProxy proxyFromConfig(const ConfigFile& cfg)
+static QNetworkProxy proxyFromConfig(const ConfigFile &cfg)
{
QNetworkProxy proxy;
return proxy;
}
-bool ClientProxy::isUsingSystemDefault() {
+bool ClientProxy::isUsingSystemDefault()
+{
OCC::ConfigFile cfg;
// if there is no config file, default to system proxy.
- if( cfg.exists() ) {
+ if (cfg.exists()) {
return cfg.proxyType() == QNetworkProxy::DefaultProxy;
}
QNetworkProxy proxy;
// if there is no config file, default to system proxy.
- if( cfg.exists() ) {
+ if (cfg.exists()) {
proxyType = cfg.proxyType();
- proxy = proxyFromConfig(cfg);
+ proxy = proxyFromConfig(cfg);
}
- switch(proxyType) {
+ switch (proxyType) {
case QNetworkProxy::NoProxy:
qCInfo(lcClientProxy) << "Set proxy configuration to use NO proxy";
QNetworkProxyFactory::setUseSystemConfiguration(false);
}
}
-const char* ClientProxy::proxyTypeToCStr(QNetworkProxy::ProxyType type)
+const char *ClientProxy::proxyTypeToCStr(QNetworkProxy::ProxyType type)
{
switch (type) {
case QNetworkProxy::NoProxy:
QThreadPool::globalInstance()->start(runnable); // takes ownership and deletes
}
-SystemProxyRunnable::SystemProxyRunnable(const QUrl &url) : QObject(), QRunnable(), _url(url)
+SystemProxyRunnable::SystemProxyRunnable(const QUrl &url)
+ : QObject()
+ , QRunnable()
+ , _url(url)
{
-
}
void SystemProxyRunnable::run()
// FIXME Would we really ever return more?
}
}
-
-
}
void setupQtProxyFromConfig();
private:
- const char* proxyTypeToCStr(QNetworkProxy::ProxyType type);
+ const char *proxyTypeToCStr(QNetworkProxy::ProxyType type);
};
-class SystemProxyRunnable : public QObject, public QRunnable {
+class SystemProxyRunnable : public QObject, public QRunnable
+{
Q_OBJECT
public:
SystemProxyRunnable(const QUrl &url);
void run();
signals:
void systemProxyLookedUp(const QNetworkProxy &url);
+
private:
QUrl _url;
};
OWNCLOUDSYNC_EXPORT QString printQNetworkProxy(const QNetworkProxy &proxy);
-
-
}
#endif // CLIENTPROXY_H
static const char proxyPassC[] = "Proxy/pass";
static const char proxyNeedsAuthC[] = "Proxy/needsAuth";
-static const char useUploadLimitC[] = "BWLimit/useUploadLimit";
+static const char useUploadLimitC[] = "BWLimit/useUploadLimit";
static const char useDownloadLimitC[] = "BWLimit/useDownloadLimit";
-static const char uploadLimitC[] = "BWLimit/uploadLimit";
-static const char downloadLimitC[] = "BWLimit/downloadLimit";
+static const char uploadLimitC[] = "BWLimit/uploadLimit";
+static const char downloadLimitC[] = "BWLimit/downloadLimit";
static const char newBigFolderSizeLimitC[] = "newBigFolderSizeLimit";
static const char useNewBigFolderSizeLimitC[] = "useNewBigFolderSizeLimit";
const char certPath[] = "http_certificatePath";
const char certPasswd[] = "http_certificatePasswd";
QString ConfigFile::_confDir = QString::null;
-bool ConfigFile::_askedUser = false;
+bool ConfigFile::_askedUser = false;
ConfigFile::ConfigFile()
{
// QDesktopServices uses the application name to create a config path
- qApp->setApplicationName( Theme::instance()->appNameGUI() );
+ qApp->setApplicationName(Theme::instance()->appNameGUI());
QSettings::setDefaultFormat(QSettings::IniFormat);
QSettings settings(config, QSettings::IniFormat);
- settings.beginGroup( defaultConnection() );
+ settings.beginGroup(defaultConnection());
}
bool ConfigFile::setConfDir(const QString &value)
{
QString dirPath = value;
- if( dirPath.isEmpty() ) return false;
+ if (dirPath.isEmpty())
+ return false;
QFileInfo fi(dirPath);
- if ( !fi.exists() ) {
+ if (!fi.exists()) {
QDir().mkpath(dirPath);
fi.setFile(dirPath);
}
- if( fi.exists() && fi.isDir() ) {
+ if (fi.exists() && fi.isDir()) {
dirPath = fi.absoluteFilePath();
qCInfo(lcConfigFile) << "Using custom config dir " << dirPath;
- _confDir=dirPath;
+ _confDir = dirPath;
return true;
}
return false;
quint64 ConfigFile::chunkSize() const
{
QSettings settings(configFile(), QSettings::IniFormat);
- return settings.value(QLatin1String(chunkSizeC), 10*1000*1000).toLongLong(); // default to 10 MB
+ return settings.value(QLatin1String(chunkSizeC), 10 * 1000 * 1000).toLongLong(); // default to 10 MB
}
quint64 ConfigFile::maxChunkSize() const
{
QSettings settings(configFile(), QSettings::IniFormat);
- return settings.value(QLatin1String(maxChunkSizeC), 100*1000*1000).toLongLong(); // default to 100 MB
+ return settings.value(QLatin1String(maxChunkSizeC), 100 * 1000 * 1000).toLongLong(); // default to 100 MB
}
quint64 ConfigFile::minChunkSize() const
{
QSettings settings(configFile(), QSettings::IniFormat);
- return settings.value(QLatin1String(minChunkSizeC), 1000*1000).toLongLong(); // default to 1 MB
+ return settings.value(QLatin1String(minChunkSizeC), 1000 * 1000).toLongLong(); // default to 1 MB
}
quint64 ConfigFile::targetChunkUploadDuration() const
{
QSettings settings(configFile(), QSettings::IniFormat);
- return settings.value(QLatin1String(targetChunkUploadDurationC), 60*1000).toLongLong(); // default to 1 minute
+ return settings.value(QLatin1String(targetChunkUploadDurationC), 60 * 1000).toLongLong(); // default to 1 minute
}
void ConfigFile::setOptionalDesktopNotifications(bool show)
void ConfigFile::saveGeometryHeader(QHeaderView *header)
{
#ifndef TOKEN_AUTH_ONLY
- if(!header) return;
+ if (!header)
+ return;
ASSERT(!header->objectName().isEmpty());
QSettings settings(configFile(), QSettings::IniFormat);
void ConfigFile::restoreGeometryHeader(QHeaderView *header)
{
#ifndef TOKEN_AUTH_ONLY
- if(!header) return;
+ if (!header)
+ return;
ASSERT(!header->objectName().isNull());
QSettings settings(configFile(), QSettings::IniFormat);
#endif
}
-QVariant ConfigFile::getPolicySetting(const QString &setting, const QVariant& defaultValue) const
+QVariant ConfigFile::getPolicySetting(const QString &setting, const QVariant &defaultValue) const
{
if (Utility::isWindows()) {
// check for policies first and return immediately if a value is found.
QSettings userPolicy(QString::fromLatin1("HKEY_CURRENT_USER\\Software\\Policies\\%1\\%2")
- .arg(APPLICATION_VENDOR, Theme::instance()->appName()),
- QSettings::NativeFormat);
- if(userPolicy.contains(setting)) {
+ .arg(APPLICATION_VENDOR, Theme::instance()->appName()),
+ QSettings::NativeFormat);
+ if (userPolicy.contains(setting)) {
return userPolicy.value(setting);
}
QSettings machinePolicy(QString::fromLatin1("HKEY_LOCAL_MACHINE\\Software\\Policies\\%1\\%2")
- .arg(APPLICATION_VENDOR, APPLICATION_NAME),
- QSettings::NativeFormat);
- if(machinePolicy.contains(setting)) {
+ .arg(APPLICATION_VENDOR, APPLICATION_NAME),
+ QSettings::NativeFormat);
+ if (machinePolicy.contains(setting)) {
return machinePolicy.value(setting);
}
}
QString ConfigFile::configPath() const
{
- #ifndef TOKEN_AUTH_ONLY
- if( _confDir.isEmpty() ) {
+#ifndef TOKEN_AUTH_ONLY
+ if (_confDir.isEmpty()) {
// Qt 5's QStandardPaths::writableLocation gives us wrong results (without /data/),
// so we'll have to use the deprecated version for now
_confDir = QDesktopServices::storageLocation(QDesktopServices::DataLocation);
}
- #endif
+#endif
QString dir = _confDir;
- if( !dir.endsWith(QLatin1Char('/')) ) dir.append(QLatin1Char('/'));
+ if (!dir.endsWith(QLatin1Char('/')))
+ dir.append(QLatin1Char('/'));
return dir;
}
QString ConfigFile::configPathWithAppName() const
{
//HACK
- return QFileInfo( configFile() ).dir().absolutePath().append("/");
+ return QFileInfo(configFile()).dir().absolutePath().append("/");
}
static const QLatin1String exclFile("sync-exclude.lst");
switch (scope) {
case UserScope:
- fi.setFile( configPath(), exclFile );
+ fi.setFile(configPath(), exclFile);
- if( ! fi.isReadable() ) {
- fi.setFile( configPath(), QLatin1String("exclude.lst") );
+ if (!fi.isReadable()) {
+ fi.setFile(configPath(), QLatin1String("exclude.lst"));
}
- if( ! fi.isReadable() ) {
- fi.setFile( configPath(), exclFile );
+ if (!fi.isReadable()) {
+ fi.setFile(configPath(), exclFile);
}
return fi.absoluteFilePath();
case SystemScope:
{
QFileInfo fi;
#ifdef Q_OS_WIN
- fi.setFile( QCoreApplication::applicationDirPath(), exclFile );
+ fi.setFile(QCoreApplication::applicationDirPath(), exclFile);
#endif
#ifdef Q_OS_UNIX
fi.setFile(QString(SYSCONFDIR "/" + Theme::instance()->appName()), exclFile);
- if ( ! fi.exists() ) {
+ if (!fi.exists()) {
// Prefer to return the preferred path! Only use the fallback location
// if the other path does not exist and the fallback is valid.
- QFileInfo nextToBinary( QCoreApplication::applicationDirPath(), exclFile );
+ QFileInfo nextToBinary(QCoreApplication::applicationDirPath(), exclFile);
if (nextToBinary.exists()) {
fi = nextToBinary;
}
#endif
#ifdef Q_OS_MAC
// exec path is inside the bundle
- fi.setFile( QCoreApplication::applicationDirPath(),
- QLatin1String("../Resources/") + exclFile );
+ fi.setFile(QCoreApplication::applicationDirPath(),
+ QLatin1String("../Resources/") + exclFile);
#endif
-
+
return fi.absoluteFilePath();
}
bool ConfigFile::exists()
{
- QFile file( configFile() );
+ QFile file(configFile());
return file.exists();
}
return Theme::instance()->appName();
}
-void ConfigFile::storeData(const QString& group, const QString& key, const QVariant& value)
+void ConfigFile::storeData(const QString &group, const QString &key, const QVariant &value)
{
const QString con(group.isEmpty() ? defaultConnection() : group);
QSettings settings(configFile(), QSettings::IniFormat);
settings.sync();
}
-QVariant ConfigFile::retrieveData(const QString& group, const QString& key) const
+QVariant ConfigFile::retrieveData(const QString &group, const QString &key) const
{
const QString con(group.isEmpty() ? defaultConnection() : group);
QSettings settings(configFile(), QSettings::IniFormat);
return settings.value(key);
}
-void ConfigFile::removeData(const QString& group, const QString& key)
+void ConfigFile::removeData(const QString &group, const QString &key)
{
const QString con(group.isEmpty() ? defaultConnection() : group);
QSettings settings(configFile(), QSettings::IniFormat);
settings.remove(key);
}
-bool ConfigFile::dataExists(const QString& group, const QString& key) const
+bool ConfigFile::dataExists(const QString &group, const QString &key) const
{
const QString con(group.isEmpty() ? defaultConnection() : group);
QSettings settings(configFile(), QSettings::IniFormat);
return settings.contains(key);
}
-int ConfigFile::remotePollInterval( const QString& connection ) const
+int ConfigFile::remotePollInterval(const QString &connection) const
{
- QString con( connection );
- if( connection.isEmpty() ) con = defaultConnection();
+ QString con(connection);
+ if (connection.isEmpty())
+ con = defaultConnection();
- QSettings settings(configFile(), QSettings::IniFormat);
- settings.beginGroup( con );
+ QSettings settings(configFile(), QSettings::IniFormat);
+ settings.beginGroup(con);
- int remoteInterval = settings.value( QLatin1String(remotePollIntervalC), DEFAULT_REMOTE_POLL_INTERVAL ).toInt();
- if( remoteInterval < 5000) {
- qCWarning(lcConfigFile) << "Remote Interval is less than 5 seconds, reverting to" << DEFAULT_REMOTE_POLL_INTERVAL;
- remoteInterval = DEFAULT_REMOTE_POLL_INTERVAL;
- }
- return remoteInterval;
+ int remoteInterval = settings.value(QLatin1String(remotePollIntervalC), DEFAULT_REMOTE_POLL_INTERVAL).toInt();
+ if (remoteInterval < 5000) {
+ qCWarning(lcConfigFile) << "Remote Interval is less than 5 seconds, reverting to" << DEFAULT_REMOTE_POLL_INTERVAL;
+ remoteInterval = DEFAULT_REMOTE_POLL_INTERVAL;
+ }
+ return remoteInterval;
}
-void ConfigFile::setRemotePollInterval(int interval, const QString &connection )
+void ConfigFile::setRemotePollInterval(int interval, const QString &connection)
{
- QString con( connection );
- if( connection.isEmpty() ) con = defaultConnection();
+ QString con(connection);
+ if (connection.isEmpty())
+ con = defaultConnection();
- if( interval < 5000 ) {
+ if (interval < 5000) {
qCWarning(lcConfigFile) << "Remote Poll interval of " << interval << " is below five seconds.";
return;
}
QSettings settings(configFile(), QSettings::IniFormat);
- settings.beginGroup( con );
- settings.setValue(QLatin1String(remotePollIntervalC), interval );
+ settings.beginGroup(con);
+ settings.setValue(QLatin1String(remotePollIntervalC), interval);
settings.sync();
}
-quint64 ConfigFile::forceSyncInterval(const QString& connection) const
+quint64 ConfigFile::forceSyncInterval(const QString &connection) const
{
uint pollInterval = remotePollInterval(connection);
- QString con( connection );
- if( connection.isEmpty() ) con = defaultConnection();
+ QString con(connection);
+ if (connection.isEmpty())
+ con = defaultConnection();
QSettings settings(configFile(), QSettings::IniFormat);
- settings.beginGroup( con );
+ settings.beginGroup(con);
quint64 defaultInterval = 2 * 60 * 60 * 1000ull; // 2h
- quint64 interval = settings.value( QLatin1String(forceSyncIntervalC), defaultInterval ).toULongLong();
- if( interval < pollInterval) {
+ quint64 interval = settings.value(QLatin1String(forceSyncIntervalC), defaultInterval).toULongLong();
+ if (interval < pollInterval) {
qCWarning(lcConfigFile) << "Force sync interval is less than the remote poll inteval, reverting to" << pollInterval;
interval = pollInterval;
}
return interval;
}
-quint64 ConfigFile::notificationRefreshInterval(const QString& connection) const
+quint64 ConfigFile::notificationRefreshInterval(const QString &connection) const
{
- QString con( connection );
- if( connection.isEmpty() ) con = defaultConnection();
+ QString con(connection);
+ if (connection.isEmpty())
+ con = defaultConnection();
QSettings settings(configFile(), QSettings::IniFormat);
- settings.beginGroup( con );
+ settings.beginGroup(con);
quint64 defaultInterval = 5 * 60 * 1000ull; // 5 minutes
- quint64 interval = settings.value( QLatin1String(notificationRefreshIntervalC), defaultInterval ).toULongLong();
- if( interval < 60*1000ull) {
+ quint64 interval = settings.value(QLatin1String(notificationRefreshIntervalC), defaultInterval).toULongLong();
+ if (interval < 60 * 1000ull) {
qCWarning(lcConfigFile) << "Notification refresh interval smaller than one minute, setting to one minute";
- interval = 60*1000ull;
+ interval = 60 * 1000ull;
}
return interval;
}
-int ConfigFile::updateCheckInterval( const QString& connection ) const
+int ConfigFile::updateCheckInterval(const QString &connection) const
{
- QString con( connection );
- if( connection.isEmpty() ) con = defaultConnection();
+ QString con(connection);
+ if (connection.isEmpty())
+ con = defaultConnection();
QSettings settings(configFile(), QSettings::IniFormat);
- settings.beginGroup( con );
+ settings.beginGroup(con);
- int defaultInterval = 1000*60*60*10; // ten hours
- int interval = settings.value( QLatin1String(updateCheckIntervalC), defaultInterval ).toInt();
+ int defaultInterval = 1000 * 60 * 60 * 10; // ten hours
+ int interval = settings.value(QLatin1String(updateCheckIntervalC), defaultInterval).toInt();
- int minInterval = 1000*60*5;
- if( interval < minInterval) {
+ int minInterval = 1000 * 60 * 5;
+ if (interval < minInterval) {
qCWarning(lcConfigFile) << "Update check interval less than five minutes, setting " << minInterval;
interval = minInterval;
}
return interval;
}
-bool ConfigFile::skipUpdateCheck( const QString& connection ) const
+bool ConfigFile::skipUpdateCheck(const QString &connection) const
{
- QString con( connection );
- if( connection.isEmpty() ) con = defaultConnection();
+ QString con(connection);
+ if (connection.isEmpty())
+ con = defaultConnection();
QVariant fallback = getValue(QLatin1String(skipUpdateCheckC), con, false);
fallback = getValue(QLatin1String(skipUpdateCheckC), QString(), fallback);
return value.toBool();
}
-void ConfigFile::setSkipUpdateCheck( bool skip, const QString& connection )
+void ConfigFile::setSkipUpdateCheck(bool skip, const QString &connection)
{
- QString con( connection );
- if( connection.isEmpty() ) con = defaultConnection();
+ QString con(connection);
+ if (connection.isEmpty())
+ con = defaultConnection();
QSettings settings(configFile(), QSettings::IniFormat);
- settings.beginGroup( con );
+ settings.beginGroup(con);
- settings.setValue( QLatin1String(skipUpdateCheckC), QVariant(skip) );
+ settings.setValue(QLatin1String(skipUpdateCheckC), QVariant(skip));
settings.sync();
-
}
int ConfigFile::maxLogLines() const
{
QSettings settings(configFile(), QSettings::IniFormat);
- return settings.value( QLatin1String(maxLogLinesC), DEFAULT_MAX_LOG_LINES ).toInt();
+ return settings.value(QLatin1String(maxLogLinesC), DEFAULT_MAX_LOG_LINES).toInt();
}
-void ConfigFile::setMaxLogLines( int lines )
+void ConfigFile::setMaxLogLines(int lines)
{
QSettings settings(configFile(), QSettings::IniFormat);
settings.setValue(QLatin1String(maxLogLinesC), lines);
}
void ConfigFile::setProxyType(int proxyType,
- const QString& host,
- int port, bool needsAuth,
- const QString& user,
- const QString& pass)
+ const QString &host,
+ int port, bool needsAuth,
+ const QString &user,
+ const QString &pass)
{
QSettings settings(configFile(), QSettings::IniFormat);
settings.setValue(QLatin1String(proxyTypeC), proxyType);
- if (proxyType == QNetworkProxy::HttpProxy ||
- proxyType == QNetworkProxy::Socks5Proxy) {
+ if (proxyType == QNetworkProxy::HttpProxy || proxyType == QNetworkProxy::Socks5Proxy) {
settings.setValue(QLatin1String(proxyHostC), host);
settings.setValue(QLatin1String(proxyPortC), port);
settings.setValue(QLatin1String(proxyNeedsAuthC), needsAuth);
settings.sync();
}
-QVariant ConfigFile::getValue(const QString& param, const QString& group,
- const QVariant& defaultValue) const
+QVariant ConfigFile::getValue(const QString ¶m, const QString &group,
+ const QVariant &defaultValue) const
{
QVariant systemSetting;
if (Utility::isMac()) {
- QSettings systemSettings(QLatin1String("/Library/Preferences/" APPLICATION_REV_DOMAIN ".plist"), QSettings::NativeFormat);
- if (!group.isEmpty()) {
- systemSettings.beginGroup(group);
- }
- systemSetting = systemSettings.value(param, defaultValue);
+ QSettings systemSettings(QLatin1String("/Library/Preferences/" APPLICATION_REV_DOMAIN ".plist"), QSettings::NativeFormat);
+ if (!group.isEmpty()) {
+ systemSettings.beginGroup(group);
+ }
+ systemSetting = systemSettings.value(param, defaultValue);
} else if (Utility::isUnix()) {
- QSettings systemSettings(QString( SYSCONFDIR "/%1/%1.conf").arg(Theme::instance()->appName()), QSettings::NativeFormat);
+ QSettings systemSettings(QString(SYSCONFDIR "/%1/%1.conf").arg(Theme::instance()->appName()), QSettings::NativeFormat);
if (!group.isEmpty()) {
systemSettings.beginGroup(group);
}
} else { // Windows
QSettings systemSettings(QString::fromLatin1("HKEY_LOCAL_MACHINE\\Software\\%1\\%2")
.arg(APPLICATION_VENDOR, Theme::instance()->appName()),
- QSettings::NativeFormat);
+ QSettings::NativeFormat);
if (!group.isEmpty()) {
systemSettings.beginGroup(group);
}
}
QSettings settings(configFile(), QSettings::IniFormat);
- if (!group.isEmpty()) settings.beginGroup(group);
+ if (!group.isEmpty())
+ settings.beginGroup(group);
return settings.value(param, systemSetting);
}
-void ConfigFile::setValue(const QString& key, const QVariant &value)
+void ConfigFile::setValue(const QString &key, const QVariant &value)
{
QSettings settings(configFile(), QSettings::IniFormat);
bool monoDefault = false; // On Mac we want bw by default
#ifdef Q_OS_MAC
// OEM themes are not obliged to ship mono icons
- monoDefault = (0 == (strcmp("ownCloud",APPLICATION_NAME)));
+ monoDefault = (0 == (strcmp("ownCloud", APPLICATION_NAME)));
#endif
return settings.value(QLatin1String(monoIconsC), monoDefault).toBool();
}
return retrieveData(QString(), QLatin1String(certPath)).toString();
}
-void ConfigFile::setCertificatePath(const QString& cPath)
+void ConfigFile::setCertificatePath(const QString &cPath)
{
- QSettings settings(configFile(), QSettings::IniFormat);
- settings.setValue( QLatin1String(certPath), cPath);
- settings.sync();
+ QSettings settings(configFile(), QSettings::IniFormat);
+ settings.setValue(QLatin1String(certPath), cPath);
+ settings.sync();
}
QString ConfigFile::certificatePasswd() const
return retrieveData(QString(), QLatin1String(certPasswd)).toString();
}
-void ConfigFile::setCertificatePasswd(const QString& cPasswd)
+void ConfigFile::setCertificatePasswd(const QString &cPasswd)
{
- QSettings settings(configFile(), QSettings::IniFormat);
- settings.setValue( QLatin1String(certPasswd), cPasswd);
- settings.sync();
+ QSettings settings(configFile(), QSettings::IniFormat);
+ settings.setValue(QLatin1String(certPasswd), cPasswd);
+ settings.sync();
}
-
}
public:
ConfigFile();
- enum Scope { UserScope, SystemScope };
+ enum Scope { UserScope,
+ SystemScope };
QString configPath() const;
QString configPathWithAppName() const;
// the certs do not depend on a connection.
QByteArray caCerts();
- void setCaCerts( const QByteArray& );
+ void setCaCerts(const QByteArray &);
- bool passwordStorageAllowed(const QString &connection = QString::null );
+ bool passwordStorageAllowed(const QString &connection = QString::null);
// max count of lines in the log window
- int maxLogLines() const;
+ int maxLogLines() const;
void setMaxLogLines(int);
/* Server poll interval in milliseconds */
- int remotePollInterval( const QString& connection = QString() ) const;
+ int remotePollInterval(const QString &connection = QString()) const;
/* Set poll interval. Value in milliseconds has to be larger than 5000 */
- void setRemotePollInterval(int interval, const QString& connection = QString() );
+ void setRemotePollInterval(int interval, const QString &connection = QString());
/* Interval to check for new notifications */
- quint64 notificationRefreshInterval(const QString& connection = QString()) const;
+ quint64 notificationRefreshInterval(const QString &connection = QString()) const;
/* Force sync interval, in milliseconds */
quint64 forceSyncInterval(const QString &connection = QString()) const;
// proxy settings
void setProxyType(int proxyType,
- const QString& host = QString(),
- int port = 0, bool needsAuth = false,
- const QString& user = QString(),
- const QString& pass = QString());
+ const QString &host = QString(),
+ int port = 0, bool needsAuth = false,
+ const QString &user = QString(),
+ const QString &pass = QString());
int proxyType() const;
QString proxyHostName() const;
bool proxyNeedsAuth() const;
QString proxyUser() const;
QString proxyPassword() const;
-
+
/** 0: no limit, 1: manual, >0: automatic */
int useUploadLimit() const;
int useDownloadLimit() const;
void restoreGeometry(QWidget *w);
// how often the check about new versions runs, default two hours
- int updateCheckInterval( const QString& connection = QString() ) const;
+ int updateCheckInterval(const QString &connection = QString()) const;
- bool skipUpdateCheck( const QString& connection = QString() ) const;
- void setSkipUpdateCheck( bool, const QString& );
+ bool skipUpdateCheck(const QString &connection = QString()) const;
+ void setSkipUpdateCheck(bool, const QString &);
void saveGeometryHeader(QHeaderView *header);
void restoreGeometryHeader(QHeaderView *header);
QString certificatePath() const;
- void setCertificatePath(const QString& cPath);
+ void setCertificatePath(const QString &cPath);
QString certificatePasswd() const;
- void setCertificatePasswd(const QString& cPasswd);
+ void setCertificatePasswd(const QString &cPasswd);
protected:
- QVariant getPolicySetting(const QString& policy, const QVariant& defaultValue = QVariant()) const;
- void storeData(const QString& group, const QString& key, const QVariant& value);
- QVariant retrieveData(const QString& group, const QString& key) const;
- void removeData(const QString& group, const QString& key);
- bool dataExists(const QString& group, const QString& key) const;
+ QVariant getPolicySetting(const QString &policy, const QVariant &defaultValue = QVariant()) const;
+ void storeData(const QString &group, const QString &key, const QVariant &value);
+ QVariant retrieveData(const QString &group, const QString &key) const;
+ void removeData(const QString &group, const QString &key);
+ bool dataExists(const QString &group, const QString &key) const;
private:
- QVariant getValue(const QString& param, const QString& group = QString::null,
- const QVariant& defaultValue = QVariant()) const;
- void setValue(const QString& key, const QVariant &value);
+ QVariant getValue(const QString ¶m, const QString &group = QString::null,
+ const QVariant &defaultValue = QVariant()) const;
+ void setValue(const QString &key, const QVariant &value);
private:
- typedef QSharedPointer< AbstractCredentials > SharedCreds;
+ typedef QSharedPointer<AbstractCredentials> SharedCreds;
- static bool _askedUser;
+ static bool _askedUser;
static QString _oCVersion;
static QString _confDir;
};
-
}
#endif // CONFIGFILE_H
// 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);
+static qint64 timeoutToUseMsec = qMax(1000, ConnectionValidator::DefaultCallingIntervalMsec - 5 * 1000);
ConnectionValidator::ConnectionValidator(AccountPtr account, QObject *parent)
- : QObject(parent),
- _account(account),
- _isCheckingServerAndAuth(false)
+ : QObject(parent)
+ , _account(account)
+ , _isCheckingServerAndAuth(false)
{
}
-QString ConnectionValidator::statusString( Status stat )
+QString ConnectionValidator::statusString(Status stat)
{
- switch( stat ) {
+ switch (stat) {
case Undefined:
return QLatin1String("Undefined");
case Connected:
void ConnectionValidator::checkServerAndAuth()
{
- if( !_account ) {
+ if (!_account) {
_errors << tr("No ownCloud account configured");
- reportResult( NotConfigured );
+ reportResult(NotConfigured);
return;
}
qCDebug(lcConnectionValidator) << "Checking server and authentication";
if (ClientProxy::isUsingSystemDefault()) {
qCDebug(lcConnectionValidator) << "Trying to look up system proxy";
ClientProxy::lookupSystemProxyAsync(_account->url(),
- this, SLOT(systemProxyLookupDone(QNetworkProxy)));
+ this, SLOT(systemProxyLookupDone(QNetworkProxy)));
} else {
// We want to reset the QNAM proxy so that the global proxy settings are used (via ClientProxy settings)
_account->networkAccessManager()->setProxy(QNetworkProxy(QNetworkProxy::DefaultProxy));
}
}
-void ConnectionValidator::systemProxyLookupDone(const QNetworkProxy &proxy) {
+void ConnectionValidator::systemProxyLookupDone(const QNetworkProxy &proxy)
+{
if (!_account) {
qCWarning(lcConnectionValidator) << "Bailing out, Account had been deleted";
return;
CheckServerJob *checkJob = new CheckServerJob(_account, this);
checkJob->setTimeout(timeoutToUseMsec);
checkJob->setIgnoreCredentialFailure(true);
- connect(checkJob, SIGNAL(instanceFound(QUrl,QJsonObject)), SLOT(slotStatusFound(QUrl,QJsonObject)));
- connect(checkJob, SIGNAL(instanceNotFound(QNetworkReply*)), SLOT(slotNoStatusFound(QNetworkReply*)));
+ connect(checkJob, SIGNAL(instanceFound(QUrl, QJsonObject)), SLOT(slotStatusFound(QUrl, QJsonObject)));
+ connect(checkJob, SIGNAL(instanceNotFound(QNetworkReply *)), SLOT(slotNoStatusFound(QNetworkReply *)));
connect(checkJob, SIGNAL(timeout(QUrl)), SLOT(slotJobTimeout(QUrl)));
checkJob->start();
}
-void ConnectionValidator::slotStatusFound(const QUrl&url, const QJsonObject &info)
+void ConnectionValidator::slotStatusFound(const QUrl &url, const QJsonObject &info)
{
// Newer servers don't disclose any version in status.php anymore
// https://github.com/owncloud/core/pull/27473/files
// status.php was found.
qCInfo(lcConnectionValidator) << "** Application: ownCloud found: "
- << url << " with version "
- << CheckServerJob::versionString(info)
- << "(" << serverVersion << ")";
+ << url << " with version "
+ << CheckServerJob::versionString(info)
+ << "(" << serverVersion << ")";
if (!serverVersion.isEmpty() && !setAndCheckServerVersion(serverVersion)) {
return;
}
if (info["maintenance"].toBool()) {
- reportResult( MaintenanceMode );
+ reportResult(MaintenanceMode);
return;
}
// now check the authentication
if (_account->credentials()->ready())
- QTimer::singleShot( 0, this, SLOT( checkAuthentication() ));
+ QTimer::singleShot(0, this, SLOT(checkAuthentication()));
else
- reportResult( CredentialsMissingOrWrong );
+ reportResult(CredentialsMissingOrWrong);
}
// status.php could not be loaded (network or server issue!).
if (!_account->credentials()->ready()) {
// This could be needed for SSL client certificates
// We need to load them from keychain and try
- reportResult( CredentialsMissingOrWrong );
- } else if (! _account->credentials()->stillValid(reply)) {
+ reportResult(CredentialsMissingOrWrong);
+ } else if (!_account->credentials()->stillValid(reply)) {
_errors.append(tr("Authentication error: Either username or password are wrong."));
} else {
//_errors.append(tr("Unable to connect to %1").arg(_account->url().toString()));
- _errors.append( job->errorString() );
+ _errors.append(job->errorString());
}
- reportResult( StatusNotFound );
+ reportResult(StatusNotFound);
}
void ConnectionValidator::slotJobTimeout(const QUrl &url)
Q_UNUSED(url);
//_errors.append(tr("Unable to connect to %1").arg(url.toString()));
_errors.append(tr("timeout"));
- reportResult( Timeout );
+ reportResult(Timeout);
}
job->setTimeout(timeoutToUseMsec);
job->setProperties(QList<QByteArray>() << "getlastmodified");
connect(job, SIGNAL(result(QVariantMap)), SLOT(slotAuthSuccess()));
- connect(job, SIGNAL(finishedWithError(QNetworkReply*)), SLOT(slotAuthFailed(QNetworkReply*)));
+ connect(job, SIGNAL(finishedWithError(QNetworkReply *)), SLOT(slotAuthFailed(QNetworkReply *)));
job->start();
}
auto job = qobject_cast<PropfindJob *>(sender());
Status stat = Timeout;
- if( reply->error() == QNetworkReply::AuthenticationRequiredError ||
- !_account->credentials()->stillValid(reply)) {
+ if (reply->error() == QNetworkReply::AuthenticationRequiredError || !_account->credentials()->stillValid(reply)) {
qCWarning(lcConnectionValidator) << "******** Password is wrong!" << reply->error() << job->errorString();
_errors << tr("The provided credentials are not correct");
stat = CredentialsMissingOrWrong;
- } else if( reply->error() != QNetworkReply::NoError ) {
+ } else if (reply->error() != QNetworkReply::NoError) {
_errors << job->errorStringParsingBody();
const int httpStatus =
- reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
- if ( httpStatus == 503 ) {
+ reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
+ if (httpStatus == 503) {
_errors.clear();
stat = ServiceUnavailable;
}
}
- reportResult( stat );
+ reportResult(stat);
}
void ConnectionValidator::slotAuthSuccess()
void ConnectionValidator::fetchUser()
{
-
JsonApiJob *job = new JsonApiJob(_account, QLatin1String("ocs/v1.php/cloud/user"), this);
job->setTimeout(timeoutToUseMsec);
QObject::connect(job, SIGNAL(jsonReceived(QJsonDocument, int)), this, SLOT(slotUserFetched(QJsonDocument)));
job->start();
}
-bool ConnectionValidator::setAndCheckServerVersion(const QString& version)
+bool ConnectionValidator::setAndCheckServerVersion(const QString &version)
{
qCInfo(lcConnectionValidator) << _account->url() << "has server version" << version;
_account->setServerVersion(version);
// We cannot deal with servers < 5.0.0
if (_account->serverVersionInt()
- && _account->serverVersionInt() < Account::makeServerVersion(5, 0, 0)) {
- _errors.append( tr("The configured server for this client is too old") );
- _errors.append( tr("Please update to the latest server and restart the client.") );
- reportResult( ServerVersionMismatch );
+ && _account->serverVersionInt() < Account::makeServerVersion(5, 0, 0)) {
+ _errors.append(tr("The configured server for this client is too old"));
+ _errors.append(tr("Please update to the latest server and restart the client."));
+ reportResult(ServerVersionMismatch);
return false;
}
_account->setDavUser(user);
AvatarJob *job = new AvatarJob(_account, this);
- job->setTimeout(20*1000);
+ job->setTimeout(20 * 1000);
QObject::connect(job, SIGNAL(avatarPixmap(QImage)), this, SLOT(slotAvatarImage(QImage)));
job->start();
}
}
-void ConnectionValidator::slotAvatarImage(const QImage& img)
+void ConnectionValidator::slotAvatarImage(const QImage &img)
{
_account->setAvatar(img);
reportResult(Connected);
Timeout // actually also used for other errors on the authed request
};
- static QString statusString( Status );
+ static QString statusString(Status);
// How often should the Application ask this object to check for the connection?
enum { DefaultCallingIntervalMsec = 32 * 1000 };
void checkAuthentication();
signals:
- void connectionResult( ConnectionValidator::Status status, QStringList errors );
+ void connectionResult(ConnectionValidator::Status status, QStringList errors);
protected slots:
void slotCheckServerAndAuth();
- void slotStatusFound(const QUrl&url, const QJsonObject &info);
+ void slotStatusFound(const QUrl &url, const QJsonObject &info);
void slotNoStatusFound(QNetworkReply *reply);
- void slotJobTimeout(const QUrl& url);
+ void slotJobTimeout(const QUrl &url);
void slotAuthFailed(QNetworkReply *reply);
void slotAuthSuccess();
- void slotCapabilitiesRecieved(const QJsonDocument&);
+ void slotCapabilitiesRecieved(const QJsonDocument &);
void slotUserFetched(const QJsonDocument &);
void slotAvatarImage(const QImage &img);
*
* Returns false and reports ServerVersionMismatch for very old servers.
*/
- bool setAndCheckServerVersion(const QString& version);
+ bool setAndCheckServerVersion(const QString &version);
QStringList _errors;
- AccountPtr _account;
+ AccountPtr _account;
bool _isCheckingServerAndAuth;
};
-
}
#endif // CONNECTIONVALIDATOR_H
Q_LOGGING_CATEGORY(lcCookieJar, "sync.cookiejar", QtInfoMsg)
namespace {
- const unsigned int JAR_VERSION = 23;
+ const unsigned int JAR_VERSION = 23;
}
QDataStream &operator<<(QDataStream &stream, const QList<QNetworkCookie> &list)
quint32 count;
stream >> count;
- for(quint32 i = 0; i < count; ++i)
- {
+ for (quint32 i = 0; i < count; ++i) {
QByteArray value;
stream >> value;
QList<QNetworkCookie> newCookies = QNetworkCookie::parseCookies(value);
return stream;
}
-CookieJar::CookieJar(QObject *parent) :
- QNetworkCookieJar(parent)
+CookieJar::CookieJar(QObject *parent)
+ : QNetworkCookieJar(parent)
{
}
{
}
-bool CookieJar::setCookiesFromUrl(const QList<QNetworkCookie>& cookieList, const QUrl& url)
+bool CookieJar::setCookiesFromUrl(const QList<QNetworkCookie> &cookieList, const QUrl &url)
{
- if (QNetworkCookieJar::setCookiesFromUrl(cookieList, url)) {
- Q_EMIT newCookiesForUrl(cookieList, url);
- return true;
- }
+ if (QNetworkCookieJar::setCookiesFromUrl(cookieList, url)) {
+ Q_EMIT newCookiesForUrl(cookieList, url);
+ return true;
+ }
- return false;
+ return false;
}
QList<QNetworkCookie> CookieJar::cookiesForUrl(const QUrl &url) const
QList<QNetworkCookie> CookieJar::removeExpired(const QList<QNetworkCookie> &cookies)
{
QList<QNetworkCookie> updatedList;
- foreach(const QNetworkCookie &cookie, cookies) {
+ foreach (const QNetworkCookie &cookie, cookies) {
if (cookie.expirationDate() > QDateTime::currentDateTime() && !cookie.isSessionCookie()) {
updatedList << cookie;
}
void restore(const QString &fileName);
signals:
- void newCookiesForUrl(const QList<QNetworkCookie>& cookieList, const QUrl& url);
+ void newCookiesForUrl(const QList<QNetworkCookie> &cookieList, const QUrl &url);
+
private:
QList<QNetworkCookie> removeExpired(const QList<QNetworkCookie> &cookies);
};
#include "asserts.h"
#include "creds/abstractcredentials.h"
-namespace OCC
-{
+namespace OCC {
Q_LOGGING_CATEGORY(lcCredentials, "sync.credentials", QtInfoMsg)
QString AbstractCredentials::keychainKey(const QString &url, const QString &user)
{
QString u(url);
- if( u.isEmpty() ) {
+ if (u.isEmpty()) {
qCWarning(lcCredentials) << "Empty url in keyChain, error!";
return QString::null;
}
- if( user.isEmpty() ) {
+ if (user.isEmpty()) {
qCWarning(lcCredentials) << "Error: User is empty!";
return QString::null;
}
- if( !u.endsWith(QChar('/')) ) {
+ if (!u.endsWith(QChar('/'))) {
u.append(QChar('/'));
}
- QString key = user+QLatin1Char(':')+u;
+ QString key = user + QLatin1Char(':') + u;
return key;
}
} // namespace OCC
class QNetworkAccessManager;
class QNetworkReply;
-namespace OCC
-{
+namespace OCC {
class OWNCLOUDSYNC_EXPORT AbstractCredentials : public QObject
{
* Calling Account::setCredentials() will call this function.
* Credentials only live as long as the underlying account object.
*/
- virtual void setAccount(Account* account);
+ virtual void setAccount(Account *account);
virtual QString authType() const = 0;
virtual QString user() const = 0;
- virtual QNetworkAccessManager* getQNAM() const = 0;
+ virtual QNetworkAccessManager *getQNAM() const = 0;
virtual bool ready() const = 0;
virtual void fetchFromKeychain() = 0;
virtual void askFromUser() = 0;
void asked();
protected:
- Account* _account;
+ Account *_account;
};
} // namespace OCC
#include "account.h"
#include "syncengine.h"
-namespace OCC
-{
+namespace OCC {
} // namespace OCC
#include "owncloudlib.h"
-namespace OCC
-{
+namespace OCC {
} // namespace OCC
#include "creds/dummycredentials.h"
#include "accessmanager.h"
-namespace OCC
-{
+namespace OCC {
QString DummyCredentials::authType() const
{
return _user;
}
-QNetworkAccessManager* DummyCredentials::getQNAM() const
+QNetworkAccessManager *DummyCredentials::getQNAM() const
{
return new AccessManager;
}
}
void DummyCredentials::persist()
-{}
+{
+}
} // namespace OCC
#include "creds/abstractcredentials.h"
-namespace OCC
-{
+namespace OCC {
class OWNCLOUDSYNC_EXPORT DummyCredentials : public AbstractCredentials
{
Q_OBJECT
public:
-
QString _user;
QString _password;
QString authType() const Q_DECL_OVERRIDE;
QString user() const Q_DECL_OVERRIDE;
- QNetworkAccessManager* getQNAM() const Q_DECL_OVERRIDE;
+ QNetworkAccessManager *getQNAM() const Q_DECL_OVERRIDE;
bool ready() const Q_DECL_OVERRIDE;
bool stillValid(QNetworkReply *reply) Q_DECL_OVERRIDE;
void fetchFromKeychain() Q_DECL_OVERRIDE;
void askFromUser() Q_DECL_OVERRIDE;
void persist() Q_DECL_OVERRIDE;
void invalidateToken() Q_DECL_OVERRIDE {}
- void forgetSensitiveData() Q_DECL_OVERRIDE {};
+ void forgetSensitiveData() Q_DECL_OVERRIDE{};
};
} // namespace OCC
using namespace QKeychain;
-namespace OCC
-{
+namespace OCC {
Q_LOGGING_CATEGORY(lcHttpCredentials, "sync.credentials.http", QtInfoMsg)
-namespace
-{
-const char userC[] = "user";
-const char clientCertificatePEMC[] = "_clientCertificatePEM";
-const char clientKeyPEMC[] = "_clientKeyPEM";
-const char authenticationFailedC[] = "owncloud-authentication-failed";
+namespace {
+ const char userC[] = "user";
+ const char clientCertificatePEMC[] = "_clientCertificatePEM";
+ const char clientKeyPEMC[] = "_clientKeyPEM";
+ const char authenticationFailedC[] = "owncloud-authentication-failed";
} // ns
-class HttpCredentialsAccessManager : public AccessManager {
+class HttpCredentialsAccessManager : public AccessManager
+{
public:
- HttpCredentialsAccessManager(const HttpCredentials *cred, QObject* parent = 0)
- : AccessManager(parent), _cred(cred) {}
+ HttpCredentialsAccessManager(const HttpCredentials *cred, QObject *parent = 0)
+ : AccessManager(parent)
+ , _cred(cred)
+ {
+ }
+
protected:
- QNetworkReply *createRequest(Operation op, const QNetworkRequest &request, QIODevice *outgoingData) Q_DECL_OVERRIDE {
- QByteArray credHash = QByteArray(_cred->user().toUtf8()+":"+_cred->password().toUtf8()).toBase64();
+ QNetworkReply *createRequest(Operation op, const QNetworkRequest &request, QIODevice *outgoingData) Q_DECL_OVERRIDE
+ {
+ QByteArray credHash = QByteArray(_cred->user().toUtf8() + ":" + _cred->password().toUtf8()).toBase64();
QNetworkRequest req(request);
req.setRawHeader(QByteArray("Authorization"), QByteArray("Basic ") + credHash);
return AccessManager::createRequest(op, req, outgoingData);
}
+
private:
const HttpCredentials *_cred;
};
}
// From wizard
-HttpCredentials::HttpCredentials(const QString& user, const QString& password, const QSslCertificate& certificate, const QSslKey& key)
- : _user(user),
- _password(password),
- _ready(true),
- _clientSslKey(key),
- _clientSslCertificate(certificate)
+HttpCredentials::HttpCredentials(const QString &user, const QString &password, const QSslCertificate &certificate, const QSslKey &key)
+ : _user(user)
+ , _password(password)
+ , _ready(true)
+ , _clientSslKey(key)
+ , _clientSslCertificate(certificate)
{
}
return _password;
}
-void HttpCredentials::setAccount(Account* account)
+void HttpCredentials::setAccount(Account *account)
{
AbstractCredentials::setAccount(account);
if (_user.isEmpty()) {
}
}
-QNetworkAccessManager* HttpCredentials::getQNAM() const
+QNetworkAccessManager *HttpCredentials::getQNAM() const
{
- AccessManager* qnam = new HttpCredentialsAccessManager(this);
+ AccessManager *qnam = new HttpCredentialsAccessManager(this);
- connect( qnam, SIGNAL(authenticationRequired(QNetworkReply*, QAuthenticator*)),
- this, SLOT(slotAuthentication(QNetworkReply*,QAuthenticator*)));
+ connect(qnam, SIGNAL(authenticationRequired(QNetworkReply *, QAuthenticator *)),
+ this, SLOT(slotAuthentication(QNetworkReply *, QAuthenticator *)));
return qnam;
}
// User must be fetched from config file
fetchUser();
- const QString kck = keychainKey(_account->url().toString(), _user );
+ const QString kck = keychainKey(_account->url().toString(), _user);
if (_ready) {
Q_EMIT fetched();
job->setKey(kck);
qCDebug(lcHttpCredentials) << "-------- ----->" << _clientSslCertificate << _clientSslKey;
- connect(job, SIGNAL(finished(QKeychain::Job*)), SLOT(slotReadClientCertPEMJobDone(QKeychain::Job*)));
+ connect(job, SIGNAL(finished(QKeychain::Job *)), SLOT(slotReadClientCertPEMJobDone(QKeychain::Job *)));
job->start();
}
}
-void HttpCredentials::slotReadClientCertPEMJobDone(QKeychain::Job* incoming)
+void HttpCredentials::slotReadClientCertPEMJobDone(QKeychain::Job *incoming)
{
// Store PEM in memory
- ReadPasswordJob *readJob = static_cast<ReadPasswordJob*>(incoming);
+ ReadPasswordJob *readJob = static_cast<ReadPasswordJob *>(incoming);
if (readJob->error() == NoError && readJob->binaryData().length() > 0) {
QList<QSslCertificate> sslCertificateList = QSslCertificate::fromData(readJob->binaryData(), QSsl::Pem);
- if(sslCertificateList.length() >= 1) {
+ if (sslCertificateList.length() >= 1) {
_clientSslCertificate = sslCertificateList.at(0);
}
}
job->setInsecureFallback(false);
job->setKey(kck);
- connect(job, SIGNAL(finished(QKeychain::Job*)), SLOT(slotReadClientKeyPEMJobDone(QKeychain::Job*)));
+ connect(job, SIGNAL(finished(QKeychain::Job *)), SLOT(slotReadClientKeyPEMJobDone(QKeychain::Job *)));
job->start();
}
-void HttpCredentials::slotReadClientKeyPEMJobDone(QKeychain::Job* incoming)
+void HttpCredentials::slotReadClientKeyPEMJobDone(QKeychain::Job *incoming)
{
// Store key in memory
- ReadPasswordJob *readJob = static_cast<ReadPasswordJob*>(incoming);
+ ReadPasswordJob *readJob = static_cast<ReadPasswordJob *>(incoming);
if (readJob->error() == NoError && readJob->binaryData().length() > 0) {
QByteArray clientKeyPEM = readJob->binaryData();
}
// Now fetch the actual server password
- const QString kck = keychainKey(_account->url().toString(), _user );
+ const QString kck = keychainKey(_account->url().toString(), _user);
ReadPasswordJob *job = new ReadPasswordJob(Theme::instance()->appName());
addSettingsToJob(_account, job);
job->setInsecureFallback(false);
job->setKey(kck);
- connect(job, SIGNAL(finished(QKeychain::Job*)), SLOT(slotReadJobDone(QKeychain::Job*)));
+ connect(job, SIGNAL(finished(QKeychain::Job *)), SLOT(slotReadJobDone(QKeychain::Job *)));
job->start();
}
bool HttpCredentials::stillValid(QNetworkReply *reply)
{
return ((reply->error() != QNetworkReply::AuthenticationRequiredError)
- // returned if user or password is incorrect
- && (reply->error() != QNetworkReply::OperationCanceledError
- || !reply->property(authenticationFailedC).toBool()));
+ // returned if user or password is incorrect
+ && (reply->error() != QNetworkReply::OperationCanceledError
+ || !reply->property(authenticationFailedC).toBool()));
}
void HttpCredentials::slotReadJobDone(QKeychain::Job *incomingJob)
{
- QKeychain::ReadPasswordJob *job = static_cast<ReadPasswordJob*>(incomingJob);
+ QKeychain::ReadPasswordJob *job = static_cast<ReadPasswordJob *>(incomingJob);
_password = job->textData();
- if( _user.isEmpty()) {
+ if (_user.isEmpty()) {
qCWarning(lcHttpCredentials) << "Strange: User is empty!";
}
QKeychain::Error error = job->error();
- if( !_password.isEmpty() && error == NoError ) {
+ if (!_password.isEmpty() && error == NoError) {
// All cool, the keychain did not come back with error.
// Still, the password can be empty which indicates a problem and
// the password dialog has to be opened.
void HttpCredentials::invalidateToken()
{
- if (! _password.isEmpty()) {
+ if (!_password.isEmpty()) {
_previousPassword = _password;
}
_password = QString();
fetchUser();
const QString kck = keychainKey(_account->url().toString(), _user);
- if( kck.isEmpty() ) {
+ if (kck.isEmpty()) {
qCWarning(lcHttpCredentials) << "InvalidateToken: User is empty, bailing out!";
return;
}
WritePasswordJob *job = new WritePasswordJob(Theme::instance()->appName());
addSettingsToJob(_account, job);
job->setInsecureFallback(false);
- connect(job, SIGNAL(finished(QKeychain::Job*)), SLOT(slotWriteClientCertPEMJobDone(QKeychain::Job*)));
+ connect(job, SIGNAL(finished(QKeychain::Job *)), SLOT(slotWriteClientCertPEMJobDone(QKeychain::Job *)));
job->setKey(keychainKey(_account->url().toString(), _user + clientCertificatePEMC));
job->setBinaryData(_clientSslCertificate.toPem());
job->start();
{
Q_UNUSED(incomingJob);
// write ssl key
- WritePasswordJob* job = new WritePasswordJob(Theme::instance()->appName());
+ WritePasswordJob *job = new WritePasswordJob(Theme::instance()->appName());
addSettingsToJob(_account, job);
job->setInsecureFallback(false);
- connect(job, SIGNAL(finished(QKeychain::Job*)), SLOT(slotWriteClientKeyPEMJobDone(QKeychain::Job*)));
+ connect(job, SIGNAL(finished(QKeychain::Job *)), SLOT(slotWriteClientKeyPEMJobDone(QKeychain::Job *)));
job->setKey(keychainKey(_account->url().toString(), _user + clientKeyPEMC));
job->setBinaryData(_clientSslKey.toPem());
job->start();
void HttpCredentials::slotWriteClientKeyPEMJobDone(Job *incomingJob)
{
Q_UNUSED(incomingJob);
- WritePasswordJob* job = new WritePasswordJob(Theme::instance()->appName());
+ WritePasswordJob *job = new WritePasswordJob(Theme::instance()->appName());
addSettingsToJob(_account, job);
job->setInsecureFallback(false);
- connect(job, SIGNAL(finished(QKeychain::Job*)), SLOT(slotWriteJobDone(QKeychain::Job*)));
+ connect(job, SIGNAL(finished(QKeychain::Job *)), SLOT(slotWriteJobDone(QKeychain::Job *)));
job->setKey(keychainKey(_account->url().toString(), _user));
job->setTextData(_password);
job->start();
default:
qCWarning(lcHttpCredentials) << "Error while writing password" << job->errorString();
}
- WritePasswordJob *wjob = qobject_cast<WritePasswordJob*>(job);
+ WritePasswordJob *wjob = qobject_cast<WritePasswordJob *>(job);
wjob->deleteLater();
}
-void HttpCredentials::slotAuthentication(QNetworkReply* reply, QAuthenticator* authenticator)
+void HttpCredentials::slotAuthentication(QNetworkReply *reply, QAuthenticator *authenticator)
{
Q_UNUSED(authenticator)
// Because of issue #4326, we need to set the login and password manually at every requests
class ReadPasswordJob;
}
-namespace OCC
-{
+namespace OCC {
class OWNCLOUDSYNC_EXPORT HttpCredentials : public AbstractCredentials
{
Q_OBJECT
friend class HttpCredentialsAccessManager;
+
public:
explicit HttpCredentials();
- HttpCredentials(const QString& user, const QString& password, const QSslCertificate& certificate = QSslCertificate(), const QSslKey& key = QSslKey());
+ HttpCredentials(const QString &user, const QString &password, const QSslCertificate &certificate = QSslCertificate(), const QSslKey &key = QSslKey());
QString authType() const Q_DECL_OVERRIDE;
- QNetworkAccessManager* getQNAM() const Q_DECL_OVERRIDE;
+ QNetworkAccessManager *getQNAM() const Q_DECL_OVERRIDE;
bool ready() const Q_DECL_OVERRIDE;
void fetchFromKeychain() Q_DECL_OVERRIDE;
bool stillValid(QNetworkReply *reply) Q_DECL_OVERRIDE;
virtual bool sslIsTrusted() { return false; }
// To fetch the user name as early as possible
- void setAccount(Account* account) Q_DECL_OVERRIDE;
+ void setAccount(Account *account) Q_DECL_OVERRIDE;
private Q_SLOTS:
- void slotAuthentication(QNetworkReply*, QAuthenticator*);
+ void slotAuthentication(QNetworkReply *, QAuthenticator *);
- void slotReadClientCertPEMJobDone(QKeychain::Job*);
- void slotReadClientKeyPEMJobDone(QKeychain::Job*);
- void slotReadJobDone(QKeychain::Job*);
+ void slotReadClientCertPEMJobDone(QKeychain::Job *);
+ void slotReadClientKeyPEMJobDone(QKeychain::Job *);
+ void slotReadJobDone(QKeychain::Job *);
- void slotWriteClientCertPEMJobDone(QKeychain::Job*);
- void slotWriteClientKeyPEMJobDone(QKeychain::Job*);
- void slotWriteJobDone(QKeychain::Job*);
+ void slotWriteClientCertPEMJobDone(QKeychain::Job *);
+ void slotWriteClientKeyPEMJobDone(QKeychain::Job *);
+ void slotWriteJobDone(QKeychain::Job *);
void clearQNAMCache();
protected:
#include "creds/tokencredentials.h"
-namespace OCC
-{
+namespace OCC {
Q_LOGGING_CATEGORY(lcTokenCredentials, "sync.credentials.token", QtInfoMsg)
-namespace
-{
+namespace {
-const char authenticationFailedC[] = "owncloud-authentication-failed";
+ const char authenticationFailedC[] = "owncloud-authentication-failed";
} // ns
-class TokenCredentialsAccessManager : public AccessManager {
+class TokenCredentialsAccessManager : public AccessManager
+{
public:
friend class TokenCredentials;
- TokenCredentialsAccessManager(const TokenCredentials *cred, QObject* parent = 0)
- : AccessManager(parent), _cred(cred) {}
+ TokenCredentialsAccessManager(const TokenCredentials *cred, QObject *parent = 0)
+ : AccessManager(parent)
+ , _cred(cred)
+ {
+ }
+
protected:
- QNetworkReply *createRequest(Operation op, const QNetworkRequest &request, QIODevice *outgoingData) {
+ QNetworkReply *createRequest(Operation op, const QNetworkRequest &request, QIODevice *outgoingData)
+ {
if (_cred->user().isEmpty() || _cred->password().isEmpty()) {
qCWarning(lcTokenCredentials) << "Empty user/password provided!";
}
QNetworkRequest req(request);
- QByteArray credHash = QByteArray(_cred->user().toUtf8()+":"+_cred->password().toUtf8()).toBase64();
+ QByteArray credHash = QByteArray(_cred->user().toUtf8() + ":" + _cred->password().toUtf8()).toBase64();
req.setRawHeader(QByteArray("Authorization"), QByteArray("Basic ") + credHash);
// A pre-authenticated cookie
return AccessManager::createRequest(op, req, outgoingData);
}
+
private:
const TokenCredentials *_cred;
};
TokenCredentials::TokenCredentials()
- : _user(),
- _password(),
- _ready(false)
+ : _user()
+ , _password()
+ , _ready(false)
{
}
-TokenCredentials::TokenCredentials(const QString& user, const QString& password, const QString &token)
- : _user(user),
- _password(password),
- _token(token),
- _ready(true)
+TokenCredentials::TokenCredentials(const QString &user, const QString &password, const QString &token)
+ : _user(user)
+ , _password(password)
+ , _token(token)
+ , _ready(true)
{
}
return _password;
}
-QNetworkAccessManager* TokenCredentials::getQNAM() const
+QNetworkAccessManager *TokenCredentials::getQNAM() const
{
- AccessManager* qnam = new TokenCredentialsAccessManager(this);
+ AccessManager *qnam = new TokenCredentialsAccessManager(this);
- connect( qnam, SIGNAL(authenticationRequired(QNetworkReply*, QAuthenticator*)),
- this, SLOT(slotAuthentication(QNetworkReply*,QAuthenticator*)));
+ connect(qnam, SIGNAL(authenticationRequired(QNetworkReply *, QAuthenticator *)),
+ this, SLOT(slotAuthentication(QNetworkReply *, QAuthenticator *)));
return qnam;
}
bool TokenCredentials::stillValid(QNetworkReply *reply)
{
return ((reply->error() != QNetworkReply::AuthenticationRequiredError)
- // returned if user/password or token are incorrect
- && (reply->error() != QNetworkReply::OperationCanceledError
- || !reply->property(authenticationFailedC).toBool()));
+ // returned if user/password or token are incorrect
+ && (reply->error() != QNetworkReply::OperationCanceledError
+ || !reply->property(authenticationFailedC).toBool()));
}
void TokenCredentials::invalidateToken()
}
-void TokenCredentials::slotAuthentication(QNetworkReply* reply, QAuthenticator* authenticator)
+void TokenCredentials::slotAuthentication(QNetworkReply *reply, QAuthenticator *authenticator)
{
Q_UNUSED(authenticator)
// we cannot use QAuthenticator, because it sends username and passwords with latin1
class Job;
}
-namespace OCC
-{
+namespace OCC {
class TokenCredentialsAccessManager;
class OWNCLOUDSYNC_EXPORT TokenCredentials : public AbstractCredentials
public:
friend class TokenCredentialsAccessManager;
TokenCredentials();
- TokenCredentials(const QString& user, const QString& password, const QString &token);
+ TokenCredentials(const QString &user, const QString &password, const QString &token);
QString authType() const Q_DECL_OVERRIDE;
- QNetworkAccessManager* getQNAM() const Q_DECL_OVERRIDE;
+ QNetworkAccessManager *getQNAM() const Q_DECL_OVERRIDE;
bool ready() const Q_DECL_OVERRIDE;
void askFromUser() Q_DECL_OVERRIDE;
void fetchFromKeychain() Q_DECL_OVERRIDE;
QString password() const;
private Q_SLOTS:
- void slotAuthentication(QNetworkReply*, QAuthenticator*);
+ void slotAuthentication(QNetworkReply *, QAuthenticator *);
private:
QString _user;
int DiscoveryJob::isInSelectiveSyncBlackListCallback(void *data, const char *path)
{
- return static_cast<DiscoveryJob*>(data)->isInSelectiveSyncBlackList(path);
+ return static_cast<DiscoveryJob *>(data)->isInSelectiveSyncBlackList(path);
}
-bool DiscoveryJob::checkSelectiveSyncNewFolder(const QString& path, const char *remotePerm)
+bool DiscoveryJob::checkSelectiveSyncNewFolder(const QString &path, const char *remotePerm)
{
-
if (_syncOptions._confirmExternalStorage && std::strchr(remotePerm, 'M')) {
// 'M' in the permission means external storage.
return true;
}
- // If this path or the parent is in the white list, then we do not block this file
+ // If this path or the parent is in the white list, then we do not block this file
if (findPathInList(_selectiveSyncWhiteList, path)) {
return false;
}
// it is not too big, put it in the white list (so we will not do more query for the children)
// and and do not block.
auto p = path;
- if (!p.endsWith(QLatin1Char('/'))) { p += QLatin1Char('/'); }
+ if (!p.endsWith(QLatin1Char('/'))) {
+ p += QLatin1Char('/');
+ }
_selectiveSyncWhiteList.insert(std::upper_bound(_selectiveSyncWhiteList.begin(),
- _selectiveSyncWhiteList.end(), p), p);
+ _selectiveSyncWhiteList.end(), p),
+ p);
return false;
}
int DiscoveryJob::checkSelectiveSyncNewFolderCallback(void *data, const char *path, const char *remotePerm)
{
- return static_cast<DiscoveryJob*>(data)->checkSelectiveSyncNewFolder(QString::fromUtf8(path), remotePerm);
+ return static_cast<DiscoveryJob *>(data)->checkSelectiveSyncNewFolder(QString::fromUtf8(path), remotePerm);
}
-void DiscoveryJob::update_job_update_callback (bool local,
- const char *dirUrl,
- void *userdata)
+void DiscoveryJob::update_job_update_callback(bool local,
+ const char *dirUrl,
+ void *userdata)
{
- DiscoveryJob *updateJob = static_cast<DiscoveryJob*>(userdata);
+ DiscoveryJob *updateJob = static_cast<DiscoveryJob *>(userdata);
if (updateJob) {
// Don't wanna overload the UI
if (!updateJob->_lastUpdateProgressCallbackCall.isValid()) {
QByteArray pPath(dirUrl);
int indx = pPath.lastIndexOf('/');
- if(indx>-1) {
- const QString path = QUrl::fromPercentEncoding( pPath.mid(indx+1));
+ if (indx > -1) {
+ const QString path = QUrl::fromPercentEncoding(pPath.mid(indx + 1));
emit updateJob->folderDiscovered(local, path);
}
}
}
// Only use for error cases! It will always set an error errno
-int get_errno_from_http_errcode( int err, const QString & reason ) {
+int get_errno_from_http_errcode(int err, const QString &reason)
+{
int new_errno = EIO;
- switch(err) {
- case 401: /* Unauthorized */
- case 402: /* Payment Required */
- case 407: /* Proxy Authentication Required */
+ switch (err) {
+ case 401: /* Unauthorized */
+ case 402: /* Payment Required */
+ case 407: /* Proxy Authentication Required */
case 405:
new_errno = EPERM;
break;
- case 301: /* Moved Permanently */
- case 303: /* See Other */
- case 404: /* Not Found */
- case 410: /* Gone */
+ case 301: /* Moved Permanently */
+ case 303: /* See Other */
+ case 404: /* Not Found */
+ case 410: /* Gone */
new_errno = ENOENT;
break;
- case 408: /* Request Timeout */
- case 504: /* Gateway Timeout */
+ case 408: /* Request Timeout */
+ case 504: /* Gateway Timeout */
new_errno = EAGAIN;
break;
- case 423: /* Locked */
+ case 423: /* Locked */
new_errno = EACCES;
break;
- case 403: /* Forbidden */
+ case 403: /* Forbidden */
new_errno = ERRNO_FORBIDDEN;
break;
- case 400: /* Bad Request */
- case 409: /* Conflict */
- case 411: /* Length Required */
- case 412: /* Precondition Failed */
- case 414: /* Request-URI Too Long */
- case 415: /* Unsupported Media Type */
- case 424: /* Failed Dependency */
- case 501: /* Not Implemented */
+ case 400: /* Bad Request */
+ case 409: /* Conflict */
+ case 411: /* Length Required */
+ case 412: /* Precondition Failed */
+ case 414: /* Request-URI Too Long */
+ case 415: /* Unsupported Media Type */
+ case 424: /* Failed Dependency */
+ case 501: /* Not Implemented */
new_errno = EINVAL;
break;
- case 507: /* Insufficient Storage */
+ case 507: /* Insufficient Storage */
new_errno = ENOSPC;
break;
- case 206: /* Partial Content */
- case 300: /* Multiple Choices */
- case 302: /* Found */
- case 305: /* Use Proxy */
- case 306: /* (Unused) */
- case 307: /* Temporary Redirect */
- case 406: /* Not Acceptable */
- case 416: /* Requested Range Not Satisfiable */
- case 417: /* Expectation Failed */
- case 422: /* Unprocessable Entity */
- case 500: /* Internal Server Error */
- case 502: /* Bad Gateway */
- case 505: /* HTTP Version Not Supported */
+ case 206: /* Partial Content */
+ case 300: /* Multiple Choices */
+ case 302: /* Found */
+ case 305: /* Use Proxy */
+ case 306: /* (Unused) */
+ case 307: /* Temporary Redirect */
+ case 406: /* Not Acceptable */
+ case 416: /* Requested Range Not Satisfiable */
+ case 417: /* Expectation Failed */
+ case 422: /* Unprocessable Entity */
+ case 500: /* Internal Server Error */
+ case 502: /* Bad Gateway */
+ case 505: /* HTTP Version Not Supported */
new_errno = EIO;
break;
- case 503: /* Service Unavailable */
+ case 503: /* Service Unavailable */
// https://github.com/owncloud/core/pull/26145/files
if (reason == "Storage not available" || reason == "Storage is temporarily not available") {
new_errno = ERRNO_STORAGE_UNAVAILABLE;
new_errno = ERRNO_SERVICE_UNAVAILABLE;
}
break;
- case 413: /* Request Entity too Large */
+ case 413: /* Request Entity too Large */
new_errno = EFBIG;
break;
default:
}
-
DiscoverySingleDirectoryJob::DiscoverySingleDirectoryJob(const AccountPtr &account, const QString &path, QObject *parent)
- : QObject(parent), _subPath(path), _account(account), _ignoredFirst(false), _isRootPath(false), _isExternalStorage(false)
+ : QObject(parent)
+ , _subPath(path)
+ , _account(account)
+ , _ignoredFirst(false)
+ , _isRootPath(false)
+ , _isExternalStorage(false)
{
}
LsColJob *lsColJob = new LsColJob(_account, _subPath, this);
QList<QByteArray> props;
- props << "resourcetype" << "getlastmodified" << "getcontentlength" << "getetag"
- << "http://owncloud.org/ns:id" << "http://owncloud.org/ns:downloadURL"
- << "http://owncloud.org/ns:dDC" << "http://owncloud.org/ns:permissions";
+ props << "resourcetype"
+ << "getlastmodified"
+ << "getcontentlength"
+ << "getetag"
+ << "http://owncloud.org/ns:id"
+ << "http://owncloud.org/ns:downloadURL"
+ << "http://owncloud.org/ns:dDC"
+ << "http://owncloud.org/ns:permissions";
if (_isRootPath)
props << "http://owncloud.org/ns:data-fingerprint";
lsColJob->setProperties(props);
- QObject::connect(lsColJob, SIGNAL(directoryListingIterated(QString,QMap<QString,QString>)),
- this, SLOT(directoryListingIteratedSlot(QString,QMap<QString,QString>)));
- QObject::connect(lsColJob, SIGNAL(finishedWithError(QNetworkReply*)), this, SLOT(lsJobFinishedWithErrorSlot(QNetworkReply*)));
+ QObject::connect(lsColJob, SIGNAL(directoryListingIterated(QString, QMap<QString, QString>)),
+ this, SLOT(directoryListingIteratedSlot(QString, QMap<QString, QString>)));
+ QObject::connect(lsColJob, SIGNAL(finishedWithError(QNetworkReply *)), this, SLOT(lsJobFinishedWithErrorSlot(QNetworkReply *)));
QObject::connect(lsColJob, SIGNAL(finishedWithoutError()), this, SLOT(lsJobFinishedWithoutErrorSlot()));
lsColJob->start();
}
}
-static csync_vio_file_stat_t* propertyMapToFileStat(const QMap<QString,QString> &map)
+static csync_vio_file_stat_t *propertyMapToFileStat(const QMap<QString, QString> &map)
{
- csync_vio_file_stat_t* file_stat = csync_vio_file_stat_new();
+ csync_vio_file_stat_t *file_stat = csync_vio_file_stat_new();
for (auto it = map.constBegin(); it != map.constEnd(); ++it) {
QString property = it.key();
file_stat->type = CSYNC_VIO_FILE_TYPE_REGULAR;
}
file_stat->fields |= CSYNC_VIO_FILE_STAT_FIELDS_TYPE;
- } else if (property == "getlastmodified") {
+ } else if (property == "getlastmodified") {
file_stat->mtime = oc_httpdate_parse(value.toUtf8());
file_stat->fields |= CSYNC_VIO_FILE_STAT_FIELDS_MTIME;
} else if (property == "getcontentlength") {
return file_stat;
}
-void DiscoverySingleDirectoryJob::directoryListingIteratedSlot(QString file, const QMap<QString,QString> &map)
+void DiscoverySingleDirectoryJob::directoryListingIteratedSlot(QString file, const QMap<QString, QString> &map)
{
if (!_ignoredFirst) {
// The first entry is for the folder itself, we should process it differently.
purposes in the desktop client, we only need to know about the mount points.
So replace the 'M' by a 'm' for every sub entries in an external storage */
std::replace(file_stat->remotePerm, file_stat->remotePerm + strlen(file_stat->remotePerm),
- 'M', 'm');
+ 'M', 'm');
}
QStringRef fileRef(&file);
int slashPos = file.lastIndexOf(QLatin1Char('/'));
- if( slashPos > -1 ) {
- fileRef = file.midRef(slashPos+1);
+ if (slashPos > -1) {
+ fileRef = file.midRef(slashPos + 1);
}
_results.append(file_stat);
}
//This works in concerto with the RequestEtagJob and the Folder object to check if the remote folder changed.
if (map.contains("getetag")) {
- _etagConcatenation += map.value("getetag");
+ _etagConcatenation += map.value("getetag");
- if (_firstEtag.isEmpty()) {
- _firstEtag = map.value("getetag"); // for directory itself
- }
+ if (_firstEtag.isEmpty()) {
+ _firstEtag = map.value("getetag"); // for directory itself
+ }
}
}
_discoveryJob = discoveryJob;
_pathPrefix = pathPrefix;
- connect(discoveryJob, SIGNAL(doOpendirSignal(QString,DiscoveryDirectoryResult*)),
- this, SLOT(doOpendirSlot(QString,DiscoveryDirectoryResult*)),
- Qt::QueuedConnection);
- connect(discoveryJob, SIGNAL(doGetSizeSignal(QString,qint64*)),
- this, SLOT(doGetSizeSlot(QString,qint64*)),
- Qt::QueuedConnection);
+ connect(discoveryJob, SIGNAL(doOpendirSignal(QString, DiscoveryDirectoryResult *)),
+ this, SLOT(doOpendirSlot(QString, DiscoveryDirectoryResult *)),
+ Qt::QueuedConnection);
+ connect(discoveryJob, SIGNAL(doGetSizeSignal(QString, qint64 *)),
+ this, SLOT(doGetSizeSlot(QString, qint64 *)),
+ Qt::QueuedConnection);
}
// Coming from owncloud_opendir -> DiscoveryJob::vio_opendir_hook -> doOpendirSignal
}
// emit _discoveryJob->folderDiscovered(false, subPath);
- _discoveryJob->update_job_update_callback (false, subPath.toUtf8(), _discoveryJob);
+ _discoveryJob->update_job_update_callback(false, subPath.toUtf8(), _discoveryJob);
// Result gets written in there
_currentDiscoveryDirectoryResult = r;
// Schedule the DiscoverySingleDirectoryJob
_singleDirJob = new DiscoverySingleDirectoryJob(_account, fullPath, this);
QObject::connect(_singleDirJob, SIGNAL(finishedWithResult(const QList<FileStatPointer> &)),
- this, SLOT(singleDirectoryJobResultSlot(const QList<FileStatPointer> &)));
- QObject::connect(_singleDirJob, SIGNAL(finishedWithError(int,QString)),
- this, SLOT(singleDirectoryJobFinishedWithErrorSlot(int,QString)));
+ this, SLOT(singleDirectoryJobResultSlot(const QList<FileStatPointer> &)));
+ QObject::connect(_singleDirJob, SIGNAL(finishedWithError(int, QString)),
+ this, SLOT(singleDirectoryJobFinishedWithErrorSlot(int, QString)));
QObject::connect(_singleDirJob, SIGNAL(firstDirectoryPermissions(QString)),
- this, SLOT(singleDirectoryJobFirstDirectoryPermissionsSlot(QString)));
+ this, SLOT(singleDirectoryJobFirstDirectoryPermissionsSlot(QString)));
QObject::connect(_singleDirJob, SIGNAL(etagConcatenation(QString)),
- this, SIGNAL(etagConcatenation(QString)));
+ this, SIGNAL(etagConcatenation(QString)));
QObject::connect(_singleDirJob, SIGNAL(etag(QString)),
- this, SIGNAL(etag(QString)));
+ this, SIGNAL(etag(QString)));
if (!_firstFolderProcessed) {
_singleDirJob->setIsRootPath();
}
-void DiscoveryMainThread::singleDirectoryJobResultSlot(const QList<FileStatPointer> & result)
+void DiscoveryMainThread::singleDirectoryJobResultSlot(const QList<FileStatPointer> &result)
{
if (!_currentDiscoveryDirectoryResult) {
return; // possibly aborted
}
qCDebug(lcDiscovery) << csyncErrnoCode << msg;
- _currentDiscoveryDirectoryResult->code = csyncErrnoCode;
- _currentDiscoveryDirectoryResult->msg = msg;
- _currentDiscoveryDirectoryResult = 0; // the sync thread owns it now
+ _currentDiscoveryDirectoryResult->code = csyncErrnoCode;
+ _currentDiscoveryDirectoryResult->msg = msg;
+ _currentDiscoveryDirectoryResult = 0; // the sync thread owns it now
_discoveryJob->_vioMutex.lock();
_discoveryJob->_vioWaitCondition.wakeAll();
}
}
-void DiscoveryMainThread::doGetSizeSlot(const QString& path, qint64* result)
+void DiscoveryMainThread::doGetSizeSlot(const QString &path, qint64 *result)
{
QString fullPath = _pathPrefix;
if (!_pathPrefix.endsWith('/')) {
// Schedule the DiscoverySingleDirectoryJob
auto propfindJob = new PropfindJob(_account, fullPath, this);
- propfindJob->setProperties(QList<QByteArray>() << "resourcetype" << "http://owncloud.org/ns:size");
+ propfindJob->setProperties(QList<QByteArray>() << "resourcetype"
+ << "http://owncloud.org/ns:size");
QObject::connect(propfindJob, SIGNAL(finishedWithError()),
- this, SLOT(slotGetSizeFinishedWithError()));
+ this, SLOT(slotGetSizeFinishedWithError()));
QObject::connect(propfindJob, SIGNAL(result(QVariantMap)),
- this, SLOT(slotGetSizeResult(QVariantMap)));
+ this, SLOT(slotGetSizeResult(QVariantMap)));
propfindJob->start();
}
void DiscoveryMainThread::slotGetSizeFinishedWithError()
{
- if (! _currentGetSizeResult) {
+ if (!_currentGetSizeResult) {
return; // possibly aborted
}
_currentGetSizeResult = 0;
QMutexLocker locker(&_discoveryJob->_vioMutex);
_discoveryJob->_vioWaitCondition.wakeAll();
-
}
void DiscoveryMainThread::slotGetSizeResult(const QVariantMap &map)
{
- if (! _currentGetSizeResult) {
+ if (!_currentGetSizeResult) {
return; // possibly aborted
}
}
-
-
// called from SyncEngine
-void DiscoveryMainThread::abort() {
+void DiscoveryMainThread::abort()
+{
if (_singleDirJob) {
- _singleDirJob->disconnect(SIGNAL(finishedWithError(int,QString)), this);
+ _singleDirJob->disconnect(SIGNAL(finishedWithError(int, QString)), this);
_singleDirJob->disconnect(SIGNAL(firstDirectoryPermissions(QString)), this);
_singleDirJob->disconnect(SIGNAL(finishedWithResult(const QList<FileStatPointer> &)), this);
_singleDirJob->abort();
}
}
-csync_vio_handle_t* DiscoveryJob::remote_vio_opendir_hook (const char *url,
- void *userdata)
+csync_vio_handle_t *DiscoveryJob::remote_vio_opendir_hook(const char *url,
+ void *userdata)
{
- DiscoveryJob *discoveryJob = static_cast<DiscoveryJob*>(userdata);
+ DiscoveryJob *discoveryJob = static_cast<DiscoveryJob *>(userdata);
if (discoveryJob) {
qCDebug(lcDiscovery) << discoveryJob << url << "Calling into main thread...";
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() );
+ discoveryJob->_csync_ctx->error_string = qstrdup(directoryResult->msg.toUtf8().constData());
return NULL;
}
}
-csync_vio_file_stat_t* DiscoveryJob::remote_vio_readdir_hook (csync_vio_handle_t *dhandle,
- void *userdata)
+csync_vio_file_stat_t *DiscoveryJob::remote_vio_readdir_hook(csync_vio_handle_t *dhandle,
+ void *userdata)
{
- DiscoveryJob *discoveryJob = static_cast<DiscoveryJob*>(userdata);
+ DiscoveryJob *discoveryJob = static_cast<DiscoveryJob *>(userdata);
if (discoveryJob) {
- DiscoveryDirectoryResult *directoryResult = static_cast<DiscoveryDirectoryResult*>(dhandle);
+ DiscoveryDirectoryResult *directoryResult = static_cast<DiscoveryDirectoryResult *>(dhandle);
if (directoryResult->listIndex < directoryResult->list.size()) {
csync_vio_file_stat_t *file_stat = directoryResult->list.at(directoryResult->listIndex++).data();
// Make a copy, csync_update will delete the copy
return NULL;
}
-void DiscoveryJob::remote_vio_closedir_hook (csync_vio_handle_t *dhandle, void *userdata)
+void DiscoveryJob::remote_vio_closedir_hook(csync_vio_handle_t *dhandle, void *userdata)
{
- DiscoveryJob *discoveryJob = static_cast<DiscoveryJob*>(userdata);
+ DiscoveryJob *discoveryJob = static_cast<DiscoveryJob *>(userdata);
if (discoveryJob) {
- DiscoveryDirectoryResult *directoryResult = static_cast<DiscoveryDirectoryResult*> (dhandle);
+ DiscoveryDirectoryResult *directoryResult = static_cast<DiscoveryDirectoryResult *>(dhandle);
QString path = directoryResult->path;
qCDebug(lcDiscovery) << discoveryJob << path;
- // just deletes the struct and the iterator, the data itself is owned by the SyncEngine/DiscoveryMainThread
+ // just deletes the struct and the iterator, the data itself is owned by the SyncEngine/DiscoveryMainThread
delete directoryResult;
}
}
-void DiscoveryJob::start() {
+void DiscoveryJob::start()
+{
_selectiveSyncBlackList.sort();
_selectiveSyncWhiteList.sort();
_csync_ctx->callbacks.update_callback_userdata = this;
emit finished(ret);
deleteLater();
}
-
}
* if the files are new, or changed.
*/
-struct SyncOptions {
+struct SyncOptions
+{
SyncOptions()
: _newBigFolderSizeLimit(-1)
, _confirmExternalStorage(false)
, _minChunkSize(1 * 1000 * 1000) // 1 MB
, _maxChunkSize(100 * 1000 * 1000) // 100 MB
, _targetChunkUploadDuration(60 * 1000) // 1 minute
- {}
+ {
+ }
/** Maximum size (in Bytes) a folder can have without asking for confirmation.
* -1 means infinite */
* @brief The FileStatPointer class
* @ingroup libsync
*/
-class FileStatPointer {
+class FileStatPointer
+{
public:
FileStatPointer(csync_vio_file_stat_t *stat)
: _stat(stat)
- { }
+ {
+ }
FileStatPointer(const FileStatPointer &other)
: _stat(csync_vio_file_stat_copy(other._stat))
- { }
- ~FileStatPointer() {
+ {
+ }
+ ~FileStatPointer()
+ {
csync_vio_file_stat_destroy(_stat);
}
- FileStatPointer &operator=(const FileStatPointer &other) {
+ FileStatPointer &operator=(const FileStatPointer &other)
+ {
csync_vio_file_stat_destroy(_stat);
_stat = csync_vio_file_stat_copy(other._stat);
return *this;
csync_vio_file_stat_t *_stat;
};
-struct DiscoveryDirectoryResult {
+struct DiscoveryDirectoryResult
+{
QString path;
QString msg;
int code;
QList<FileStatPointer> list;
int listIndex;
- DiscoveryDirectoryResult() : code(EIO), listIndex(0) { }
+ DiscoveryDirectoryResult()
+ : code(EIO)
+ , listIndex(0)
+ {
+ }
};
/**
*
* @ingroup libsync
*/
-class DiscoverySingleDirectoryJob : public QObject {
+class DiscoverySingleDirectoryJob : public QObject
+{
Q_OBJECT
public:
explicit DiscoverySingleDirectoryJob(const AccountPtr &account, const QString &path, QObject *parent = 0);
void finishedWithResult(const QList<FileStatPointer> &);
void finishedWithError(int csyncErrnoCode, const QString &msg);
private slots:
- void directoryListingIteratedSlot(QString, const QMap<QString,QString>&);
+ void directoryListingIteratedSlot(QString, const QMap<QString, QString> &);
void lsJobFinishedWithoutErrorSlot();
- void lsJobFinishedWithErrorSlot(QNetworkReply*);
+ void lsJobFinishedWithErrorSlot(QNetworkReply *);
+
private:
QList<FileStatPointer> _results;
QString _subPath;
// Lives in main thread. Deleted by the SyncEngine
class DiscoveryJob;
-class DiscoveryMainThread : public QObject {
+class DiscoveryMainThread : public QObject
+{
Q_OBJECT
QPointer<DiscoveryJob> _discoveryJob;
bool _firstFolderProcessed;
public:
- DiscoveryMainThread(AccountPtr account) : QObject(), _account(account),
- _currentDiscoveryDirectoryResult(0), _currentGetSizeResult(0), _firstFolderProcessed(false)
- { }
+ DiscoveryMainThread(AccountPtr account)
+ : QObject()
+ , _account(account)
+ , _currentDiscoveryDirectoryResult(0)
+ , _currentGetSizeResult(0)
+ , _firstFolderProcessed(false)
+ {
+ }
void abort();
QByteArray _dataFingerprint;
public slots:
// From DiscoveryJob:
- void doOpendirSlot(const QString &url, DiscoveryDirectoryResult* );
- void doGetSizeSlot(const QString &path ,qint64 *result);
+ void doOpendirSlot(const QString &url, DiscoveryDirectoryResult *);
+ void doGetSizeSlot(const QString &path, qint64 *result);
// From Job:
void singleDirectoryJobResultSlot(const QList<FileStatPointer> &);
void singleDirectoryJobFinishedWithErrorSlot(int csyncErrnoCode, const QString &msg);
- void singleDirectoryJobFirstDirectoryPermissionsSlot(const QString&);
+ void singleDirectoryJobFirstDirectoryPermissionsSlot(const QString &);
void slotGetSizeFinishedWithError();
- void slotGetSizeResult(const QVariantMap&);
+ void slotGetSizeResult(const QVariantMap &);
signals:
void etag(const QString &);
void etagConcatenation(const QString &);
+
public:
- void setupHooks(DiscoveryJob* discoveryJob, const QString &pathPrefix);
+ void setupHooks(DiscoveryJob *discoveryJob, const QString &pathPrefix);
};
/**
*
* @ingroup libsync
*/
-class DiscoveryJob : public QObject {
+class DiscoveryJob : public QObject
+{
Q_OBJECT
friend class DiscoveryMainThread;
- CSYNC *_csync_ctx;
- csync_log_callback _log_callback;
- int _log_level;
- QElapsedTimer _lastUpdateProgressCallbackCall;
+ CSYNC *_csync_ctx;
+ csync_log_callback _log_callback;
+ int _log_level;
+ QElapsedTimer _lastUpdateProgressCallbackCall;
/**
* return true if the given path should be ignored,
* false if the path should be synced
*/
- bool isInSelectiveSyncBlackList(const char* path) const;
+ bool isInSelectiveSyncBlackList(const char *path) const;
static int isInSelectiveSyncBlackListCallback(void *, const char *);
bool checkSelectiveSyncNewFolder(const QString &path, const char *remotePerm);
- static int checkSelectiveSyncNewFolderCallback(void* data, const char* path, const char* remotePerm);
+ static int checkSelectiveSyncNewFolderCallback(void *data, const char *path, const char *remotePerm);
// Just for progress
- static void update_job_update_callback (bool local,
- const char *dirname,
- void *userdata);
+ static void update_job_update_callback(bool local,
+ const char *dirname,
+ void *userdata);
// For using QNAM to get the directory listings
- static csync_vio_handle_t* remote_vio_opendir_hook (const char *url,
- void *userdata);
- static csync_vio_file_stat_t* remote_vio_readdir_hook (csync_vio_handle_t *dhandle,
- void *userdata);
- static void remote_vio_closedir_hook (csync_vio_handle_t *dhandle,
- void *userdata);
+ static csync_vio_handle_t *remote_vio_opendir_hook(const char *url,
+ void *userdata);
+ static csync_vio_file_stat_t *remote_vio_readdir_hook(csync_vio_handle_t *dhandle,
+ void *userdata);
+ static void remote_vio_closedir_hook(csync_vio_handle_t *dhandle,
+ void *userdata);
QMutex _vioMutex;
QWaitCondition _vioWaitCondition;
public:
- explicit DiscoveryJob(CSYNC *ctx, QObject* parent = 0)
- : QObject(parent), _csync_ctx(ctx) {
+ explicit DiscoveryJob(CSYNC *ctx, QObject *parent = 0)
+ : QObject(parent)
+ , _csync_ctx(ctx)
+ {
// We need to forward the log property as csync uses thread local
// and updates run in another thread
_log_callback = csync_get_log_callback();
void folderDiscovered(bool local, QString folderUrl);
// After the discovery job has been woken up again (_vioWaitCondition)
- void doOpendirSignal(QString url, DiscoveryDirectoryResult*);
+ void doOpendirSignal(QString url, DiscoveryDirectoryResult *);
void doGetSizeSignal(const QString &path, qint64 *result);
// A new folder was discovered and was not synced because of the confirmation feature
void newBigFolder(const QString &folder, bool isExternal);
};
-
}
using namespace OCC;
-ExcludedFiles::ExcludedFiles(c_strlist_t** excludesPtr)
+ExcludedFiles::ExcludedFiles(c_strlist_t **excludesPtr)
: _excludesPtr(excludesPtr)
{
}
c_strlist_destroy(*_excludesPtr);
}
-ExcludedFiles& ExcludedFiles::instance()
+ExcludedFiles &ExcludedFiles::instance()
{
- static c_strlist_t* globalExcludes;
+ static c_strlist_t *globalExcludes;
static ExcludedFiles inst(&globalExcludes);
return inst;
}
-void ExcludedFiles::addExcludeFilePath(const QString& path)
+void ExcludedFiles::addExcludeFilePath(const QString &path)
{
_excludeFiles.insert(path);
}
*_excludesPtr = NULL;
bool success = true;
- foreach (const QString& file, _excludeFiles) {
+ foreach (const QString &file, _excludeFiles) {
if (csync_exclude_load(file.toUtf8(), _excludesPtr) < 0)
success = false;
}
}
bool ExcludedFiles::isExcluded(
- const QString& filePath,
- const QString& basePath,
- bool excludeHidden) const
+ const QString &filePath,
+ const QString &basePath,
+ bool excludeHidden) const
{
if (!filePath.startsWith(basePath, Utility::fsCasePreserving() ? Qt::CaseInsensitive : Qt::CaseSensitive)) {
// Mark paths we're not responsible for as excluded...
return true;
}
- if( excludeHidden ) {
+ if (excludeHidden) {
QString path = filePath;
// Check all path subcomponents, but to *not* check the base path:
// We do want to be able to sync with a hidden folder as the target.
while (path.size() > basePath.size()) {
QFileInfo fi(path);
- if( fi.isHidden() || fi.fileName().startsWith(QLatin1Char('.')) ) {
+ if (fi.isHidden() || fi.fileName().startsWith(QLatin1Char('.'))) {
return true;
}
{
Q_OBJECT
public:
- static ExcludedFiles & instance();
+ static ExcludedFiles &instance();
- ExcludedFiles(c_strlist_t** excludesPtr);
+ ExcludedFiles(c_strlist_t **excludesPtr);
~ExcludedFiles();
/**
*
* Does not load the file. Use reloadExcludes() afterwards.
*/
- void addExcludeFilePath(const QString& path);
+ void addExcludeFilePath(const QString &path);
/**
* Checks whether a file or directory should be excluded.
* @param basePath folder path from which to apply exclude rules
*/
bool isExcluded(
- const QString& filePath,
- const QString& basePath,
- bool excludeHidden) const;
+ const QString &filePath,
+ const QString &basePath,
+ bool excludeHidden) const;
#ifdef WITH_TESTING
void addExcludeExpr(const QString &expr);
private:
// This is a pointer to the csync exclude list, its is owned by this class
// but the pointer can be in a csync_context so that it can itself also query the list.
- c_strlist_t** _excludesPtr;
+ c_strlist_t **_excludesPtr;
QSet<QString> _excludeFiles;
};
// We use some internals of csync:
extern "C" int c_utimes(const char *, const struct timeval *);
-extern "C" void csync_win32_set_file_hidden( const char *file, bool h );
+extern "C" void csync_win32_set_file_hidden(const char *file, bool h);
extern "C" {
#include "csync.h"
Q_LOGGING_CATEGORY(lcFileSystem, "sync.filesystem", QtInfoMsg)
-QString FileSystem::longWinPath( const QString& inpath )
+QString FileSystem::longWinPath(const QString &inpath)
{
QString path(inpath);
#ifdef Q_OS_WIN
- path = QString::fromWCharArray( static_cast<wchar_t*>( c_utf8_path_to_locale(inpath.toUtf8() ) ) );
+ path = QString::fromWCharArray(static_cast<wchar_t *>(c_utf8_path_to_locale(inpath.toUtf8())));
#endif
return path;
}
-bool FileSystem::fileEquals(const QString& fn1, const QString& fn2)
+bool FileSystem::fileEquals(const QString &fn1, const QString &fn2)
{
// compare two files with given filename and return true if they have the same content
QFile f1(fn1);
return false;
}
-void FileSystem::setFileHidden(const QString& filename, bool hidden)
+void FileSystem::setFileHidden(const QString &filename, bool hidden)
{
#ifdef _WIN32
QString fName = longWinPath(filename);
DWORD dwAttrs;
- dwAttrs = GetFileAttributesW( (wchar_t*)fName.utf16() );
+ dwAttrs = GetFileAttributesW((wchar_t *)fName.utf16());
if (dwAttrs != INVALID_FILE_ATTRIBUTES) {
if (hidden && !(dwAttrs & FILE_ATTRIBUTE_HIDDEN)) {
- SetFileAttributesW((wchar_t*)fName.utf16(), dwAttrs | FILE_ATTRIBUTE_HIDDEN );
+ SetFileAttributesW((wchar_t *)fName.utf16(), dwAttrs | FILE_ATTRIBUTE_HIDDEN);
} else if (!hidden && (dwAttrs & FILE_ATTRIBUTE_HIDDEN)) {
- SetFileAttributesW((wchar_t*)fName.utf16(), dwAttrs & ~FILE_ATTRIBUTE_HIDDEN );
+ SetFileAttributesW((wchar_t *)fName.utf16(), dwAttrs & ~FILE_ATTRIBUTE_HIDDEN);
}
}
#else
return result;
}
-void FileSystem::setFileReadOnly(const QString& filename, bool readonly)
+void FileSystem::setFileReadOnly(const QString &filename, bool readonly)
{
QFile file(filename);
QFile::Permissions permissions = file.permissions();
QFile::Permissions allWritePermissions =
- QFile::WriteUser | QFile::WriteGroup | QFile::WriteOther | QFile::WriteOwner;
+ QFile::WriteUser | QFile::WriteGroup | QFile::WriteOther | QFile::WriteOwner;
static QFile::Permissions defaultWritePermissions = getDefaultWritePermissions();
permissions &= ~allWritePermissions;
file.setPermissions(permissions);
}
-void FileSystem::setFolderMinimumPermissions(const QString& filename)
+void FileSystem::setFolderMinimumPermissions(const QString &filename)
{
#ifdef Q_OS_MAC
QFile::Permissions perm = QFile::ReadOwner | QFile::WriteOwner | QFile::ExeOwner;
}
-void FileSystem::setFileReadOnlyWeak(const QString& filename, bool readonly)
+void FileSystem::setFileReadOnlyWeak(const QString &filename, bool readonly)
{
QFile file(filename);
QFile::Permissions permissions = file.permissions();
time_t FileSystem::getModTime(const QString &filename)
{
- csync_vio_file_stat_t* stat = csync_vio_file_stat_new();
+ csync_vio_file_stat_t *stat = csync_vio_file_stat_new();
qint64 result = -1;
if (csync_vio_local_stat(filename.toUtf8().data(), stat) != -1
- && (stat->fields & CSYNC_VIO_FILE_STAT_FIELDS_MTIME)) {
+ && (stat->fields & CSYNC_VIO_FILE_STAT_FIELDS_MTIME)) {
result = stat->mtime;
} else {
qCWarning(lcFileSystem) << "Could not get modification time for" << filename
- << "with csync, using QFileInfo";
+ << "with csync, using QFileInfo";
result = Utility::qDateTimeToTime_t(QFileInfo(filename).lastModified());
}
csync_vio_file_stat_destroy(stat);
return result;
}
-bool FileSystem::setModTime(const QString& filename, time_t modTime)
+bool FileSystem::setModTime(const QString &filename, time_t modTime)
{
struct timeval times[2];
times[0].tv_sec = times[1].tv_sec = modTime;
int rc = c_utimes(filename.toUtf8().data(), times);
if (rc != 0) {
qCWarning(lcFileSystem) << "Error setting mtime for" << filename
- << "failed: rc" << rc << ", errno:" << errno;
+ << "failed: rc" << rc << ", errno:" << errno;
return false;
}
return true;
}
#ifdef Q_OS_WIN
-static bool isLnkFile(const QString& filename)
+static bool isLnkFile(const QString &filename)
{
return filename.endsWith(".lnk");
}
#endif
bool FileSystem::rename(const QString &originFileName,
- const QString &destinationFileName,
- QString *errorString)
+ const QString &destinationFileName,
+ QString *errorString)
{
bool success = false;
QString error;
QString dest = longWinPath(destinationFileName);
if (isLnkFile(originFileName) || isLnkFile(destinationFileName)) {
- success = MoveFileEx((wchar_t*)orig.utf16(),
- (wchar_t*)dest.utf16(),
- MOVEFILE_COPY_ALLOWED | MOVEFILE_WRITE_THROUGH);
+ success = MoveFileEx((wchar_t *)orig.utf16(),
+ (wchar_t *)dest.utf16(),
+ MOVEFILE_COPY_ALLOWED | MOVEFILE_WRITE_THROUGH);
if (!success) {
wchar_t *string = 0;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
- NULL, ::GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
- (LPWSTR)&string, 0, NULL);
+ NULL, ::GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
+ (LPWSTR)&string, 0, NULL);
error = QString::fromWCharArray(string);
LocalFree((HLOCAL)string);
if (!success) {
qCWarning(lcFileSystem) << "Error renaming file" << originFileName
- << "to" << destinationFileName
- << "failed: " << error;
+ << "to" << destinationFileName
+ << "failed: " << error;
if (errorString) {
*errorString = error;
}
return success;
}
-bool FileSystem::fileChanged(const QString& fileName,
- qint64 previousSize,
- time_t previousMtime)
+bool FileSystem::fileChanged(const QString &fileName,
+ qint64 previousSize,
+ time_t previousMtime)
{
return getSize(fileName) != previousSize
|| getModTime(fileName) != previousMtime;
}
-bool FileSystem::verifyFileUnchanged(const QString& fileName,
- qint64 previousSize,
- time_t previousMtime)
+bool FileSystem::verifyFileUnchanged(const QString &fileName,
+ qint64 previousSize,
+ time_t previousMtime)
{
const qint64 actualSize = getSize(fileName);
const time_t actualMtime = getModTime(fileName);
if (actualSize != previousSize || actualMtime != previousMtime) {
qCInfo(lcFileSystem) << "File" << fileName << "has changed:"
- << "size: " << previousSize << "<->" << actualSize
- << ", mtime: " << previousMtime << "<->" << actualMtime;
+ << "size: " << previousSize << "<->" << actualSize
+ << ", mtime: " << previousMtime << "<->" << actualMtime;
return false;
}
return true;
}
-bool FileSystem::renameReplace(const QString& originFileName,
- const QString& destinationFileName,
- qint64 destinationSize,
- time_t destinationMtime,
- QString* errorString)
+bool FileSystem::renameReplace(const QString &originFileName,
+ const QString &destinationFileName,
+ qint64 destinationSize,
+ time_t destinationMtime,
+ QString *errorString)
{
if (fileExists(destinationFileName)
- && fileChanged(destinationFileName, destinationSize, destinationMtime)) {
+ && fileChanged(destinationFileName, destinationSize, destinationMtime)) {
if (errorString) {
*errorString = qApp->translate("FileSystem",
- "The destination file has an unexpected size or modification time");
+ "The destination file has an unexpected size or modification time");
}
return false;
}
return uncheckedRenameReplace(originFileName, destinationFileName, errorString);
}
-bool FileSystem::uncheckedRenameReplace(const QString& originFileName,
- const QString& destinationFileName,
- QString* errorString)
+bool FileSystem::uncheckedRenameReplace(const QString &originFileName,
+ const QString &destinationFileName,
+ QString *errorString)
{
#ifndef Q_OS_WIN
bool success;
// ### FIXME
success = true;
bool destExists = fileExists(destinationFileName);
- if( destExists && !QFile::remove(destinationFileName) ) {
+ if (destExists && !QFile::remove(destinationFileName)) {
*errorString = orig.errorString();
qCWarning(lcFileSystem) << "Target file could not be removed.";
success = false;
}
- if( success ) {
+ if (success) {
success = orig.rename(destinationFileName);
}
#endif
if (!success) {
*errorString = orig.errorString();
- qCWarning(lcFileSystem) << "Renaming temp file to final failed: " << *errorString ;
+ qCWarning(lcFileSystem) << "Renaming temp file to final failed: " << *errorString;
return false;
}
QString orig = longWinPath(originFileName);
QString dest = longWinPath(destinationFileName);
- ok = MoveFileEx((wchar_t*)orig.utf16(),
- (wchar_t*)dest.utf16(),
- MOVEFILE_REPLACE_EXISTING+MOVEFILE_COPY_ALLOWED+MOVEFILE_WRITE_THROUGH);
+ ok = MoveFileEx((wchar_t *)orig.utf16(),
+ (wchar_t *)dest.utf16(),
+ MOVEFILE_REPLACE_EXISTING + MOVEFILE_COPY_ALLOWED + MOVEFILE_WRITE_THROUGH);
if (!ok) {
wchar_t *string = 0;
- FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
- NULL, ::GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
- (LPWSTR)&string, 0, NULL);
+ FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
+ NULL, ::GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
+ (LPWSTR)&string, 0, NULL);
*errorString = QString::fromWCharArray(string);
qCWarning(lcFileSystem) << "Renaming temp file to final failed: " << *errorString;
return true;
}
-bool FileSystem::openAndSeekFileSharedRead(QFile* file, QString* errorOrNull, qint64 seek)
+bool FileSystem::openAndSeekFileSharedRead(QFile *file, QString *errorOrNull, qint64 seek)
{
QString errorDummy;
// avoid many if (errorOrNull) later.
- QString& error = errorOrNull ? *errorOrNull : errorDummy;
+ QString &error = errorOrNull ? *errorOrNull : errorDummy;
error.clear();
#ifdef Q_OS_WIN
QString fName = longWinPath(file->fileName());
HANDLE fileHandle = CreateFileW(
- (const wchar_t*)fName.utf16(),
- accessRights,
- shareMode,
- &securityAtts,
- creationDisp,
- FILE_ATTRIBUTE_NORMAL,
- NULL);
+ (const wchar_t *)fName.utf16(),
+ accessRights,
+ shareMode,
+ &securityAtts,
+ creationDisp,
+ FILE_ATTRIBUTE_NORMAL,
+ NULL);
// Bail out on error.
if (fileHandle == INVALID_HANDLE_VALUE) {
}
// Seek to the right spot
- LARGE_INTEGER *li = reinterpret_cast<LARGE_INTEGER*>(&seek);
+ LARGE_INTEGER *li = reinterpret_cast<LARGE_INTEGER *>(&seek);
DWORD newFilePointer = SetFilePointer(fileHandle, li->LowPart, &li->HighPart, FILE_BEGIN);
if (newFilePointer == 0xFFFFFFFF && GetLastError() != NO_ERROR) {
error = qt_error_string();
}
#ifdef Q_OS_WIN
-static qint64 getSizeWithCsync(const QString& filename)
+static qint64 getSizeWithCsync(const QString &filename)
{
qint64 result = 0;
- csync_vio_file_stat_t* stat = csync_vio_file_stat_new();
+ csync_vio_file_stat_t *stat = csync_vio_file_stat_new();
if (csync_vio_local_stat(filename.toUtf8().data(), stat) != -1
- && (stat->fields & CSYNC_VIO_FILE_STAT_FIELDS_SIZE)) {
+ && (stat->fields & CSYNC_VIO_FILE_STAT_FIELDS_SIZE)) {
result = stat->size;
} else {
qCWarning(lcFileSystem) << "Could not get size for" << filename << "with csync";
}
#endif
-qint64 FileSystem::getSize(const QString& filename)
+qint64 FileSystem::getSize(const QString &filename)
{
#ifdef Q_OS_WIN
if (isLnkFile(filename)) {
}
#ifdef Q_OS_WIN
-static bool fileExistsWin(const QString& filename)
+static bool fileExistsWin(const QString &filename)
{
WIN32_FIND_DATA FindFileData;
HANDLE hFind;
QString fName = FileSystem::longWinPath(filename);
- hFind = FindFirstFileW( (wchar_t*)fName.utf16(), &FindFileData);
+ hFind = FindFirstFileW((wchar_t *)fName.utf16(), &FindFileData);
if (hFind == INVALID_HANDLE_VALUE) {
return false;
}
}
#endif
-bool FileSystem::fileExists(const QString& filename, const QFileInfo& fileInfo)
+bool FileSystem::fileExists(const QString &filename, const QFileInfo &fileInfo)
{
#ifdef Q_OS_WIN
if (isLnkFile(filename)) {
// if the filename is different from the filename in fileInfo, the fileInfo is
// not valid. There needs to be one initialised here. Otherwise the incoming
// fileInfo is re-used.
- if( fileInfo.filePath() != filename ) {
+ if (fileInfo.filePath() != filename) {
QFileInfo myFI(filename);
re = myFI.exists();
}
}
#ifdef Q_OS_WIN
-QString FileSystem::fileSystemForPath(const QString & path)
+QString FileSystem::fileSystemForPath(const QString &path)
{
// See also QStorageInfo (Qt >=5.4) and GetVolumeInformationByHandleW (>= Vista)
QString drive = path.left(2);
- if (! drive.endsWith(":"))
+ if (!drive.endsWith(":"))
return QString();
drive.append('\\');
const size_t fileSystemBufferSize = 4096;
TCHAR fileSystemBuffer[fileSystemBufferSize];
- if (! GetVolumeInformationW(
+ if (!GetVolumeInformationW(
reinterpret_cast<LPCWSTR>(drive.utf16()),
NULL, 0,
NULL, NULL, NULL,
}
#endif
-#define BUFSIZE qint64(500*1024) // 500 KiB
+#define BUFSIZE qint64(500 * 1024) // 500 KiB
-static QByteArray readToCrypto( const QString& filename, QCryptographicHash::Algorithm algo )
+static QByteArray readToCrypto(const QString &filename, QCryptographicHash::Algorithm algo)
{
QFile file(filename);
const qint64 bufSize = qMin(BUFSIZE, file.size() + 1);
QByteArray buf(bufSize, Qt::Uninitialized);
QByteArray arr;
- QCryptographicHash crypto( algo );
+ QCryptographicHash crypto(algo);
if (file.open(QIODevice::ReadOnly)) {
qint64 size;
while (!file.atEnd()) {
- size = file.read( buf.data(), bufSize );
- if( size > 0 ) {
+ size = file.read(buf.data(), bufSize);
+ if (size > 0) {
crypto.addData(buf.data(), size);
}
}
return arr;
}
-QByteArray FileSystem::calcMd5( const QString& filename )
+QByteArray FileSystem::calcMd5(const QString &filename)
{
- return readToCrypto( filename, QCryptographicHash::Md5 );
+ return readToCrypto(filename, QCryptographicHash::Md5);
}
-QByteArray FileSystem::calcSha1( const QString& filename )
+QByteArray FileSystem::calcSha1(const QString &filename)
{
- return readToCrypto( filename, QCryptographicHash::Sha1 );
+ return readToCrypto(filename, QCryptographicHash::Sha1);
}
#ifdef ZLIB_FOUND
-QByteArray FileSystem::calcAdler32( const QString& filename )
+QByteArray FileSystem::calcAdler32(const QString &filename)
{
QFile file(filename);
const qint64 bufSize = qMin(BUFSIZE, file.size() + 1);
qint64 size;
while (!file.atEnd()) {
size = file.read(buf.data(), bufSize);
- if( size > 0 )
- adler = adler32(adler, (const Bytef*) buf.data(), size);
+ if (size > 0)
+ adler = adler32(adler, (const Bytef *)buf.data(), size);
}
}
- return QByteArray::number( adler, 16 );
+ return QByteArray::number(adler, 16);
}
#endif
if (conflictFileUserName.isEmpty())
conflictFileName.insert(dotLocation, "_conflict-" + timeString);
else
- conflictFileName.insert(dotLocation, "_conflict_" + QString::fromUtf8(conflictFileUserName) + "-" + timeString);
+ conflictFileName.insert(dotLocation, "_conflict_" + QString::fromUtf8(conflictFileUserName) + "-" + timeString);
return conflictFileName;
}
return true;
}
-bool FileSystem::isFileLocked(const QString& fileName)
+bool FileSystem::isFileLocked(const QString &fileName)
{
#ifdef Q_OS_WIN
mbchar_t *wuri = c_utf8_path_to_locale(fileName.toUtf8());
if (attr != INVALID_FILE_ATTRIBUTES) {
// Try to open the file with as much access as possible..
HANDLE win_h = CreateFileW(
- wuri,
- GENERIC_READ | GENERIC_WRITE,
- FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
- NULL, OPEN_EXISTING,
- FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS,
- NULL);
+ wuri,
+ GENERIC_READ | GENERIC_WRITE,
+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
+ NULL, OPEN_EXISTING,
+ FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS,
+ NULL);
c_free_locale_string(wuri);
if (win_h == INVALID_HANDLE_VALUE) {
*/
namespace FileSystem {
-/**
+ /**
* @brief compare two files with given filename and return true if they have the same content
*/
-bool fileEquals(const QString &fn1, const QString &fn2);
+ bool fileEquals(const QString &fn1, const QString &fn2);
-/**
+ /**
* @brief Mark the file as hidden (only has effects on windows)
*/
-void OWNCLOUDSYNC_EXPORT setFileHidden(const QString& filename, bool hidden);
+ void OWNCLOUDSYNC_EXPORT setFileHidden(const QString &filename, bool hidden);
-/**
+ /**
* @brief Marks the file as read-only.
*
* On linux this either revokes all 'w' permissions or restores permissions
* according to the umask.
*/
-void OWNCLOUDSYNC_EXPORT setFileReadOnly(const QString& filename, bool readonly);
+ void OWNCLOUDSYNC_EXPORT setFileReadOnly(const QString &filename, bool readonly);
-/**
+ /**
* @brief Marks the file as read-only.
*
* It's like setFileReadOnly(), but weaker: if readonly is false and the user
* This means that it will preserve explicitly set rw-r--r-- permissions even
* when the umask is 0002. (setFileReadOnly() would adjust to rw-rw-r--)
*/
-void OWNCLOUDSYNC_EXPORT setFileReadOnlyWeak(const QString& filename, bool readonly);
+ void OWNCLOUDSYNC_EXPORT setFileReadOnlyWeak(const QString &filename, bool readonly);
-/**
+ /**
* @brief Try to set permissions so that other users on the local machine can not
* go into the folder.
*/
-void OWNCLOUDSYNC_EXPORT setFolderMinimumPermissions(const QString& filename);
+ void OWNCLOUDSYNC_EXPORT setFolderMinimumPermissions(const QString &filename);
-/** convert a "normal" windows path into a path that can be 32k chars long. */
-QString OWNCLOUDSYNC_EXPORT longWinPath( const QString& inpath );
+ /** convert a "normal" windows path into a path that can be 32k chars long. */
+ QString OWNCLOUDSYNC_EXPORT longWinPath(const QString &inpath);
-/**
+ /**
* @brief Get the mtime for a filepath
*
* Use this over QFileInfo::lastModified() to avoid timezone related bugs. See
* owncloud/core#9781 for details.
*/
-time_t OWNCLOUDSYNC_EXPORT getModTime(const QString& filename);
+ time_t OWNCLOUDSYNC_EXPORT getModTime(const QString &filename);
-bool OWNCLOUDSYNC_EXPORT setModTime(const QString &filename, time_t modTime);
+ bool OWNCLOUDSYNC_EXPORT setModTime(const QString &filename, time_t modTime);
-/**
+ /**
* @brief Get the size for a file
*
* Use this over QFileInfo::size() to avoid bugs with lnk files on Windows.
* See https://bugreports.qt.io/browse/QTBUG-24831.
*/
-qint64 OWNCLOUDSYNC_EXPORT getSize(const QString& filename);
+ qint64 OWNCLOUDSYNC_EXPORT getSize(const QString &filename);
-/**
+ /**
* @brief Checks whether a file exists.
*
* Use this over QFileInfo::exists() and QFile::exists() to avoid bugs with lnk
* files, see above.
*/
-bool OWNCLOUDSYNC_EXPORT fileExists(const QString& filename, const QFileInfo& = QFileInfo() );
+ bool OWNCLOUDSYNC_EXPORT fileExists(const QString &filename, const QFileInfo & = QFileInfo());
-/**
+ /**
* @brief Rename the file \a originFileName to \a destinationFileName.
*
* It behaves as QFile::rename() but handles .lnk files correctly on Windows.
*/
-bool OWNCLOUDSYNC_EXPORT rename(const QString& originFileName,
- const QString& destinationFileName,
- QString* errorString = NULL);
+ bool OWNCLOUDSYNC_EXPORT rename(const QString &originFileName,
+ const QString &destinationFileName,
+ QString *errorString = NULL);
-/**
+ /**
* @brief Check if \a fileName has changed given previous size and mtime
*
* Nonexisting files are covered through mtime: they have an mtime of -1.
*
* @return true if the file's mtime or size are not what is expected.
*/
-bool OWNCLOUDSYNC_EXPORT fileChanged(const QString& fileName,
- qint64 previousSize,
- time_t previousMtime);
+ bool OWNCLOUDSYNC_EXPORT fileChanged(const QString &fileName,
+ qint64 previousSize,
+ time_t previousMtime);
-/**
+ /**
* @brief Like !fileChanged() but with verbose logging if the file *did* change.
*/
-bool verifyFileUnchanged(const QString& fileName,
- qint64 previousSize,
- time_t previousMtime);
+ bool verifyFileUnchanged(const QString &fileName,
+ qint64 previousSize,
+ time_t previousMtime);
-/**
+ /**
* @brief renames a file, overriding the target if it exists
*
* Rename the file \a originFileName to \a destinationFileName, and
* If the destination file does not exist, the given size and mtime are
* ignored.
*/
-bool renameReplace(const QString &originFileName,
- const QString &destinationFileName,
- qint64 destinationSize,
- time_t destinationMtime,
- QString *errorString);
+ bool renameReplace(const QString &originFileName,
+ const QString &destinationFileName,
+ qint64 destinationSize,
+ time_t destinationMtime,
+ QString *errorString);
-/**
+ /**
* Rename the file \a originFileName to \a destinationFileName, and
* overwrite the destination if it already exists - without extra checks.
*/
-bool uncheckedRenameReplace(const QString &originFileName,
- const QString &destinationFileName,
- QString *errorString);
+ bool uncheckedRenameReplace(const QString &originFileName,
+ const QString &destinationFileName,
+ QString *errorString);
-/**
+ /**
* Removes a file.
*
* Equivalent to QFile::remove(), except on Windows, where it will also
* successfully remove read-only files.
*/
-bool OWNCLOUDSYNC_EXPORT remove(const QString &fileName, QString *errorString = 0);
+ bool OWNCLOUDSYNC_EXPORT remove(const QString &fileName, QString *errorString = 0);
-/**
+ /**
* Replacement for QFile::open(ReadOnly) followed by a seek().
* This version sets a more permissive sharing mode on Windows.
*
* Warning: The resulting file may have an empty fileName and be unsuitable for use
* with QFileInfo! Calling seek() on the QFile with >32bit signed values will fail!
*/
-bool openAndSeekFileSharedRead(QFile* file, QString* error, qint64 seek);
+ bool openAndSeekFileSharedRead(QFile *file, QString *error, qint64 seek);
#ifdef Q_OS_WIN
-/**
+ /**
* Returns the file system used at the given path.
*/
-QString fileSystemForPath(const QString & path);
+ QString fileSystemForPath(const QString &path);
#endif
-QByteArray OWNCLOUDSYNC_EXPORT calcMd5( const QString& fileName );
-QByteArray OWNCLOUDSYNC_EXPORT calcSha1( const QString& fileName );
+ QByteArray OWNCLOUDSYNC_EXPORT calcMd5(const QString &fileName);
+ QByteArray OWNCLOUDSYNC_EXPORT calcSha1(const QString &fileName);
#ifdef ZLIB_FOUND
-QByteArray OWNCLOUDSYNC_EXPORT calcAdler32( const QString& fileName );
+ QByteArray OWNCLOUDSYNC_EXPORT calcAdler32(const QString &fileName);
#endif
-/**
+ /**
* Returns a file name based on \a fn that's suitable for a conflict.
*/
-QString OWNCLOUDSYNC_EXPORT makeConflictFileName(const QString &fn, const QDateTime &dt);
+ QString OWNCLOUDSYNC_EXPORT makeConflictFileName(const QString &fn, const QDateTime &dt);
-/**
+ /**
* Returns true when a file is locked. (Windows only)
*/
-bool OWNCLOUDSYNC_EXPORT isFileLocked(const QString& fileName);
-
+ bool OWNCLOUDSYNC_EXPORT isFileLocked(const QString &fileName);
}
/** @} */
-
}
// logging handler.
static void mirallLogCatcher(QtMsgType type, const char *msg)
{
- Q_UNUSED(type)
- // qDebug() exports to local8Bit, which is not always UTF-8
- Logger::instance()->mirallLog( QString::fromLocal8Bit(msg) );
+ Q_UNUSED(type)
+ // qDebug() exports to local8Bit, which is not always UTF-8
+ Logger::instance()->mirallLog(QString::fromLocal8Bit(msg));
}
-static void qInstallMessageHandler(QtMsgHandler h) {
+static void qInstallMessageHandler(QtMsgHandler h)
+{
qInstallMsgHandler(h);
}
#elif QT_VERSION < QT_VERSION_CHECK(5, 4, 0)
-static void mirallLogCatcher(QtMsgType, const QMessageLogContext &ctx, const QString &message) {
+static void mirallLogCatcher(QtMsgType, const QMessageLogContext &ctx, const QString &message)
+{
QByteArray file = ctx.file;
file = file.mid(file.lastIndexOf('/') + 1);
- Logger::instance()->mirallLog( QString::fromLocal8Bit(file) + QLatin1Char(':') + QString::number(ctx.line)
- + QLatin1Char(' ') + message) ;
+ Logger::instance()->mirallLog(QString::fromLocal8Bit(file) + QLatin1Char(':') + QString::number(ctx.line)
+ + QLatin1Char(' ') + message);
}
#else
-static void mirallLogCatcher(QtMsgType type, const QMessageLogContext &ctx, const QString &message) {
+static void mirallLogCatcher(QtMsgType type, const QMessageLogContext &ctx, const QString &message)
+{
auto logger = Logger::instance();
if (!logger->isNoop()) {
- logger->doLog( qFormatLogMessage(type, ctx, message) ) ;
+ logger->doLog(qFormatLogMessage(type, ctx, message));
}
}
#endif
static void csyncLogCatcher(int verbosity,
- const char *function,
- const char *buffer)
+ const char *function,
+ const char *buffer)
{
if (verbosity <= CSYNC_LOG_PRIORITY_FATAL) {
QMessageLogger(0, 0, function, lcCsync().categoryName()).fatal("%s", buffer);
return &log;
}
-Logger::Logger( QObject* parent) : QObject(parent),
- _showTime(true), _logWindowActivated(false), _doFileFlush(false), _logExpire(0), _logDebug(false)
+Logger::Logger(QObject *parent)
+ : QObject(parent)
+ , _showTime(true)
+ , _logWindowActivated(false)
+ , _doFileFlush(false)
+ , _logExpire(0)
+ , _logDebug(false)
{
#if QT_VERSION >= QT_VERSION_CHECK(5, 4, 0)
qSetMessagePattern("%{time MM-dd hh:mm:ss:zzz} [ %{type} %{category} ]%{if-debug}\t[ %{function} ]%{endif}:\t%{message}");
csync_set_log_callback(csyncLogCatcher);
}
-Logger::~Logger() {
+Logger::~Logger()
+{
#ifndef NO_MSG_HANDLER
qInstallMessageHandler(0);
#endif
void Logger::log(Log log)
{
QString msg;
- if( _showTime ) {
+ if (_showTime) {
msg = log.timeStamp.toString(QLatin1String("MM-dd hh:mm:ss:zzz")) + QLatin1Char(' ');
}
- if( log.source == Log::CSync ) {
+ if (log.source == Log::CSync) {
// msg += "csync - ";
} else {
// msg += "ownCloud - ";
}
- msg += QString().sprintf("%p ", (void*)QThread::currentThread());
+ msg += QString().sprintf("%p ", (void *)QThread::currentThread());
msg += log.message;
// _logs.append(log);
// std::cout << qPrintable(log.message) << std::endl;
}
-void Logger::doLog(const QString& msg)
+void Logger::doLog(const QString &msg)
{
{
QMutexLocker lock(&_mutex);
- if( _logstream ) {
+ if (_logstream) {
(*_logstream) << msg << endl;
- if( _doFileFlush ) _logstream->flush();
+ if (_doFileFlush)
+ _logstream->flush();
}
}
emit logWindowLog(msg);
}
-void Logger::mirallLog( const QString& message )
+void Logger::mirallLog(const QString &message)
{
Log log_;
log_.source = Log::Occ;
log_.timeStamp = QDateTime::currentDateTime();
log_.message = message;
- Logger::instance()->log( log_ );
+ Logger::instance()->log(log_);
}
void Logger::setLogWindowActivated(bool activated)
_logWindowActivated = activated;
}
-void Logger::setLogFile(const QString & name)
+void Logger::setLogFile(const QString &name)
{
QMutexLocker locker(&_mutex);
csync_set_log_level(11);
-
- if( _logstream ) {
+
+ if (_logstream) {
_logstream.reset(0);
_logFile.close();
}
- if( name.isEmpty() ) {
+ if (name.isEmpty()) {
return;
}
if (name == QLatin1String("-")) {
openSucceeded = _logFile.open(1, QIODevice::WriteOnly);
} else {
- _logFile.setFileName( name );
+ _logFile.setFileName(name);
openSucceeded = _logFile.open(QIODevice::WriteOnly);
}
- if(!openSucceeded) {
+ if (!openSucceeded) {
locker.unlock(); // Just in case postGuiMessage has a qDebug()
- postGuiMessage( tr("Error"),
- QString(tr("<nobr>File '%1'<br/>cannot be opened for writing.<br/><br/>"
- "The log output can <b>not</b> be saved!</nobr>"))
- .arg(name));
+ postGuiMessage(tr("Error"),
+ QString(tr("<nobr>File '%1'<br/>cannot be opened for writing.<br/><br/>"
+ "The log output can <b>not</b> be saved!</nobr>"))
+ .arg(name));
return;
}
- _logstream.reset(new QTextStream( &_logFile ));
+ _logstream.reset(new QTextStream(&_logFile));
}
-void Logger::setLogExpire( int expire )
+void Logger::setLogExpire(int expire)
{
_logExpire = expire;
}
-void Logger::setLogDir( const QString& dir )
+void Logger::setLogDir(const QString &dir)
{
_logDirectory = dir;
}
-void Logger::setLogFlush( bool flush )
+void Logger::setLogFlush(bool flush)
{
_doFileFlush = flush;
}
-void Logger::setLogDebug( bool debug )
+void Logger::setLogDebug(bool debug)
{
QLoggingCategory::setFilterRules(debug ? QStringLiteral("qt.*=true\n*.debug=true") : QString());
_logDebug = debug;
// Find out what is the file with the highest number if any
QStringList files = dir.entryList(QStringList("owncloud.log.*"),
- QDir::Files);
+ QDir::Files);
QRegExp rx("owncloud.log.(\\d+)");
uint maxNumber = 0;
QDateTime now = QDateTime::currentDateTime();
- foreach(const QString &s, files) {
+ foreach (const QString &s, files) {
if (rx.exactMatch(s)) {
maxNumber = qMax(maxNumber, rx.cap(1).toUInt());
if (_logExpire > 0) {
QFileInfo fileInfo = dir.absoluteFilePath(s);
- if (fileInfo.lastModified().addSecs(60*60 * _logExpire) < now) {
+ if (fileInfo.lastModified().addSecs(60 * 60 * _logExpire) < now) {
dir.remove(s);
}
}
}
}
- QString filename = _logDirectory + "/owncloud.log." + QString::number(maxNumber+1);
+ QString filename = _logDirectory + "/owncloud.log." + QString::number(maxNumber + 1);
setLogFile(filename);
}
}
namespace OCC {
-struct Log{
- typedef enum{
- Occ,
- CSync
- } Source;
-
- QDateTime timeStamp;
- Source source;
- QString message;
+struct Log
+{
+ typedef enum {
+ Occ,
+ CSync
+ } Source;
+
+ QDateTime timeStamp;
+ Source source;
+ QString message;
};
/**
*/
class OWNCLOUDSYNC_EXPORT Logger : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
+ bool isNoop() const;
+ void log(Log log);
+ void doLog(const QString &log);
- bool isNoop() const;
- void log(Log log);
- void doLog(const QString &log);
-
- static void mirallLog( const QString& message );
+ static void mirallLog(const QString &message);
- const QList<Log>& logs() const {return _logs;}
+ const QList<Log> &logs() const { return _logs; }
- static Logger* instance();
+ static Logger *instance();
- void postGuiLog(const QString& title, const QString& message);
- void postOptionalGuiLog(const QString& title, const QString& message);
- void postGuiMessage(const QString& title, const QString& message);
+ void postGuiLog(const QString &title, const QString &message);
+ void postOptionalGuiLog(const QString &title, const QString &message);
+ void postGuiMessage(const QString &title, const QString &message);
- void setLogWindowActivated(bool activated);
- void setLogFile( const QString & name );
- void setLogExpire( int expire );
- void setLogDir( const QString& dir );
- void setLogFlush( bool flush );
+ void setLogWindowActivated(bool activated);
+ void setLogFile(const QString &name);
+ void setLogExpire(int expire);
+ void setLogDir(const QString &dir);
+ void setLogFlush(bool flush);
- bool logDebug() const { return _logDebug; }
- void setLogDebug( bool debug );
+ bool logDebug() const { return _logDebug; }
+ void setLogDebug(bool debug);
signals:
- void logWindowLog(const QString&);
+ void logWindowLog(const QString &);
- void guiLog(const QString&, const QString&);
- void guiMessage(const QString&, const QString&);
- void optionalGuiLog(const QString&, const QString&);
+ void guiLog(const QString &, const QString &);
+ void guiMessage(const QString &, const QString &);
+ void optionalGuiLog(const QString &, const QString &);
public slots:
- void enterNextLogFile();
+ void enterNextLogFile();
private:
- Logger(QObject* parent=0);
- ~Logger();
- QList<Log> _logs;
- bool _showTime;
- bool _logWindowActivated;
- QFile _logFile;
- bool _doFileFlush;
- int _logExpire;
- bool _logDebug;
- QScopedPointer<QTextStream> _logstream;
- QMutex _mutex;
- QString _logDirectory;
-
+ Logger(QObject *parent = 0);
+ ~Logger();
+ QList<Log> _logs;
+ bool _showTime;
+ bool _logWindowActivated;
+ QFile _logFile;
+ bool _doFileFlush;
+ int _logExpire;
+ bool _logDebug;
+ QScopedPointer<QTextStream> _logstream;
+ QMutex _mutex;
+ QString _logDirectory;
};
} // namespace OCC
// assumes ownership
sendRequest("PROPFIND", makeDavUrl(path()), req, buf);
- if( reply()->error() != QNetworkReply::NoError ) {
+ if (reply()->error() != QNetworkReply::NoError) {
qCWarning(lcEtagJob) << "request network error: " << reply()->errorString();
}
AbstractNetworkJob::start();
bool RequestEtagJob::finished()
{
qCInfo(lcEtagJob) << "Request Etag of" << reply()->request().url() << "FINISHED WITH STATUS"
- << reply()->error()
- << (reply()->error() == QNetworkReply::NoError ? QLatin1String("") : errorString());
+ << reply()->error()
+ << (reply()->error() == QNetworkReply::NoError ? QLatin1String("") : errorString());
if (reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute) == 207) {
// Parse DAV response
QString etag;
while (!reader.atEnd()) {
QXmlStreamReader::TokenType type = reader.readNext();
- if (type == QXmlStreamReader::StartElement &&
- reader.namespaceUri() == QLatin1String("DAV:")) {
+ if (type == QXmlStreamReader::StartElement && reader.namespaceUri() == QLatin1String("DAV:")) {
QString name = reader.name().toString();
if (name == QLatin1String("getetag")) {
etag += reader.readElementText();
}
MkColJob::MkColJob(AccountPtr account, const QUrl &url,
- const QMap<QByteArray, QByteArray> &extraHeaders, QObject *parent)
- : AbstractNetworkJob(account, QString(), parent), _url(url), _extraHeaders(extraHeaders)
+ const QMap<QByteArray, QByteArray> &extraHeaders, QObject *parent)
+ : AbstractNetworkJob(account, QString(), parent)
+ , _url(url)
+ , _extraHeaders(extraHeaders)
{
}
void MkColJob::start()
{
- // add 'Content-Length: 0' header (see https://github.com/owncloud/client/issues/3256)
- QNetworkRequest req;
- req.setRawHeader("Content-Length", "0");
- for(auto it = _extraHeaders.constBegin(); it != _extraHeaders.constEnd(); ++it) {
+ // add 'Content-Length: 0' header (see https://github.com/owncloud/client/issues/3256)
+ QNetworkRequest req;
+ req.setRawHeader("Content-Length", "0");
+ for (auto it = _extraHeaders.constBegin(); it != _extraHeaders.constEnd(); ++it) {
req.setRawHeader(it.key(), it.value());
- }
+ }
- // assumes ownership
- if (_url.isValid()) {
- sendRequest("MKCOL", _url, req);
- } else {
- sendRequest("MKCOL", makeDavUrl(path()), req);
- }
- AbstractNetworkJob::start();
+ // assumes ownership
+ if (_url.isValid()) {
+ sendRequest("MKCOL", _url, req);
+ } else {
+ sendRequest("MKCOL", makeDavUrl(path()), req);
+ }
+ AbstractNetworkJob::start();
}
bool MkColJob::finished()
{
qCInfo(lcMkColJob) << "MKCOL of" << reply()->request().url() << "FINISHED WITH STATUS"
- << reply()->error()
- << (reply()->error() == QNetworkReply::NoError ? QLatin1String("") : errorString());
+ << reply()->error()
+ << (reply()->error() == QNetworkReply::NoError ? QLatin1String("") : errorString());
emit finished(reply()->error());
return true;
/*********************************************************************************************/
// supposed to read <D:collection> when pointing to <D:resourcetype><D:collection></D:resourcetype>..
-static QString readContentsAsString(QXmlStreamReader &reader) {
+static QString readContentsAsString(QXmlStreamReader &reader)
+{
QString result;
int level = 0;
do {
LsColXMLParser::LsColXMLParser()
{
-
}
-bool LsColXMLParser::parse( const QByteArray& xml, QHash<QString, qint64> *sizes, const QString& expectedPath)
+bool LsColXMLParser::parse(const QByteArray &xml, QHash<QString, qint64> *sizes, const QString &expectedPath)
{
// Parse DAV response
QXmlStreamReader reader(xml);
} else if (reader.name() == "propstat") {
insidePropstat = false;
if (currentPropsHaveHttp200) {
- currentHttp200Properties = QMap<QString,QString>(currentTmpProperties);
+ currentHttp200Properties = QMap<QString, QString>(currentTmpProperties);
}
currentTmpProperties.clear();
currentPropsHaveHttp200 = false;
emit finishedWithoutError();
}
return true;
-
}
/*********************************************************************************************/
}
LsColJob::LsColJob(AccountPtr account, const QUrl &url, QObject *parent)
- : AbstractNetworkJob(account, QString(), parent), _url(url)
+ : AbstractNetworkJob(account, QString(), parent)
+ , _url(url)
{
}
int colIdx = prop.lastIndexOf(":");
auto ns = prop.left(colIdx);
if (ns == "http://owncloud.org/ns") {
- propStr += " <oc:" + prop.mid(colIdx+1) + " />\n";
+ propStr += " <oc:" + prop.mid(colIdx + 1) + " />\n";
} else {
- propStr += " <" + prop.mid(colIdx+1) + " xmlns=\"" + ns + "\" />\n";
+ propStr += " <" + prop.mid(colIdx + 1) + " xmlns=\"" + ns + "\" />\n";
}
} else {
propStr += " <d:" + prop + " />\n";
QByteArray xml("<?xml version=\"1.0\" ?>\n"
"<d:propfind xmlns:d=\"DAV:\" xmlns:oc=\"http://owncloud.org/ns\">\n"
" <d:prop>\n"
- + propStr +
- " </d:prop>\n"
- "</d:propfind>\n");
+ + propStr + " </d:prop>\n"
+ "</d:propfind>\n");
QBuffer *buf = new QBuffer(this);
buf->setData(xml);
buf->open(QIODevice::ReadOnly);
bool LsColJob::finished()
{
qCInfo(lcLsColJob) << "LSCOL of" << reply()->request().url() << "FINISHED WITH STATUS"
- << reply()->error()
- << (reply()->error() == QNetworkReply::NoError ? QLatin1String("") : errorString());
+ << reply()->error()
+ << (reply()->error() == QNetworkReply::NoError ? QLatin1String("") : errorString());
QString contentType = reply()->header(QNetworkRequest::ContentTypeHeader).toString();
int httpCode = reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
if (httpCode == 207 && contentType.contains("application/xml; charset=utf-8")) {
LsColXMLParser parser;
- connect( &parser, SIGNAL(directoryListingSubfolders(const QStringList&)),
- this, SIGNAL(directoryListingSubfolders(const QStringList&)) );
- connect( &parser, SIGNAL(directoryListingIterated(const QString&, const QMap<QString,QString>&)),
- this, SIGNAL(directoryListingIterated(const QString&, const QMap<QString,QString>&)) );
- connect( &parser, SIGNAL(finishedWithError(QNetworkReply *)),
- this, SIGNAL(finishedWithError(QNetworkReply *)) );
- connect( &parser, SIGNAL(finishedWithoutError()),
- this, SIGNAL(finishedWithoutError()) );
+ connect(&parser, SIGNAL(directoryListingSubfolders(const QStringList &)),
+ this, SIGNAL(directoryListingSubfolders(const QStringList &)));
+ connect(&parser, SIGNAL(directoryListingIterated(const QString &, const QMap<QString, QString> &)),
+ this, SIGNAL(directoryListingIterated(const QString &, const QMap<QString, QString> &)));
+ connect(&parser, SIGNAL(finishedWithError(QNetworkReply *)),
+ this, SIGNAL(finishedWithError(QNetworkReply *)));
+ connect(&parser, SIGNAL(finishedWithoutError()),
+ this, SIGNAL(finishedWithoutError()));
QString expectedPath = reply()->request().url().path(); // something like "/owncloud/remote.php/webdav/folder"
- if( !parser.parse( reply()->readAll(), &_sizes, expectedPath ) ) {
+ if (!parser.parse(reply()->readAll(), &_sizes, expectedPath)) {
// XML parse error
emit finishedWithError(reply());
}
/*********************************************************************************************/
namespace {
-const char statusphpC[] = "status.php";
-const char owncloudDirC[] = "owncloud/";
+ const char statusphpC[] = "status.php";
+ const char owncloudDirC[] = "owncloud/";
}
CheckServerJob::CheckServerJob(AccountPtr account, QObject *parent)
- : AbstractNetworkJob(account, QLatin1String(statusphpC) , parent)
+ : AbstractNetworkJob(account, QLatin1String(statusphpC), parent)
, _subdirFallback(false)
{
setIgnoreCredentialFailure(true);
{
#if QT_VERSION > QT_VERSION_CHECK(5, 2, 0)
if (reply()->request().url().scheme() == QLatin1String("https")
- && reply()->sslConfiguration().sessionTicket().isEmpty()
- && reply()->error() == QNetworkReply::NoError) {
+ && reply()->sslConfiguration().sessionTicket().isEmpty()
+ && reply()->error() == QNetworkReply::NoError) {
qCWarning(lcCheckServerJob) << "No SSL session identifier / session ticket is used, this might impact sync performance negatively.";
}
#endif
// at the original location
if ((reply()->error() == QNetworkReply::ContentNotFoundError) && (!_subdirFallback)) {
_subdirFallback = true;
- setPath(QLatin1String(owncloudDirC)+QLatin1String(statusphpC));
+ setPath(QLatin1String(owncloudDirC) + QLatin1String(statusphpC));
start();
qCInfo(lcCheckServerJob) << "Retrying with" << reply()->url();
return false;
}
- QByteArray body = reply()->peek(4*1024);
+ QByteArray body = reply()->peek(4 * 1024);
int httpStatus = reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
- if( body.isEmpty() || httpStatus != 200) {
+ if (body.isEmpty() || httpStatus != 200) {
qCWarning(lcCheckServerJob) << "error: status.php replied " << httpStatus << body;
emit instanceNotFound(reply());
} else {
}
qCInfo(lcCheckServerJob) << "status.php returns: " << status << " " << reply()->error() << " Reply: " << reply();
- if( status.object().contains("installed") ) {
+ if (status.object().contains("installed")) {
emit instanceFound(reply()->url(), status.object());
} else {
qCWarning(lcCheckServerJob) << "No proper answer on " << reply()->url();
PropfindJob::PropfindJob(AccountPtr account, const QString &path, QObject *parent)
: AbstractNetworkJob(account, path, parent)
{
-
}
void PropfindJob::start()
foreach (const QByteArray &prop, properties) {
if (prop.contains(':')) {
int colIdx = prop.lastIndexOf(":");
- propStr += " <" + prop.mid(colIdx+1) + " xmlns=\"" + prop.left(colIdx) + "\" />\n";
+ propStr += " <" + prop.mid(colIdx + 1) + " xmlns=\"" + prop.left(colIdx) + "\" />\n";
} else {
propStr += " <d:" + prop + " />\n";
}
QByteArray xml = "<?xml version=\"1.0\" ?>\n"
"<d:propfind xmlns:d=\"DAV:\">\n"
" <d:prop>\n"
- + propStr +
- " </d:prop>\n"
- "</d:propfind>\n";
+ + propStr + " </d:prop>\n"
+ "</d:propfind>\n";
QBuffer *buf = new QBuffer(this);
buf->setData(xml);
bool PropfindJob::finished()
{
qCInfo(lcPropfindJob) << "PROPFIND of" << reply()->request().url() << "FINISHED WITH STATUS"
- << reply()->error()
- << (reply()->error() == QNetworkReply::NoError ? QLatin1String("") : errorString());
+ << reply()->error()
+ << (reply()->error() == QNetworkReply::NoError ? QLatin1String("") : errorString());
int http_result_code = reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
}
}
if (type == QXmlStreamReader::EndElement) {
- if(curElement.top() == reader.name()) {
+ if (curElement.top() == reader.name()) {
curElement.pop();
}
}
}
} else {
qCWarning(lcPropfindJob) << "*not* successful, http result code is" << http_result_code
- << (http_result_code == 302 ? reply()->header(QNetworkRequest::LocationHeader).toString() : QLatin1String(""));
+ << (http_result_code == 302 ? reply()->header(QNetworkRequest::LocationHeader).toString() : QLatin1String(""));
emit finishedWithError(reply());
}
return true;
QImage avImage;
if (http_result_code == 200) {
-
QByteArray pngData = reply()->readAll();
- if( pngData.size() ) {
-
- if( avImage.loadFromData(pngData) ) {
+ if (pngData.size()) {
+ if (avImage.loadFromData(pngData)) {
qCDebug(lcAvatarJob) << "Retrieved Avatar pixmap!";
}
}
ProppatchJob::ProppatchJob(AccountPtr account, const QString &path, QObject *parent)
: AbstractNetworkJob(account, path, parent)
{
-
}
void ProppatchJob::start()
if (keyName.contains(':')) {
int colIdx = keyName.lastIndexOf(":");
keyNs = keyName.left(colIdx);
- keyName = keyName.mid(colIdx+1);
+ keyName = keyName.mid(colIdx + 1);
}
propStr += " <" + keyName;
QByteArray xml = "<?xml version=\"1.0\" ?>\n"
"<d:propertyupdate xmlns:d=\"DAV:\">\n"
" <d:set><d:prop>\n"
- + propStr +
- " </d:prop></d:set>\n"
- "</d:propertyupdate>\n";
+ + propStr + " </d:prop></d:set>\n"
+ "</d:propertyupdate>\n";
QBuffer *buf = new QBuffer(this);
buf->setData(xml);
bool ProppatchJob::finished()
{
qCInfo(lcProppatchJob) << "PROPPATCH of" << reply()->request().url() << "FINISHED WITH STATUS"
- << reply()->error()
- << (reply()->error() == QNetworkReply::NoError ? QLatin1String("") : errorString());
+ << reply()->error()
+ << (reply()->error() == QNetworkReply::NoError ? QLatin1String("") : errorString());
int http_result_code = reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
emit success();
} else {
qCWarning(lcProppatchJob) << "*not* successful, http result code is" << http_result_code
- << (http_result_code == 302 ? reply()->header(QNetworkRequest::LocationHeader).toString() : QLatin1String(""));
+ << (http_result_code == 302 ? reply()->header(QNetworkRequest::LocationHeader).toString() : QLatin1String(""));
emit finishedWithError();
}
return true;
/*********************************************************************************************/
-JsonApiJob::JsonApiJob(const AccountPtr &account, const QString& path, QObject* parent): AbstractNetworkJob(account, path, parent)
-{ }
+JsonApiJob::JsonApiJob(const AccountPtr &account, const QString &path, QObject *parent)
+ : AbstractNetworkJob(account, path, parent)
+{
+}
-void JsonApiJob::addQueryParams(QList< QPair<QString,QString> > params)
+void JsonApiJob::addQueryParams(QList<QPair<QString, QString>> params)
{
_additionalParams = params;
}
QNetworkRequest req;
req.setRawHeader("OCS-APIREQUEST", "true");
QUrl url = Utility::concatUrlPath(account()->url(), path());
- QList<QPair<QString, QString> > params = _additionalParams;
+ QList<QPair<QString, QString>> params = _additionalParams;
params << qMakePair(QString::fromLatin1("format"), QString::fromLatin1("json"));
url.setQueryItems(params);
sendRequest("GET", url, req);
bool JsonApiJob::finished()
{
qCInfo(lcJsonApiJob) << "JsonApiJob of" << reply()->request().url() << "FINISHED WITH STATUS"
- << reply()->error()
- << (reply()->error() == QNetworkReply::NoError ? QLatin1String("") : errorString());
+ << reply()->error()
+ << (reply()->error() == QNetworkReply::NoError ? QLatin1String("") : errorString());
int statusCode = 0;
}
QString jsonStr = QString::fromUtf8(reply()->readAll());
- if( jsonStr.contains( "<?xml version=\"1.0\"?>") ) {
+ if (jsonStr.contains("<?xml version=\"1.0\"?>")) {
QRegExp rex("<statuscode>(\\d+)</statuscode>");
- if( jsonStr.contains(rex) ) {
+ if (jsonStr.contains(rex)) {
// this is a error message coming back from ocs.
statusCode = rex.cap(1).toInt();
}
} else {
QRegExp rex("\"statuscode\":(\\d+),");
// example: "{"ocs":{"meta":{"status":"ok","statuscode":100,"message":null},"data":{"version":{"major":8,"minor":"... (504)
- if( jsonStr.contains(rex) ) {
+ if (jsonStr.contains(rex)) {
statusCode = rex.cap(1).toInt();
}
}
* @brief The EntityExistsJob class
* @ingroup libsync
*/
-class OWNCLOUDSYNC_EXPORT EntityExistsJob : public AbstractNetworkJob {
+class OWNCLOUDSYNC_EXPORT EntityExistsJob : public AbstractNetworkJob
+{
Q_OBJECT
public:
- explicit EntityExistsJob(AccountPtr account, const QString &path, QObject* parent = 0);
+ explicit EntityExistsJob(AccountPtr account, const QString &path, QObject *parent = 0);
void start() Q_DECL_OVERRIDE;
signals:
- void exists(QNetworkReply*);
+ void exists(QNetworkReply *);
private slots:
virtual bool finished() Q_DECL_OVERRIDE;
* @brief The LsColJob class
* @ingroup libsync
*/
-class OWNCLOUDSYNC_EXPORT LsColXMLParser : public QObject {
+class OWNCLOUDSYNC_EXPORT LsColXMLParser : public QObject
+{
Q_OBJECT
public:
explicit LsColXMLParser();
- bool parse(const QByteArray &xml, QHash<QString, qint64> *sizes, const QString& expectedPath);
+ bool parse(const QByteArray &xml, QHash<QString, qint64> *sizes, const QString &expectedPath);
signals:
void directoryListingSubfolders(const QStringList &items);
- void directoryListingIterated(const QString &name, const QMap<QString,QString> &properties);
+ void directoryListingIterated(const QString &name, const QMap<QString, QString> &properties);
void finishedWithError(QNetworkReply *reply);
void finishedWithoutError();
-
};
-class OWNCLOUDSYNC_EXPORT LsColJob : public AbstractNetworkJob {
+class OWNCLOUDSYNC_EXPORT LsColJob : public AbstractNetworkJob
+{
Q_OBJECT
public:
explicit LsColJob(AccountPtr account, const QString &path, QObject *parent = 0);
signals:
void directoryListingSubfolders(const QStringList &items);
- void directoryListingIterated(const QString &name, const QMap<QString,QString> &properties);
+ void directoryListingIterated(const QString &name, const QMap<QString, QString> &properties);
void finishedWithError(QNetworkReply *reply);
void finishedWithoutError();
*
* @ingroup libsync
*/
-class OWNCLOUDSYNC_EXPORT PropfindJob : public AbstractNetworkJob {
+class OWNCLOUDSYNC_EXPORT PropfindJob : public AbstractNetworkJob
+{
Q_OBJECT
public:
explicit PropfindJob(AccountPtr account, const QString &path, QObject *parent = 0);
*
* @ingroup libsync
*/
-class OWNCLOUDSYNC_EXPORT AvatarJob : public AbstractNetworkJob {
+class OWNCLOUDSYNC_EXPORT AvatarJob : public AbstractNetworkJob
+{
Q_OBJECT
public:
explicit AvatarJob(AccountPtr account, QObject *parent = 0);
*
* @ingroup libsync
*/
-class OWNCLOUDSYNC_EXPORT ProppatchJob : public AbstractNetworkJob {
+class OWNCLOUDSYNC_EXPORT ProppatchJob : public AbstractNetworkJob
+{
Q_OBJECT
public:
explicit ProppatchJob(AccountPtr account, const QString &path, QObject *parent = 0);
* @brief The MkColJob class
* @ingroup libsync
*/
-class OWNCLOUDSYNC_EXPORT MkColJob : public AbstractNetworkJob {
+class OWNCLOUDSYNC_EXPORT MkColJob : public AbstractNetworkJob
+{
Q_OBJECT
QUrl _url; // Only used if the constructor taking a url is taken.
QMap<QByteArray, QByteArray> _extraHeaders;
+
public:
explicit MkColJob(AccountPtr account, const QString &path, QObject *parent = 0);
explicit MkColJob(AccountPtr account, const QUrl &url,
- const QMap<QByteArray, QByteArray> &extraHeaders, QObject *parent = 0);
+ const QMap<QByteArray, QByteArray> &extraHeaders, QObject *parent = 0);
void start() Q_DECL_OVERRIDE;
signals:
* @brief The CheckServerJob class
* @ingroup libsync
*/
-class OWNCLOUDSYNC_EXPORT CheckServerJob : public AbstractNetworkJob {
+class OWNCLOUDSYNC_EXPORT CheckServerJob : public AbstractNetworkJob
+{
Q_OBJECT
public:
explicit CheckServerJob(AccountPtr account, QObject *parent = 0);
static bool installed(const QJsonObject &info);
signals:
- void instanceFound(const QUrl&url, const QJsonObject &info);
+ void instanceFound(const QUrl &url, const QJsonObject &info);
/** Emitted on invalid status.php reply.
*
* \a reply is never null
*/
void instanceNotFound(QNetworkReply *reply);
- void timeout(const QUrl&url);
+ void timeout(const QUrl &url);
private:
bool finished() Q_DECL_OVERRIDE;
/**
* @brief The RequestEtagJob class
*/
-class OWNCLOUDSYNC_EXPORT RequestEtagJob : public AbstractNetworkJob {
+class OWNCLOUDSYNC_EXPORT RequestEtagJob : public AbstractNetworkJob
+{
Q_OBJECT
public:
explicit RequestEtagJob(AccountPtr account, const QString &path, QObject *parent = 0);
*
* @ingroup libsync
*/
-class OWNCLOUDSYNC_EXPORT JsonApiJob : public AbstractNetworkJob {
+class OWNCLOUDSYNC_EXPORT JsonApiJob : public AbstractNetworkJob
+{
Q_OBJECT
public:
explicit JsonApiJob(const AccountPtr &account, const QString &path, QObject *parent = 0);
*
* This function needs to be called before start() obviously.
*/
- void addQueryParams(QList< QPair<QString,QString> > params);
+ void addQueryParams(QList<QPair<QString, QString>> params);
public slots:
void start() Q_DECL_OVERRIDE;
+
protected:
bool finished() Q_DECL_OVERRIDE;
signals:
void jsonReceived(const QJsonDocument &json, int statusCode);
private:
- QList< QPair<QString,QString> > _additionalParams;
+ QList<QPair<QString, QString>> _additionalParams;
};
} // namespace OCC
}
OwncloudPropagator::~OwncloudPropagator()
-{}
+{
+}
int OwncloudPropagator::maximumActiveTransferJob()
// disable parallelism when there is a network limit.
return 1;
}
- return qCeil(hardMaximumActiveJob()/2.);
+ return qCeil(hardMaximumActiveJob() / 2.);
}
/* The maximum number of active jobs in parallel */
static time_t getMinBlacklistTime()
{
return qMax(qgetenv("OWNCLOUD_BLACKLIST_TIME_MIN").toInt(),
- 25); // 25 seconds
+ 25); // 25 seconds
}
static time_t getMaxBlacklistTime()
int v = qgetenv("OWNCLOUD_BLACKLIST_TIME_MAX").toInt();
if (v > 0)
return v;
- return 24*60*60; // 1 day
+ return 24 * 60 * 60; // 1 day
}
/** Creates a blacklist entry, possibly taking into account an old one.
* The old entry may be invalid, then a fresh entry is created.
*/
static SyncJournalErrorBlacklistRecord createBlacklistEntry(
- const SyncJournalErrorBlacklistRecord& old, const SyncFileItem& item)
+ const SyncJournalErrorBlacklistRecord &old, const SyncFileItem &item)
{
SyncJournalErrorBlacklistRecord entry;
// The factor of 5 feels natural: 25s, 2 min, 10 min, ~1h, ~5h, ~24h
entry._ignoreDuration = old._ignoreDuration * 5;
- if( item._httpErrorCode == 403 ) {
+ if (item._httpErrorCode == 403) {
qCWarning(lcPropagator) << "Probably firewall error: " << item._httpErrorCode << ", blacklisting up to 1h only";
- entry._ignoreDuration = qMin(entry._ignoreDuration, time_t(60*60));
+ entry._ignoreDuration = qMin(entry._ignoreDuration, time_t(60 * 60));
- } else if( item._httpErrorCode == 413 || item._httpErrorCode == 415 ) {
+ } else if (item._httpErrorCode == 413 || item._httpErrorCode == 415) {
qCWarning(lcPropagator) << "Fatal Error condition" << item._httpErrorCode << ", maximum blacklist ignore time!";
entry._ignoreDuration = maxBlacklistTime;
}
entry._ignoreDuration = qBound(minBlacklistTime, entry._ignoreDuration, maxBlacklistTime);
- if( item._status == SyncFileItem::SoftError ) {
+ if (item._status == SyncFileItem::SoftError) {
// Track these errors, but don't actively suppress them.
entry._ignoreDuration = 0;
}
*
* May adjust the status or item._errorString.
*/
-static void blacklistUpdate(SyncJournalDb* journal, SyncFileItem& item)
+static void blacklistUpdate(SyncJournalDb *journal, SyncFileItem &item)
{
SyncJournalErrorBlacklistRecord oldEntry = journal->errorBlacklistEntry(item._file);
bool mayBlacklist =
- item._errorMayBeBlacklisted // explicitly flagged for blacklisting
- || ((item._status == SyncFileItem::NormalError
- || item._status == SyncFileItem::SoftError)
- && item._httpErrorCode != 0 // or non-local error
+ item._errorMayBeBlacklisted // explicitly flagged for blacklisting
+ || ((item._status == SyncFileItem::NormalError
+ || item._status == SyncFileItem::SoftError)
+ && item._httpErrorCode != 0 // or non-local error
);
// No new entry? Possibly remove the old one, then done.
item._errorString.prepend(PropagateItemJob::tr("Continue blacklisting:") + " ");
qCInfo(lcPropagator) << "blacklisting " << item._file
- << " for " << newEntry._ignoreDuration
- << ", retry count " << newEntry._retryCount;
+ << " for " << newEntry._ignoreDuration
+ << ", retry count " << newEntry._retryCount;
return;
}
// Some soft errors might become louder on repeat occurrence
if (item._status == SyncFileItem::SoftError
- && newEntry._retryCount > 1) {
+ && newEntry._retryCount > 1) {
qCWarning(lcPropagator) << "escalating soft error on " << item._file
- << " to normal error, " << item._httpErrorCode;
+ << " to normal error, " << item._httpErrorCode;
item._status = SyncFileItem::NormalError;
return;
}
_state = Finished;
if (_item->_isRestoration) {
- if( _item->_status == SyncFileItem::Success
- || _item->_status == SyncFileItem::Conflict) {
+ if (_item->_status == SyncFileItem::Success
+ || _item->_status == SyncFileItem::Conflict) {
_item->_status = SyncFileItem::Restoration;
} else {
_item->_errorString += tr("; Restoration Failed: %1").arg(errorString);
}
} else {
- if( _item->_errorString.isEmpty() ) {
+ if (_item->_errorString.isEmpty()) {
_item->_errorString = errorString;
}
}
- if( propagator()->_abortRequested.fetchAndAddRelaxed(0) &&
- (_item->_status == SyncFileItem::NormalError
- || _item->_status == SyncFileItem::FatalError)) {
+ if (propagator()->_abortRequested.fetchAndAddRelaxed(0) && (_item->_status == SyncFileItem::NormalError
+ || _item->_status == SyncFileItem::FatalError)) {
// an abort request is ongoing. Change the status to Soft-Error
_item->_status = SyncFileItem::SoftError;
}
- switch( _item->_status ) {
+ switch (_item->_status) {
case SyncFileItem::SoftError:
case SyncFileItem::FatalError:
case SyncFileItem::NormalError:
break;
case SyncFileItem::Success:
case SyncFileItem::Restoration:
- if( _item->_hasBlacklistEntry ) {
+ if (_item->_hasBlacklistEntry) {
// wipe blacklist entry.
propagator()->_journal->wipeErrorBlacklistEntry(_item->_file);
// remove a blacklist entry in case the file was moved.
- if( _item->_originalFile != _item->_file ) {
+ if (_item->_originalFile != _item->_file) {
propagator()->_journal->wipeErrorBlacklistEntry(_item->_originalFile);
}
}
*
* Return true if the problem is handled.
*/
-bool PropagateItemJob::checkForProblemsWithShared(int httpStatusCode, const QString& msg)
+bool PropagateItemJob::checkForProblemsWithShared(int httpStatusCode, const QString &msg)
{
PropagateItemJob *newJob = NULL;
- if( httpStatusCode == 403 && propagator()->isInSharedDirectory(_item->_file )) {
- if( !_item->_isDirectory ) {
+ if (httpStatusCode == 403 && propagator()->isInSharedDirectory(_item->_file)) {
+ if (!_item->_isDirectory) {
SyncFileItemPtr downloadItem(new SyncFileItem(*_item));
if (downloadItem->_instruction == CSYNC_INSTRUCTION_NEW
- || downloadItem->_instruction == CSYNC_INSTRUCTION_TYPE_CHANGE) {
+ || downloadItem->_instruction == CSYNC_INSTRUCTION_TYPE_CHANGE) {
// don't try to recover pushing new files
return false;
} else if (downloadItem->_instruction == CSYNC_INSTRUCTION_SYNC) {
propagator()->_journal->avoidRenamesOnNextSync(_item->_file);
propagator()->_anotherSyncNeeded = true;
}
- if( newJob ) {
+ if (newJob) {
newJob->setRestoreJobMsg(msg);
_restoreJob.reset(newJob);
connect(_restoreJob.data(), SIGNAL(finished(SyncFileItem::Status)),
- this, SLOT(slotRestoreJobFinished(SyncFileItem::Status)));
+ this, SLOT(slotRestoreJobFinished(SyncFileItem::Status)));
QMetaObject::invokeMethod(newJob, "start");
}
return true;
void PropagateItemJob::slotRestoreJobFinished(SyncFileItem::Status status)
{
QString msg;
- if(_restoreJob) {
+ if (_restoreJob) {
msg = _restoreJob->restoreJobMsg();
_restoreJob->setRestoreJobMsg();
}
- if( status == SyncFileItem::Success || status == SyncFileItem::Conflict
- || status == SyncFileItem::Restoration) {
- done( SyncFileItem::SoftError, msg);
+ if (status == SyncFileItem::Success || status == SyncFileItem::Conflict
+ || status == SyncFileItem::Restoration) {
+ done(SyncFileItem::SoftError, msg);
} else {
- done( status, tr("A file or folder was removed from a read only share, but restoring failed: %1").arg(msg) );
+ done(status, tr("A file or folder was removed from a read only share, but restoring failed: %1").arg(msg));
}
}
// ================================================================================
-PropagateItemJob* OwncloudPropagator::createJob(const SyncFileItemPtr &item) {
+PropagateItemJob *OwncloudPropagator::createJob(const SyncFileItemPtr &item)
+{
bool deleteExisting = item->_instruction == CSYNC_INSTRUCTION_TYPE_CHANGE;
- switch(item->_instruction) {
- case CSYNC_INSTRUCTION_REMOVE:
- if (item->_direction == SyncFileItem::Down) return new PropagateLocalRemove(this, item);
- else return new PropagateRemoteDelete(this, item);
- case CSYNC_INSTRUCTION_NEW:
- case CSYNC_INSTRUCTION_TYPE_CHANGE:
- if (item->_isDirectory) {
- if (item->_direction == SyncFileItem::Down) {
- auto job = new PropagateLocalMkdir(this, item);
- job->setDeleteExistingFile(deleteExisting);
- return job;
- } else {
- auto job = new PropagateRemoteMkdir(this, item);
- job->setDeleteExisting(deleteExisting);
- return job;
- }
- } //fall through
- case CSYNC_INSTRUCTION_SYNC:
- case CSYNC_INSTRUCTION_CONFLICT:
- if (item->_direction != SyncFileItem::Up) {
- auto job = new PropagateDownloadFile(this, item);
- job->setDeleteExistingFolder(deleteExisting);
+ switch (item->_instruction) {
+ case CSYNC_INSTRUCTION_REMOVE:
+ if (item->_direction == SyncFileItem::Down)
+ return new PropagateLocalRemove(this, item);
+ else
+ return new PropagateRemoteDelete(this, item);
+ case CSYNC_INSTRUCTION_NEW:
+ case CSYNC_INSTRUCTION_TYPE_CHANGE:
+ if (item->_isDirectory) {
+ if (item->_direction == SyncFileItem::Down) {
+ auto job = new PropagateLocalMkdir(this, item);
+ job->setDeleteExistingFile(deleteExisting);
return job;
} else {
- PropagateUploadFileCommon *job = 0;
- if (item->_size > _chunkSize && account()->capabilities().chunkingNg()) {
- job = new PropagateUploadFileNG(this, item);
- } else {
- job = new PropagateUploadFileV1(this, item);
- }
+ auto job = new PropagateRemoteMkdir(this, item);
job->setDeleteExisting(deleteExisting);
return job;
}
- case CSYNC_INSTRUCTION_RENAME:
- if (item->_direction == SyncFileItem::Up) {
- return new PropagateRemoteMove(this, item);
+ } //fall through
+ case CSYNC_INSTRUCTION_SYNC:
+ case CSYNC_INSTRUCTION_CONFLICT:
+ if (item->_direction != SyncFileItem::Up) {
+ auto job = new PropagateDownloadFile(this, item);
+ job->setDeleteExistingFolder(deleteExisting);
+ return job;
+ } else {
+ PropagateUploadFileCommon *job = 0;
+ if (item->_size > _chunkSize && account()->capabilities().chunkingNg()) {
+ job = new PropagateUploadFileNG(this, item);
} else {
- return new PropagateLocalRename(this, item);
+ job = new PropagateUploadFileV1(this, item);
}
- case CSYNC_INSTRUCTION_IGNORE:
- case CSYNC_INSTRUCTION_ERROR:
- return new PropagateIgnoreJob(this, item);
- default:
- return 0;
+ job->setDeleteExisting(deleteExisting);
+ return job;
+ }
+ case CSYNC_INSTRUCTION_RENAME:
+ if (item->_direction == SyncFileItem::Up) {
+ return new PropagateRemoteMove(this, item);
+ } else {
+ return new PropagateLocalRename(this, item);
+ }
+ case CSYNC_INSTRUCTION_IGNORE:
+ case CSYNC_INSTRUCTION_ERROR:
+ return new PropagateIgnoreJob(this, item);
+ default:
+ return 0;
}
return 0;
}
quint64 OwncloudPropagator::smallFileSize()
{
- const quint64 smallFileSize = 100*1024; //default to 1 MB. Not dynamic right now.
+ const quint64 smallFileSize = 100 * 1024; //default to 1 MB. Not dynamic right now.
return smallFileSize;
}
-void OwncloudPropagator::start(const SyncFileItemVector& items)
+void OwncloudPropagator::start(const SyncFileItemVector &items)
{
Q_ASSERT(std::is_sorted(items.begin(), items.end()));
* When we enter a directory, we can create the directory job and push it on the stack. */
_rootJob.reset(new PropagateDirectory(this));
- QStack<QPair<QString /* directory name */, PropagateDirectory* /* job */> > directories;
+ QStack<QPair<QString /* directory name */, PropagateDirectory * /* job */>> directories;
directories.push(qMakePair(QString(), _rootJob.data()));
- QVector<PropagatorJob*> directoriesToRemove;
+ QVector<PropagatorJob *> directoriesToRemove;
QString removedDirectory;
- foreach(const SyncFileItemPtr &item, items) {
-
+ foreach (const SyncFileItemPtr &item, items) {
if (!removedDirectory.isEmpty() && item->_file.startsWith(removedDirectory)) {
// this is an item in a directory which is going to be removed.
- PropagateDirectory *delDirJob = qobject_cast<PropagateDirectory*>(directoriesToRemove.first());
+ PropagateDirectory *delDirJob = qobject_cast<PropagateDirectory *>(directoriesToRemove.first());
if (item->_instruction == CSYNC_INSTRUCTION_REMOVE) {
// already taken care of. (by the removal of the parent directory)
// increase the number of subjobs that would be there.
- if( delDirJob ) {
+ if (delDirJob) {
delDirJob->increaseAffectedCount();
}
continue;
} else if (item->_isDirectory
- && (item->_instruction == CSYNC_INSTRUCTION_NEW
- || item->_instruction == CSYNC_INSTRUCTION_TYPE_CHANGE)) {
+ && (item->_instruction == CSYNC_INSTRUCTION_NEW
+ || item->_instruction == CSYNC_INSTRUCTION_TYPE_CHANGE)) {
// create a new directory within a deleted directory? That can happen if the directory
// etag was not fetched properly on the previous sync because the sync was aborted
// while uploading this directory (which is now removed). We can ignore it.
- if( delDirJob ) {
+ if (delDirJob) {
delDirJob->increaseAffectedCount();
}
continue;
// all is good, the rename will be executed before the directory deletion
} else {
qCWarning(lcPropagator) << "WARNING: Job within a removed directory? This should not happen!"
- << item->_file << item->_instruction;
+ << item->_file << item->_instruction;
}
}
PropagateDirectory *dir = new PropagateDirectory(this, item);
if (item->_instruction == CSYNC_INSTRUCTION_TYPE_CHANGE
- && item->_direction == SyncFileItem::Up) {
+ && item->_direction == SyncFileItem::Up) {
// Skip all potential uploads to the new folder.
// Processing them now leads to problems with permissions:
// checkForPermissions() has already run and used the permissions
// of the file we're about to delete to decide whether uploading
// to the new dir is ok...
- foreach(const SyncFileItemPtr &item2, items) {
+ foreach (const SyncFileItemPtr &item2, items) {
if (item2->destination().startsWith(item->destination() + "/")) {
item2->_instruction = CSYNC_INSTRUCTION_NONE;
_anotherSyncNeeded = true;
directories[i].second->_item->_instruction = CSYNC_INSTRUCTION_NONE;
}
} else {
- PropagateDirectory* currentDirJob = directories.top().second;
+ PropagateDirectory *currentDirJob = directories.top().second;
currentDirJob->appendJob(dir);
}
- directories.push(qMakePair(item->destination() + "/" , dir));
+ directories.push(qMakePair(item->destination() + "/", dir));
} else {
if (item->_instruction == CSYNC_INSTRUCTION_TYPE_CHANGE) {
// will delete directories, so defer execution
}
}
- foreach(PropagatorJob* it, directoriesToRemove) {
+ foreach (PropagatorJob *it, directoriesToRemove) {
_rootJob->appendJob(it);
}
scheduleNextJob();
}
-const SyncOptions& OwncloudPropagator::syncOptions() const
+const SyncOptions &OwncloudPropagator::syncOptions() const
{
return _syncOptions;
}
-void OwncloudPropagator::setSyncOptions(const SyncOptions& syncOptions)
+void OwncloudPropagator::setSyncOptions(const SyncOptions &syncOptions)
{
_syncOptions = syncOptions;
_chunkSize = syncOptions._initialChunkSize;
// ownCloud server < 7.0 did not had permissions so we need some other euristics
// to detect wrong doing in a Shared directory
-bool OwncloudPropagator::isInSharedDirectory(const QString& file)
+bool OwncloudPropagator::isInSharedDirectory(const QString &file)
{
bool re = false;
- if( _remoteFolder.startsWith( QLatin1String("Shared") ) ) {
+ if (_remoteFolder.startsWith(QLatin1String("Shared"))) {
// The Shared directory is synced as its own sync connection
re = true;
} else {
- if( file.startsWith("Shared/") || file == "Shared" ) {
+ if (file.startsWith("Shared/") || file == "Shared") {
// The whole ownCloud is synced and Shared is always a top dir
re = true;
}
ConfigFile cfg;
timeout = cfg.timeout();
}
-
}
return timeout;
}
-bool OwncloudPropagator::localFileNameClash( const QString& relFile )
+bool OwncloudPropagator::localFileNameClash(const QString &relFile)
{
bool re = false;
- const QString file( _localDir + relFile );
+ const QString file(_localDir + relFile);
- if( !file.isEmpty() && Utility::fsCasePreserving() ) {
+ if (!file.isEmpty() && Utility::fsCasePreserving()) {
#ifdef Q_OS_MAC
QFileInfo fileInfo(file);
if (!fileInfo.exists()) {
// https://bugreports.qt-project.org/browse/QTBUG-39622
const QString cName = fileInfo.canonicalFilePath().normalized(QString::NormalizationForm_C);
bool equal = (file == cName);
- re = (!equal && ! cName.endsWith(relFile, Qt::CaseSensitive) );
+ re = (!equal && !cName.endsWith(relFile, Qt::CaseSensitive));
}
#elif defined(Q_OS_WIN)
- const QString file( _localDir + relFile );
+ const QString file(_localDir + relFile);
qCDebug(lcPropagator) << "CaseClashCheck for " << file;
WIN32_FIND_DATA FindFileData;
HANDLE hFind;
- hFind = FindFirstFileW( (wchar_t*)file.utf16(), &FindFileData);
+ hFind = FindFirstFileW((wchar_t *)file.utf16(), &FindFileData);
if (hFind == INVALID_HANDLE_VALUE) {
// returns false.
} else {
- QString realFileName = QString::fromWCharArray( FindFileData.cFileName );
+ QString realFileName = QString::fromWCharArray(FindFileData.cFileName);
FindClose(hFind);
- if( ! file.endsWith(realFileName, Qt::CaseSensitive) ) {
+ if (!file.endsWith(realFileName, Qt::CaseSensitive)) {
qCWarning(lcPropagator) << "Detected case clash between" << file << "and" << realFileName;
re = true;
}
{
#ifdef Q_OS_WIN
bool result = false;
- const QString file( _localDir + relfile );
+ const QString file(_localDir + relfile);
WIN32_FIND_DATA FindFileData;
HANDLE hFind;
- hFind = FindFirstFileW(reinterpret_cast<const wchar_t*>(file.utf16()), &FindFileData);
+ hFind = FindFirstFileW(reinterpret_cast<const wchar_t *>(file.utf16()), &FindFileData);
if (hFind != INVALID_HANDLE_VALUE) {
- QString firstFile = QString::fromWCharArray( FindFileData.cFileName );
+ QString firstFile = QString::fromWCharArray(FindFileData.cFileName);
if (FindNextFile(hFind, &FindFileData)) {
- QString secondFile = QString::fromWCharArray( FindFileData.cFileName );
+ QString secondFile = QString::fromWCharArray(FindFileData.cFileName);
// This extra check shouldn't be necessary, but ensures that there
// are two different filenames that are identical when case is ignored.
if (firstFile != secondFile
- && QString::compare(firstFile, secondFile, Qt::CaseInsensitive) == 0) {
+ && QString::compare(firstFile, secondFile, Qt::CaseInsensitive) == 0) {
result = true;
qCWarning(lcPropagator) << "Found two filepaths that only differ in case: " << firstFile << secondFile;
}
#endif
}
-QString OwncloudPropagator::getFilePath(const QString& tmp_file_name) const
+QString OwncloudPropagator::getFilePath(const QString &tmp_file_name) const
{
return _localDir + tmp_file_name;
}
}
}
if (_activeJobList.count() < maximumActiveTransferJob() + likelyFinishedQuicklyCount) {
- qCDebug(lcPropagator) << "Can pump in another request! activeJobs =" << _activeJobList.count();
+ qCDebug(lcPropagator) << "Can pump in another request! activeJobs =" << _activeJobList.count();
if (_rootJob->scheduleSelfOrChild()) {
scheduleNextJob();
}
: QObject(propagator)
, _state(NotYetStarted)
{
-
}
OwncloudPropagator *PropagatorJob::propagator() const
{
- return qobject_cast<OwncloudPropagator*>(parent());
+ return qobject_cast<OwncloudPropagator *>(parent());
}
// ================================================================================
return;
_state = Finished;
- emit finished(_hasError == SyncFileItem::NoStatus ? SyncFileItem::Success : _hasError);
+ emit finished(_hasError == SyncFileItem::NoStatus ? SyncFileItem::Success : _hasError);
}
qint64 PropagatorCompositeJob::committedDiskSpace() const
{
qint64 needed = 0;
- foreach (PropagatorJob* job, _runningJobs) {
+ foreach (PropagatorJob *job, _runningJobs) {
needed += job->committedDiskSpace();
}
return needed;
}
return _subJobs.scheduleSelfOrChild();
-
}
void PropagateDirectory::slotFirstJobFinished(SyncFileItem::Status status)
void PropagateDirectory::slotSubJobsFinished(SyncFileItem::Status status)
{
if (!_item->isEmpty() && status == SyncFileItem::Success) {
- if( !_item->_renameTarget.isEmpty() ) {
- if(_item->_instruction == CSYNC_INSTRUCTION_RENAME
- && _item->_originalFile != _item->_renameTarget) {
+ if (!_item->_renameTarget.isEmpty()) {
+ if (_item->_instruction == CSYNC_INSTRUCTION_RENAME
+ && _item->_originalFile != _item->_renameTarget) {
// Remove the stale entries from the database.
propagator()->_journal->deleteFileRecord(_item->_originalFile, true);
}
if (_item->_instruction == CSYNC_INSTRUCTION_RENAME
|| _item->_instruction == CSYNC_INSTRUCTION_NEW
|| _item->_instruction == CSYNC_INSTRUCTION_UPDATE_METADATA) {
- if (PropagateRemoteMkdir* mkdir = qobject_cast<PropagateRemoteMkdir*>(_firstJob.data())) {
+ if (PropagateRemoteMkdir *mkdir = qobject_cast<PropagateRemoteMkdir *>(_firstJob.data())) {
// special case from MKDIR, get the fileId from the job there
if (_item->_fileId.isEmpty() && !mkdir->_item->_fileId.isEmpty()) {
_item->_fileId = mkdir->_item->_fileId;
}
}
- SyncJournalFileRecord record(*_item, propagator()->_localDir + _item->_file);
+ SyncJournalFileRecord record(*_item, propagator()->_localDir + _item->_file);
bool ok = propagator()->_journal->setFileRecordMetadata(record);
if (!ok) {
status = _item->_status = SyncFileItem::FatalError;
// ================================================================================
CleanupPollsJob::~CleanupPollsJob()
-{}
+{
+}
void CleanupPollsJob::start()
{
// Continue with the next entry, or finish
start();
}
-
}
*
* @ingroup libsync
*/
-class PropagatorJob : public QObject {
+class PropagatorJob : public QObject
+{
Q_OBJECT
public:
- explicit PropagatorJob(OwncloudPropagator* propagator);
+ explicit PropagatorJob(OwncloudPropagator *propagator);
enum JobState {
NotYetStarted,
/*
* Abstract class to propagate a single item
*/
-class PropagateItemJob : public PropagatorJob {
+class PropagateItemJob : public PropagatorJob
+{
Q_OBJECT
protected:
void done(SyncFileItem::Status status, const QString &errorString = QString());
- bool checkForProblemsWithShared(int httpStatusCode, const QString& msg);
+ bool checkForProblemsWithShared(int httpStatusCode, const QString &msg);
/*
* set a custom restore job message that is used if the restore job succeeded.
* It is displayed in the activity view.
*/
- QString restoreJobMsg() const {
+ QString restoreJobMsg() const
+ {
return _item->_isRestoration ? _item->_errorString : QString();
}
- void setRestoreJobMsg( const QString& msg = QString() ) {
+ void setRestoreJobMsg(const QString &msg = QString())
+ {
_item->_isRestoration = true;
_item->_errorString = msg;
}
QScopedPointer<PropagateItemJob> _restoreJob;
public:
- PropagateItemJob(OwncloudPropagator* propagator, const SyncFileItemPtr &item)
- : PropagatorJob(propagator), _item(item) {}
+ PropagateItemJob(OwncloudPropagator *propagator, const SyncFileItemPtr &item)
+ : PropagatorJob(propagator)
+ , _item(item)
+ {
+ }
~PropagateItemJob();
- bool scheduleSelfOrChild() Q_DECL_OVERRIDE {
+ bool scheduleSelfOrChild() Q_DECL_OVERRIDE
+ {
if (_state != NotYetStarted) {
return false;
}
- const char * instruction_str = csync_instruction_str(_item->_instruction);
+ const char *instruction_str = csync_instruction_str(_item->_instruction);
qCInfo(lcPropagator) << "Starting" << instruction_str << "propagation of" << _item->_file << "by" << this;
_state = Running;
return true;
}
- SyncFileItemPtr _item;
+ SyncFileItemPtr _item;
public slots:
virtual void start() = 0;
* @brief Job that runs subjobs. It becomes finished only when all subjobs are finished.
* @ingroup libsync
*/
-class PropagatorCompositeJob : public PropagatorJob {
+class PropagatorCompositeJob : public PropagatorJob
+{
Q_OBJECT
public:
QVector<PropagatorJob *> _jobsToDo;
SyncFileItemVector _tasksToDo;
QVector<PropagatorJob *> _runningJobs;
- SyncFileItem::Status _hasError; // NoStatus, or NormalError / SoftError if there was an error
+ SyncFileItem::Status _hasError; // NoStatus, or NormalError / SoftError if there was an error
explicit PropagatorCompositeJob(OwncloudPropagator *propagator)
: PropagatorJob(propagator)
, _hasError(SyncFileItem::NoStatus)
- { }
+ {
+ }
- virtual ~PropagatorCompositeJob() {
+ virtual ~PropagatorCompositeJob()
+ {
qDeleteAll(_jobsToDo);
qDeleteAll(_runningJobs);
}
- void appendJob(PropagatorJob *job) {
+ void appendJob(PropagatorJob *job)
+ {
_jobsToDo.append(job);
}
- void appendTask(const SyncFileItemPtr &item) {
+ void appendTask(const SyncFileItemPtr &item)
+ {
_tasksToDo.append(item);
}
virtual bool scheduleSelfOrChild() Q_DECL_OVERRIDE;
virtual JobParallelism parallelism() Q_DECL_OVERRIDE;
- virtual void abort() Q_DECL_OVERRIDE {
+ virtual void abort() Q_DECL_OVERRIDE
+ {
foreach (PropagatorJob *j, _runningJobs)
j->abort();
}
qint64 committedDiskSpace() const Q_DECL_OVERRIDE;
private slots:
- bool possiblyRunNextJob(PropagatorJob *next) {
+ bool possiblyRunNextJob(PropagatorJob *next)
+ {
if (next->_state == NotYetStarted) {
connect(next, SIGNAL(finished(SyncFileItem::Status)), this, SLOT(slotSubJobFinished(SyncFileItem::Status)));
}
* @brief Propagate a directory, and all its sub entries.
* @ingroup libsync
*/
-class OWNCLOUDSYNC_EXPORT PropagateDirectory : public PropagatorJob {
+class OWNCLOUDSYNC_EXPORT PropagateDirectory : public PropagatorJob
+{
Q_OBJECT
public:
SyncFileItemPtr _item;
// e.g: create the directory
- QScopedPointer<PropagateItemJob>_firstJob;
+ QScopedPointer<PropagateItemJob> _firstJob;
PropagatorCompositeJob _subJobs;
explicit PropagateDirectory(OwncloudPropagator *propagator, const SyncFileItemPtr &item = SyncFileItemPtr(new SyncFileItem));
- void appendJob(PropagatorJob *job) {
+ void appendJob(PropagatorJob *job)
+ {
_subJobs.appendJob(job);
}
- void appendTask(const SyncFileItemPtr &item) {
+ void appendTask(const SyncFileItemPtr &item)
+ {
_subJobs.appendTask(item);
}
virtual bool scheduleSelfOrChild() Q_DECL_OVERRIDE;
virtual JobParallelism parallelism() Q_DECL_OVERRIDE;
- virtual void abort() Q_DECL_OVERRIDE {
+ virtual void abort() Q_DECL_OVERRIDE
+ {
if (_firstJob)
_firstJob->abort();
_subJobs.abort();
}
- void increaseAffectedCount() {
+ void increaseAffectedCount()
+ {
_firstJob->_item->_affectedItems++;
}
- qint64 committedDiskSpace() const Q_DECL_OVERRIDE {
+ qint64 committedDiskSpace() const Q_DECL_OVERRIDE
+ {
return _subJobs.committedDiskSpace();
}
* @brief Dummy job that just mark it as completed and ignored
* @ingroup libsync
*/
-class PropagateIgnoreJob : public PropagateItemJob {
+class PropagateIgnoreJob : public PropagateItemJob
+{
Q_OBJECT
public:
- PropagateIgnoreJob(OwncloudPropagator* propagator,const SyncFileItemPtr& item)
- : PropagateItemJob(propagator, item) {}
- void start() Q_DECL_OVERRIDE {
+ PropagateIgnoreJob(OwncloudPropagator *propagator, const SyncFileItemPtr &item)
+ : PropagateItemJob(propagator, item)
+ {
+ }
+ void start() Q_DECL_OVERRIDE
+ {
SyncFileItem::Status status = _item->_status;
done(status == SyncFileItem::NoStatus ? SyncFileItem::FileIgnored : status, _item->_errorString);
}
};
-class OwncloudPropagator : public QObject {
+class OwncloudPropagator : public QObject
+{
Q_OBJECT
public:
const QString _localDir; // absolute path to the local directory. ends with '/'
const QString _remoteFolder; // remote folder, ends with '/'
- SyncJournalDb * const _journal;
+ SyncJournalDb *const _journal;
bool _finishedEmited; // used to ensure that finished is only emitted once
public:
OwncloudPropagator(AccountPtr account, const QString &localDir,
- const QString &remoteFolder, SyncJournalDb *progressDb)
- : _localDir((localDir.endsWith(QChar('/'))) ? localDir : localDir+'/' )
- , _remoteFolder((remoteFolder.endsWith(QChar('/'))) ? remoteFolder : remoteFolder+'/' )
- , _journal(progressDb)
- , _finishedEmited(false)
- , _bandwidthManager(this)
- , _anotherSyncNeeded(false)
- , _chunkSize(10 * 1000 * 1000) // 10 MB, overridden in setSyncOptions
- , _account(account)
- { }
+ const QString &remoteFolder, SyncJournalDb *progressDb)
+ : _localDir((localDir.endsWith(QChar('/'))) ? localDir : localDir + '/')
+ , _remoteFolder((remoteFolder.endsWith(QChar('/'))) ? remoteFolder : remoteFolder + '/')
+ , _journal(progressDb)
+ , _finishedEmited(false)
+ , _bandwidthManager(this)
+ , _anotherSyncNeeded(false)
+ , _chunkSize(10 * 1000 * 1000) // 10 MB, overridden in setSyncOptions
+ , _account(account)
+ {
+ }
~OwncloudPropagator();
void start(const SyncFileItemVector &_syncedItems);
- const SyncOptions& syncOptions() const;
- void setSyncOptions(const SyncOptions& syncOptions);
+ const SyncOptions &syncOptions() const;
+ void setSyncOptions(const SyncOptions &syncOptions);
QAtomicInt _downloadLimit;
QAtomicInt _uploadLimit;
Jobs add themself to the list when they do an assynchronous operation.
Jobs can be several time on the list (example, when several chunks are uploaded in parallel)
*/
- QList<PropagateItemJob*> _activeJobList;
+ QList<PropagateItemJob *> _activeJobList;
/** We detected that another sync is required after this one */
bool _anotherSyncNeeded;
/* The maximum number of active jobs in parallel */
int hardMaximumActiveJob();
- bool isInSharedDirectory(const QString& file);
+ bool isInSharedDirectory(const QString &file);
/** Check whether a download would clash with an existing file
* in filesystems that are only case-preserving.
*/
- bool localFileNameClash(const QString& relfile);
+ bool localFileNameClash(const QString &relfile);
/** Check whether a file is properly accessible for upload.
*
* When that happens, we want to avoid uploading incorrect data
* and give up on the file.
*/
- bool hasCaseClashAccessibilityProblem(const QString& relfile);
+ bool hasCaseClashAccessibilityProblem(const QString &relfile);
- QString getFilePath(const QString& tmp_file_name) const;
+ QString getFilePath(const QString &tmp_file_name) const;
- PropagateItemJob *createJob(const SyncFileItemPtr& item);
+ PropagateItemJob *createJob(const SyncFileItemPtr &item);
void scheduleNextJob();
- void reportProgress(const SyncFileItem&, quint64 bytes);
+ void reportProgress(const SyncFileItem &, quint64 bytes);
- void abort() {
+ void abort()
+ {
_abortRequested.fetchAndStoreOrdered(true);
if (_rootJob) {
// We're possibly already in an item's finished stack
AccountPtr account() const;
- enum DiskSpaceResult
- {
+ enum DiskSpaceResult {
DiskSpaceOk,
DiskSpaceFailure,
DiskSpaceCritical
DiskSpaceResult diskSpaceCheck() const;
-
private slots:
/** Emit the finished signal and make sure it is only emitted once */
- void emitFinished(SyncFileItem::Status status) {
+ void emitFinished(SyncFileItem::Status status)
+ {
if (!_finishedEmited)
emit finished(status == SyncFileItem::Success);
_finishedEmited = true;
signals:
void itemCompleted(const SyncFileItemPtr &);
- void progress(const SyncFileItem&, quint64 bytes);
+ void progress(const SyncFileItem &, quint64 bytes);
void finished(bool success);
/** Emitted when propagation has problems with a locked file. */
void touchedFile(const QString &fileName);
private:
-
AccountPtr _account;
QScopedPointer<PropagateDirectory> _rootJob;
SyncOptions _syncOptions;
* @brief Job that wait for all the poll jobs to be completed
* @ingroup libsync
*/
-class CleanupPollsJob : public QObject {
+class CleanupPollsJob : public QObject
+{
Q_OBJECT
- QVector< SyncJournalDb::PollInfo > _pollInfos;
+ QVector<SyncJournalDb::PollInfo> _pollInfos;
AccountPtr _account;
SyncJournalDb *_journal;
QString _localPath;
+
public:
- explicit CleanupPollsJob(const QVector< SyncJournalDb::PollInfo > &pollInfos, AccountPtr account,
- SyncJournalDb *journal, const QString &localPath, QObject* parent = 0)
- : QObject(parent), _pollInfos(pollInfos), _account(account), _journal(journal), _localPath(localPath) {}
+ explicit CleanupPollsJob(const QVector<SyncJournalDb::PollInfo> &pollInfos, AccountPtr account,
+ SyncJournalDb *journal, const QString &localPath, QObject *parent = 0)
+ : QObject(parent)
+ , _pollInfos(pollInfos)
+ , _account(account)
+ , _journal(journal)
+ , _localPath(localPath)
+ {
+ }
~CleanupPollsJob();
private slots:
void slotPollFinished();
};
-
}
#endif
namespace OCC {
-inline QByteArray parseEtag(const char *header) {
+inline QByteArray parseEtag(const char *header)
+{
if (!header)
return QByteArray();
QByteArray arr = header;
// https://github.com/owncloud/client/issues/1195
arr.replace("-gzip", "");
- if(arr.length() >= 2 && arr.startsWith('"') && arr.endsWith('"')) {
+ if (arr.length() >= 2 && arr.startsWith('"') && arr.endsWith('"')) {
arr = arr.mid(1, arr.length() - 2);
}
return arr;
* Given an error from the network, map to a SyncFileItem::Status error
*/
inline SyncFileItem::Status classifyError(QNetworkReply::NetworkError nerror,
- int httpCode,
- bool* anotherSyncNeeded = NULL) {
- Q_ASSERT (nerror != QNetworkReply::NoError); // we should only be called when there is an error
+ int httpCode,
+ bool *anotherSyncNeeded = NULL)
+{
+ Q_ASSERT(nerror != QNetworkReply::NoError); // we should only be called when there is an error
if (nerror > QNetworkReply::NoError && nerror <= QNetworkReply::UnknownProxyError) {
// network error or proxy error -> fatal
if (httpCode == 423) {
// "Locked"
// Should be temporary.
- if (anotherSyncNeeded) { *anotherSyncNeeded = true; }
+ if (anotherSyncNeeded) {
+ *anotherSyncNeeded = true;
+ }
return SyncFileItem::SoftError;
}
return SyncFileItem::NormalError;
}
-
}
namespace OCC {
-ownCloudTheme::ownCloudTheme() :
- Theme()
+ownCloudTheme::ownCloudTheme()
+ : Theme()
{
}
{
QString devString;
devString = trUtf8("<p>Version %2. For more information visit <a href=\"%3\">https://%4</a></p>"
- "<p>For known issues and help, please visit: <a href=\"https://central.owncloud.org/c/help/desktop-file-sync\">https://central.owncloud.org</a></p>"
- "<p><small>By Klaas Freitag, Daniel Molkentin, Olivier Goffart, Markus Götz, "
- " Jan-Christoph Borchardt, and others.</small></p>"
- "<p>Copyright ownCloud GmbH</p>"
- "<p>Licensed under the GNU General Public License (GPL) Version 2.0<br/>"
- "ownCloud and the ownCloud Logo are registered trademarks of ownCloud GmbH "
- "in the United States, other countries, or both.</p>"
- )
- .arg(Utility::escape(MIRALL_VERSION_STRING),
- Utility::escape("https://" MIRALL_STRINGIFY(APPLICATION_DOMAIN)),
- Utility::escape(MIRALL_STRINGIFY(APPLICATION_DOMAIN)));
+ "<p>For known issues and help, please visit: <a href=\"https://central.owncloud.org/c/help/desktop-file-sync\">https://central.owncloud.org</a></p>"
+ "<p><small>By Klaas Freitag, Daniel Molkentin, Olivier Goffart, Markus Götz, "
+ " Jan-Christoph Borchardt, and others.</small></p>"
+ "<p>Copyright ownCloud GmbH</p>"
+ "<p>Licensed under the GNU General Public License (GPL) Version 2.0<br/>"
+ "ownCloud and the ownCloud Logo are registered trademarks of ownCloud GmbH "
+ "in the United States, other countries, or both.</p>")
+ .arg(Utility::escape(MIRALL_VERSION_STRING),
+ Utility::escape("https://" MIRALL_STRINGIFY(APPLICATION_DOMAIN)),
+ Utility::escape(MIRALL_STRINGIFY(APPLICATION_DOMAIN)));
devString += gitSHA1();
return devString;
-
}
#ifndef TOKEN_AUTH_ONLY
-QIcon ownCloudTheme::trayFolderIcon( const QString& ) const
+QIcon ownCloudTheme::trayFolderIcon(const QString &) const
{
QPixmap fallback = qApp->style()->standardPixmap(QStyle::SP_FileDialogNewFolder);
return QIcon::fromTheme("folder", fallback);
}
-QIcon ownCloudTheme::applicationIcon( ) const
+QIcon ownCloudTheme::applicationIcon() const
{
- return themeIcon( QLatin1String("owncloud-icon") );
+ return themeIcon(QLatin1String("owncloud-icon"));
}
{
return QLatin1String("ownCloud");
}
-
-
}
-
QString about() const Q_DECL_OVERRIDE;
#ifndef TOKEN_AUTH_ONLY
- QIcon trayFolderIcon( const QString& ) const Q_DECL_OVERRIDE;
- QIcon applicationIcon() const Q_DECL_OVERRIDE;
+ QIcon trayFolderIcon(const QString &) const Q_DECL_OVERRIDE;
+ QIcon applicationIcon() const Q_DECL_OVERRIDE;
#endif
QString appName() const Q_DECL_OVERRIDE;
QString appNameGUI() const Q_DECL_OVERRIDE;
#ifndef TOKEN_AUTH_ONLY
QVariant customMedia(CustomMediaType type) Q_DECL_OVERRIDE;
- QColor wizardHeaderBackgroundColor() const Q_DECL_OVERRIDE;
- QColor wizardHeaderTitleColor() const Q_DECL_OVERRIDE;
+ QColor wizardHeaderBackgroundColor() const Q_DECL_OVERRIDE;
+ QColor wizardHeaderTitleColor() const Q_DECL_OVERRIDE;
QPixmap wizardHeaderLogo() const Q_DECL_OVERRIDE;
#endif
private:
-
-
};
-
}
#endif // OWNCLOUD_MIRALL_THEME_H
#define SQLITE_SLEEP_TIME_USEC 100000
#define SQLITE_REPEAT_COUNT 20
-#define SQLITE_DO(A) if(1) { \
- _errId = (A); if(_errId != SQLITE_OK) { _error= QString::fromUtf8(sqlite3_errmsg(_db)); \
- } }
+#define SQLITE_DO(A) \
+ if (1) { \
+ _errId = (A); \
+ if (_errId != SQLITE_OK) { \
+ _error = QString::fromUtf8(sqlite3_errmsg(_db)); \
+ } \
+ }
namespace OCC {
Q_LOGGING_CATEGORY(lcSql, "sync.database.sql", QtInfoMsg)
SqlDatabase::SqlDatabase()
- :_db(0),
- _errId(0)
+ : _db(0)
+ , _errId(0)
{
-
}
bool SqlDatabase::isOpen()
return _db != 0;
}
-bool SqlDatabase::openHelper( const QString& filename, int sqliteFlags )
+bool SqlDatabase::openHelper(const QString &filename, int sqliteFlags)
{
- if( isOpen() ) {
+ if (isOpen()) {
return true;
}
sqliteFlags |= SQLITE_OPEN_NOMUTEX;
- SQLITE_DO( sqlite3_open_v2(filename.toUtf8().constData(), &_db, sqliteFlags, 0) );
+ SQLITE_DO(sqlite3_open_v2(filename.toUtf8().constData(), &_db, sqliteFlags, 0));
- if( _errId != SQLITE_OK ) {
+ if (_errId != SQLITE_OK) {
qCWarning(lcSql) << "Error:" << _error << "for" << filename;
close();
return false;
}
- if( !_db ) {
+ if (!_db) {
qCWarning(lcSql) << "Error: no database for" << filename;
return false;
}
// quick_check can fail with a disk IO error when diskspace is low
SqlQuery quick_check(*this);
quick_check.prepare("PRAGMA quick_check;", /*allow_failure=*/true);
- if( !quick_check.exec() ) {
+ if (!quick_check.exec()) {
qCWarning(lcSql) << "Error running quick_check on database";
return false;
}
quick_check.next();
QString result = quick_check.stringValue(0);
- if( result != "ok" ) {
+ if (result != "ok") {
qCWarning(lcSql) << "quick_check returned failure:" << result;
return false;
}
return true;
}
-bool SqlDatabase::openOrCreateReadWrite( const QString& filename )
+bool SqlDatabase::openOrCreateReadWrite(const QString &filename)
{
- if( isOpen() ) {
+ if (isOpen()) {
return true;
}
- if( !openHelper(filename, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE) ) {
+ if (!openHelper(filename, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE)) {
return false;
}
- if( !checkDb() ) {
+ if (!checkDb()) {
// 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) {
return true;
}
-bool SqlDatabase::openReadOnly( const QString& filename )
+bool SqlDatabase::openReadOnly(const QString &filename)
{
- if( isOpen() ) {
+ if (isOpen()) {
return true;
}
- if( !openHelper(filename, SQLITE_OPEN_READONLY) ) {
+ if (!openHelper(filename, SQLITE_OPEN_READONLY)) {
return false;
}
- if( !checkDb() ) {
+ if (!checkDb()) {
qCWarning(lcSql) << "Consistency check failed in readonly mode, giving up" << filename;
close();
return false;
void SqlDatabase::close()
{
- if( _db ) {
- SQLITE_DO(sqlite3_close(_db) );
+ if (_db) {
+ SQLITE_DO(sqlite3_close(_db));
// Fatal because reopening an unclosed db might be problematic.
ENFORCE(_errId == SQLITE_OK, "Error when closing DB");
_db = 0;
bool SqlDatabase::transaction()
{
- if( ! _db ) {
+ if (!_db) {
return false;
}
SQLITE_DO(sqlite3_exec(_db, "BEGIN", 0, 0, 0));
bool SqlDatabase::commit()
{
- if( ! _db ) {
+ if (!_db) {
return false;
}
SQLITE_DO(sqlite3_exec(_db, "COMMIT", 0, 0, 0));
return _errId == SQLITE_OK;
}
-sqlite3* SqlDatabase::sqliteDb()
+sqlite3 *SqlDatabase::sqliteDb()
{
return _db;
}
/* =========================================================================================== */
-SqlQuery::SqlQuery( SqlDatabase& db )
- :_db(db.sqliteDb()),
- _stmt(0), _errId(0)
+SqlQuery::SqlQuery(SqlDatabase &db)
+ : _db(db.sqliteDb())
+ , _stmt(0)
+ , _errId(0)
{
-
}
SqlQuery::~SqlQuery()
{
- if( _stmt ) {
+ if (_stmt) {
finish();
}
}
-SqlQuery::SqlQuery(const QString& sql, SqlDatabase& db)
- :_db(db.sqliteDb()),
- _stmt(0), _errId(0)
+SqlQuery::SqlQuery(const QString &sql, SqlDatabase &db)
+ : _db(db.sqliteDb())
+ , _stmt(0)
+ , _errId(0)
{
prepare(sql);
}
-int SqlQuery::prepare( const QString& sql, bool allow_failure )
+int SqlQuery::prepare(const QString &sql, bool allow_failure)
{
QString s(sql);
_sql = s.trimmed();
- if(_stmt ) {
+ if (_stmt) {
finish();
}
- if(!_sql.isEmpty() ) {
+ if (!_sql.isEmpty()) {
int n = 0;
int rc;
do {
rc = sqlite3_prepare_v2(_db, _sql.toUtf8().constData(), -1, &_stmt, 0);
- if( (rc == SQLITE_BUSY) || (rc == SQLITE_LOCKED) ) {
+ if ((rc == SQLITE_BUSY) || (rc == SQLITE_LOCKED)) {
n++;
OCC::Utility::usleep(SQLITE_SLEEP_TIME_USEC);
}
- } while( (n < SQLITE_REPEAT_COUNT) && ((rc == SQLITE_BUSY) || (rc == SQLITE_LOCKED)));
+ } while ((n < SQLITE_REPEAT_COUNT) && ((rc == SQLITE_BUSY) || (rc == SQLITE_LOCKED)));
_errId = rc;
- if( _errId != SQLITE_OK ) {
+ if (_errId != SQLITE_OK) {
_error = QString::fromUtf8(sqlite3_errmsg(_db));
- qCWarning(lcSql) << "Sqlite prepare statement error:" << _error << "in" <<_sql;
+ qCWarning(lcSql) << "Sqlite prepare statement error:" << _error << "in" << _sql;
ENFORCE(allow_failure, "SQLITE Prepare error");
}
}
}
// Don't do anything for selects, that is how we use the lib :-|
- if( !isSelect() && !isPragma() ) {
+ if (!isSelect() && !isPragma()) {
int rc, n = 0;
do {
rc = sqlite3_step(_stmt);
- if( rc == SQLITE_LOCKED ) {
+ if (rc == SQLITE_LOCKED) {
rc = sqlite3_reset(_stmt); /* This will also return SQLITE_LOCKED */
n++;
OCC::Utility::usleep(SQLITE_SLEEP_TIME_USEC);
- } else if( rc == SQLITE_BUSY ) {
+ } else if (rc == SQLITE_BUSY) {
OCC::Utility::usleep(SQLITE_SLEEP_TIME_USEC);
n++;
}
- } while( (n < SQLITE_REPEAT_COUNT) && ((rc == SQLITE_BUSY) || (rc == SQLITE_LOCKED)));
+ } while ((n < SQLITE_REPEAT_COUNT) && ((rc == SQLITE_BUSY) || (rc == SQLITE_LOCKED)));
_errId = rc;
if (_errId != SQLITE_DONE && _errId != SQLITE_ROW) {
_error = QString::fromUtf8(sqlite3_errmsg(_db));
- qCWarning(lcSql) << "Sqlite exec statement error:" << _errId << _error << "in" <<_sql;
+ qCWarning(lcSql) << "Sqlite exec statement error:" << _errId << _error << "in" << _sql;
} else {
qCDebug(lcSql) << "Last exec affected" << numRowsAffected() << "rows.";
}
return _errId == SQLITE_ROW;
}
-void SqlQuery::bindValue(int pos, const QVariant& value)
+void SqlQuery::bindValue(int pos, const QVariant &value)
{
qCDebug(lcSql) << "SQL bind" << pos << value;
const QDateTime dateTime = value.toDateTime();
const QString str = dateTime.toString(QLatin1String("yyyy-MM-ddThh:mm:ss.zzz"));
res = sqlite3_bind_text16(_stmt, pos, str.utf16(),
- str.size() * sizeof(ushort), SQLITE_TRANSIENT);
+ str.size() * sizeof(ushort), SQLITE_TRANSIENT);
break;
}
case QVariant::Time: {
const QTime time = value.toTime();
const QString str = time.toString(QLatin1String("hh:mm:ss.zzz"));
res = sqlite3_bind_text16(_stmt, pos, str.utf16(),
- str.size() * sizeof(ushort), SQLITE_TRANSIENT);
+ str.size() * sizeof(ushort), SQLITE_TRANSIENT);
break;
}
case QVariant::String: {
- if( !value.toString().isNull() ) {
+ if (!value.toString().isNull()) {
// lifetime of string == lifetime of its qvariant
- const QString *str = static_cast<const QString*>(value.constData());
+ const QString *str = static_cast<const QString *>(value.constData());
res = sqlite3_bind_text16(_stmt, pos, str->utf16(),
- (str->size()) * sizeof(QChar), SQLITE_TRANSIENT);
+ (str->size()) * sizeof(QChar), SQLITE_TRANSIENT);
} else {
res = sqlite3_bind_null(_stmt, pos);
}
- break; }
+ break;
+ }
case QVariant::ByteArray: {
auto ba = value.toByteArray();
res = sqlite3_bind_text(_stmt, pos, ba.constData(), ba.size(), SQLITE_TRANSIENT);
QString str = value.toString();
// SQLITE_TRANSIENT makes sure that sqlite buffers the data
res = sqlite3_bind_text16(_stmt, pos, str.utf16(),
- (str.size()) * sizeof(QChar), SQLITE_TRANSIENT);
- break; }
+ (str.size()) * sizeof(QChar), SQLITE_TRANSIENT);
+ break;
+ }
}
if (res != SQLITE_OK) {
qCWarning(lcSql) << "ERROR binding SQL value:" << value << "error:" << res;
}
- ASSERT( res == SQLITE_OK );
+ ASSERT(res == SQLITE_OK);
}
bool SqlQuery::nullValue(int index)
QString SqlQuery::stringValue(int index)
{
- return QString::fromUtf16(static_cast<const ushort*>(sqlite3_column_text16(_stmt, index)));
+ return QString::fromUtf16(static_cast<const ushort *>(sqlite3_column_text16(_stmt, index)));
}
int SqlQuery::intValue(int index)
QByteArray SqlQuery::baValue(int index)
{
- return QByteArray( static_cast<const char*>(sqlite3_column_blob(_stmt, index)),
- sqlite3_column_bytes(_stmt, index));
+ return QByteArray(static_cast<const char *>(sqlite3_column_blob(_stmt, index)),
+ sqlite3_column_bytes(_stmt, index));
}
QString SqlQuery::error() const
explicit SqlDatabase();
bool isOpen();
- bool openOrCreateReadWrite( const QString& filename );
- bool openReadOnly( const QString& filename );
+ bool openOrCreateReadWrite(const QString &filename);
+ bool openReadOnly(const QString &filename);
bool transaction();
bool commit();
void close();
QString error() const;
- sqlite3* sqliteDb();
+ sqlite3 *sqliteDb();
private:
- bool openHelper( const QString& filename, int sqliteFlags );
+ bool openHelper(const QString &filename, int sqliteFlags);
bool checkDb();
sqlite3 *_db;
QString _error; // last error string
int _errId;
-
};
/**
{
Q_DISABLE_COPY(SqlQuery)
public:
- explicit SqlQuery(SqlDatabase& db);
- explicit SqlQuery(const QString& sql, SqlDatabase& db);
+ explicit SqlQuery(SqlDatabase &db);
+ explicit SqlQuery(const QString &sql, SqlDatabase &db);
~SqlQuery();
QString error() const;
- int errorId() const;
+ int errorId() const;
/// Checks whether the value at the given column index is NULL
bool nullValue(int index);
bool isSelect();
bool isPragma();
bool exec();
- int prepare( const QString& sql, bool allow_failure = false );
+ int prepare(const QString &sql, bool allow_failure = false);
bool next();
- void bindValue(int pos, const QVariant& value);
+ void bindValue(int pos, const QVariant &value);
QString lastQuery() const;
int numRowsAffected();
void reset_and_clear_bindings();
namespace OCC {
-ProgressDispatcher* ProgressDispatcher::_instance = 0;
+ProgressDispatcher *ProgressDispatcher::_instance = 0;
-QString Progress::asResultString( const SyncFileItem& item)
+QString Progress::asResultString(const SyncFileItem &item)
{
- switch(item._instruction) {
+ switch (item._instruction) {
case CSYNC_INSTRUCTION_SYNC:
case CSYNC_INSTRUCTION_NEW:
case CSYNC_INSTRUCTION_TYPE_CHANGE:
if (item._direction != SyncFileItem::Up) {
- return QCoreApplication::translate( "progress", "Downloaded");
+ return QCoreApplication::translate("progress", "Downloaded");
} else {
- return QCoreApplication::translate( "progress", "Uploaded");
+ return QCoreApplication::translate("progress", "Uploaded");
}
case CSYNC_INSTRUCTION_CONFLICT:
- return QCoreApplication::translate( "progress", "Server version downloaded, copied changed local file into conflict file");
+ return QCoreApplication::translate("progress", "Server version downloaded, copied changed local file into conflict file");
case CSYNC_INSTRUCTION_REMOVE:
- return QCoreApplication::translate( "progress", "Deleted");
+ return QCoreApplication::translate("progress", "Deleted");
case CSYNC_INSTRUCTION_EVAL_RENAME:
case CSYNC_INSTRUCTION_RENAME:
- return QCoreApplication::translate( "progress", "Moved to %1").arg(item._renameTarget);
+ return QCoreApplication::translate("progress", "Moved to %1").arg(item._renameTarget);
case CSYNC_INSTRUCTION_IGNORE:
- return QCoreApplication::translate( "progress", "Ignored");
+ return QCoreApplication::translate("progress", "Ignored");
case CSYNC_INSTRUCTION_STAT_ERROR:
- return QCoreApplication::translate( "progress", "Filesystem access error");
+ return QCoreApplication::translate("progress", "Filesystem access error");
case CSYNC_INSTRUCTION_ERROR:
- return QCoreApplication::translate( "progress", "Error");
+ return QCoreApplication::translate("progress", "Error");
case CSYNC_INSTRUCTION_UPDATE_METADATA:
- return QCoreApplication::translate( "progress", "Updated local metadata");
+ return QCoreApplication::translate("progress", "Updated local metadata");
case CSYNC_INSTRUCTION_NONE:
case CSYNC_INSTRUCTION_EVAL:
- return QCoreApplication::translate( "progress", "Unknown");
-
+ return QCoreApplication::translate("progress", "Unknown");
}
- return QCoreApplication::translate( "progress", "Unknown");
+ return QCoreApplication::translate("progress", "Unknown");
}
-QString Progress::asActionString( const SyncFileItem &item )
+QString Progress::asActionString(const SyncFileItem &item)
{
- switch(item._instruction) {
+ switch (item._instruction) {
case CSYNC_INSTRUCTION_CONFLICT:
case CSYNC_INSTRUCTION_SYNC:
case CSYNC_INSTRUCTION_NEW:
case CSYNC_INSTRUCTION_TYPE_CHANGE:
if (item._direction != SyncFileItem::Up)
- return QCoreApplication::translate( "progress", "downloading");
+ return QCoreApplication::translate("progress", "downloading");
else
- return QCoreApplication::translate( "progress", "uploading");
+ return QCoreApplication::translate("progress", "uploading");
case CSYNC_INSTRUCTION_REMOVE:
- return QCoreApplication::translate( "progress", "deleting");
+ return QCoreApplication::translate("progress", "deleting");
case CSYNC_INSTRUCTION_EVAL_RENAME:
case CSYNC_INSTRUCTION_RENAME:
- return QCoreApplication::translate( "progress", "moving");
+ return QCoreApplication::translate("progress", "moving");
case CSYNC_INSTRUCTION_IGNORE:
- return QCoreApplication::translate( "progress", "ignoring");
+ return QCoreApplication::translate("progress", "ignoring");
case CSYNC_INSTRUCTION_STAT_ERROR:
- return QCoreApplication::translate( "progress", "error");
+ return QCoreApplication::translate("progress", "error");
case CSYNC_INSTRUCTION_ERROR:
- return QCoreApplication::translate( "progress", "error");
+ return QCoreApplication::translate("progress", "error");
case CSYNC_INSTRUCTION_UPDATE_METADATA:
- return QCoreApplication::translate( "progress", "updating local metadata");
+ return QCoreApplication::translate("progress", "updating local metadata");
case CSYNC_INSTRUCTION_NONE:
case CSYNC_INSTRUCTION_EVAL:
break;
return QString();
}
-bool Progress::isWarningKind( SyncFileItem::Status kind)
+bool Progress::isWarningKind(SyncFileItem::Status kind)
{
- return kind == SyncFileItem::SoftError || kind == SyncFileItem::NormalError
- || kind == SyncFileItem::FatalError || kind == SyncFileItem::FileIgnored
- || kind == SyncFileItem::Conflict || kind == SyncFileItem::Restoration;
-
+ return kind == SyncFileItem::SoftError || kind == SyncFileItem::NormalError
+ || kind == SyncFileItem::FatalError || kind == SyncFileItem::FileIgnored
+ || kind == SyncFileItem::Conflict || kind == SyncFileItem::Restoration;
}
-bool Progress::isIgnoredKind( SyncFileItem::Status kind)
+bool Progress::isIgnoredKind(SyncFileItem::Status kind)
{
- return kind == SyncFileItem::FileIgnored;
-
+ return kind == SyncFileItem::FileIgnored;
}
-ProgressDispatcher* ProgressDispatcher::instance() {
+ProgressDispatcher *ProgressDispatcher::instance()
+{
if (!_instance) {
_instance = new ProgressDispatcher();
}
return _instance;
}
-ProgressDispatcher::ProgressDispatcher(QObject *parent) :
- QObject(parent)
+ProgressDispatcher::ProgressDispatcher(QObject *parent)
+ : QObject(parent)
{
-
}
ProgressDispatcher::~ProgressDispatcher()
{
-
}
-void ProgressDispatcher::setProgressInfo(const QString& folder, const ProgressInfo& progress)
+void ProgressDispatcher::setProgressInfo(const QString &folder, const ProgressInfo &progress)
{
- if( folder.isEmpty())
-// The update phase now also has progress
-// (progress._currentItems.size() == 0
-// && progress._totalFileCount == 0) )
+ if (folder.isEmpty())
+ // The update phase now also has progress
+ // (progress._currentItems.size() == 0
+ // && progress._totalFileCount == 0) )
{
return;
}
- emit progressInfo( folder, progress );
+ emit progressInfo(folder, progress);
}
ProgressInfo::ProgressInfo()
// Skip any ignored, error or non-propagated files and directories.
if (instruction == CSYNC_INSTRUCTION_NONE
- || instruction == CSYNC_INSTRUCTION_UPDATE_METADATA
- || instruction == CSYNC_INSTRUCTION_IGNORE
- || instruction == CSYNC_INSTRUCTION_ERROR) {
+ || instruction == CSYNC_INSTRUCTION_UPDATE_METADATA
+ || instruction == CSYNC_INSTRUCTION_IGNORE
+ || instruction == CSYNC_INSTRUCTION_ERROR) {
return false;
}
double fpsL = 0.5;
double fpsU = 0.8;
double nearMaxFps =
- qBound(0.0,
- (fps - fpsL * _maxFilesPerSecond) /
- ((fpsU - fpsL) * _maxFilesPerSecond),
- 1.0);
+ qBound(0.0,
+ (fps - fpsL * _maxFilesPerSecond) / ((fpsU - fpsL) * _maxFilesPerSecond),
+ 1.0);
// Compute a value that is 0 when transfer is >= U*max and
// 1 when transfer is <= L*max
double trans = _sizeProgress._progressPerSec;
double transU = 0.1;
double transL = 0.01;
- double slowTransfer = 1.0 -
- qBound(0.0,
- (trans - transL * _maxBytesPerSecond) /
- ((transU - transL) * _maxBytesPerSecond),
- 1.0);
+ double slowTransfer = 1.0 - qBound(0.0,
+ (trans - transL * _maxBytesPerSecond) / ((transU - transL) * _maxBytesPerSecond),
+ 1.0);
double beOptimistic = nearMaxFps * slowTransfer;
size.estimatedEta = (1.0 - beOptimistic) * size.estimatedEta
- + beOptimistic * optimisticEta();
+ + beOptimistic * optimisticEta();
return size;
}
// (if we never got to fully excercise transfer or files/second)
return _fileProgress.remaining() / _maxFilesPerSecond * 1000
- + _sizeProgress.remaining() / _maxBytesPerSecond * 1000;
+ + _sizeProgress.remaining() / _maxBytesPerSecond * 1000;
}
bool ProgressInfo::trustEta() const
}
_maxFilesPerSecond = qMax(_fileProgress._progressPerSec,
- _maxFilesPerSecond);
+ _maxFilesPerSecond);
_maxBytesPerSecond = qMax(_sizeProgress._progressPerSec,
- _maxBytesPerSecond);
+ _maxBytesPerSecond);
}
void ProgressInfo::recomputeCompletedSize()
{
quint64 r = _totalSizeOfCompletedJobs;
- foreach(const ProgressItem &i, _currentItems) {
+ foreach (const ProgressItem &i, _currentItems) {
if (isSizeDependent(i._item))
r += i._progress._completed;
}
_completed = qMin(completed, _total);
_prevCompleted = qMin(_prevCompleted, _completed);
}
-
-
}
/**
* Increase the file and size totals by the amount indicated in item.
*/
- void adjustTotalsForFile(const SyncFileItem & item);
+ void adjustTotalsForFile(const SyncFileItem &item);
quint64 totalFiles() const;
quint64 completedFiles() const;
quint64 currentFile() const;
/** Return true if the size needs to be taken in account in the total amount of time */
- static inline bool isSizeDependent(const SyncFileItem & item)
+ static inline bool isSizeDependent(const SyncFileItem &item)
{
- return ! item._isDirectory && (
- item._instruction == CSYNC_INSTRUCTION_CONFLICT
- || item._instruction == CSYNC_INSTRUCTION_SYNC
- || item._instruction == CSYNC_INSTRUCTION_NEW
- || item._instruction == CSYNC_INSTRUCTION_TYPE_CHANGE);
+ return !item._isDirectory && (item._instruction == CSYNC_INSTRUCTION_CONFLICT
+ || item._instruction == CSYNC_INSTRUCTION_SYNC
+ || item._instruction == CSYNC_INSTRUCTION_NEW
+ || item._instruction == CSYNC_INSTRUCTION_TYPE_CHANGE);
}
/**
namespace Progress {
- OWNCLOUDSYNC_EXPORT QString asActionString( const SyncFileItem& item );
- OWNCLOUDSYNC_EXPORT QString asResultString( const SyncFileItem& item );
-
- OWNCLOUDSYNC_EXPORT bool isWarningKind( SyncFileItem::Status );
- OWNCLOUDSYNC_EXPORT bool isIgnoredKind( SyncFileItem::Status );
+ OWNCLOUDSYNC_EXPORT QString asActionString(const SyncFileItem &item);
+ OWNCLOUDSYNC_EXPORT QString asResultString(const SyncFileItem &item);
+ OWNCLOUDSYNC_EXPORT bool isWarningKind(SyncFileItem::Status);
+ OWNCLOUDSYNC_EXPORT bool isIgnoredKind(SyncFileItem::Status);
}
/**
friend class Folder; // only allow Folder class to access the setting slots.
public:
- static ProgressDispatcher* instance();
+ static ProgressDispatcher *instance();
~ProgressDispatcher();
signals:
@param[out] progress A struct with all progress info.
*/
- void progressInfo( const QString& folder, const ProgressInfo& progress );
+ void progressInfo(const QString &folder, const ProgressInfo &progress);
/**
* @brief: the item was completed by a job
*/
- void itemCompleted(const QString &folder, const SyncFileItemPtr & item);
+ void itemCompleted(const QString &folder, const SyncFileItemPtr &item);
protected:
- void setProgressInfo(const QString& folder, const ProgressInfo& progress);
+ void setProgressInfo(const QString &folder, const ProgressInfo &progress);
private:
- ProgressDispatcher(QObject* parent = 0);
+ ProgressDispatcher(QObject *parent = 0);
QElapsedTimer _timer;
- static ProgressDispatcher* _instance;
+ static ProgressDispatcher *_instance;
};
-
}
#endif // PROGRESSDISPATCHER_H
// 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
-QString OWNCLOUDSYNC_EXPORT createDownloadTmpFileName(const QString &previous) {
+QString OWNCLOUDSYNC_EXPORT createDownloadTmpFileName(const QString &previous)
+{
QString tmpFileName;
QString tmpPath;
int slashPos = previous.lastIndexOf('/');
tmpFileName = previous;
tmpPath = QString();
} else {
- tmpFileName = previous.mid(slashPos+1);
+ tmpFileName = previous.mid(slashPos + 1);
tmpPath = previous.left(slashPos);
}
- int overhead = 1 + 1 + 2 + 8; // slash dot dot-tilde ffffffff"
+ int overhead = 1 + 1 + 2 + 8; // slash dot dot-tilde ffffffff"
int spaceForFileName = qMin(254, tmpFileName.length() + overhead) - overhead;
if (tmpPath.length() > 0) {
return tmpPath + '/' + '.' + tmpFileName.left(spaceForFileName) + ".~" + (QString::number(uint(qrand() % 0xFFFFFFFF), 16));
}
// DOES NOT take ownership of the device.
-GETFileJob::GETFileJob(AccountPtr account, const QString& path, QFile *device,
- const QMap<QByteArray, QByteArray> &headers, const QByteArray &expectedEtagForResume,
- quint64 resumeStart, QObject* parent)
-: AbstractNetworkJob(account, path, parent),
- _device(device), _headers(headers), _expectedEtagForResume(expectedEtagForResume)
-, _resumeStart(resumeStart) , _errorStatus(SyncFileItem::NoStatus)
-, _bandwidthLimited(false), _bandwidthChoked(false), _bandwidthQuota(0), _bandwidthManager(0)
-, _hasEmittedFinishedSignal(false), _lastModified()
+GETFileJob::GETFileJob(AccountPtr account, const QString &path, QFile *device,
+ const QMap<QByteArray, QByteArray> &headers, const QByteArray &expectedEtagForResume,
+ quint64 resumeStart, QObject *parent)
+ : AbstractNetworkJob(account, path, parent)
+ , _device(device)
+ , _headers(headers)
+ , _expectedEtagForResume(expectedEtagForResume)
+ , _resumeStart(resumeStart)
+ , _errorStatus(SyncFileItem::NoStatus)
+ , _bandwidthLimited(false)
+ , _bandwidthChoked(false)
+ , _bandwidthQuota(0)
+ , _bandwidthManager(0)
+ , _hasEmittedFinishedSignal(false)
+ , _lastModified()
{
}
-GETFileJob::GETFileJob(AccountPtr account, const QUrl& url, QFile *device,
- const QMap<QByteArray, QByteArray> &headers, const QByteArray &expectedEtagForResume,
- quint64 resumeStart, QObject* parent)
-
-: AbstractNetworkJob(account, url.toEncoded(), parent),
- _device(device), _headers(headers), _expectedEtagForResume(expectedEtagForResume)
-, _resumeStart(resumeStart), _errorStatus(SyncFileItem::NoStatus), _directDownloadUrl(url)
-, _bandwidthLimited(false), _bandwidthChoked(false), _bandwidthQuota(0), _bandwidthManager(0)
-, _hasEmittedFinishedSignal(false), _lastModified()
+GETFileJob::GETFileJob(AccountPtr account, const QUrl &url, QFile *device,
+ const QMap<QByteArray, QByteArray> &headers, const QByteArray &expectedEtagForResume,
+ quint64 resumeStart, QObject *parent)
+
+ : AbstractNetworkJob(account, url.toEncoded(), parent)
+ , _device(device)
+ , _headers(headers)
+ , _expectedEtagForResume(expectedEtagForResume)
+ , _resumeStart(resumeStart)
+ , _errorStatus(SyncFileItem::NoStatus)
+ , _directDownloadUrl(url)
+ , _bandwidthLimited(false)
+ , _bandwidthChoked(false)
+ , _bandwidthQuota(0)
+ , _bandwidthManager(0)
+ , _hasEmittedFinishedSignal(false)
+ , _lastModified()
{
}
-void GETFileJob::start() {
+void GETFileJob::start()
+{
if (_resumeStart > 0) {
- _headers["Range"] = "bytes=" + QByteArray::number(_resumeStart) +'-';
+ _headers["Range"] = "bytes=" + QByteArray::number(_resumeStart) + '-';
_headers["Accept-Ranges"] = "bytes";
qCDebug(lcGetJob) << "Retry with range " << _headers["Range"];
}
QNetworkRequest req;
- for(QMap<QByteArray, QByteArray>::const_iterator it = _headers.begin(); it != _headers.end(); ++it) {
+ for (QMap<QByteArray, QByteArray>::const_iterator it = _headers.begin(); it != _headers.end(); ++it) {
req.setRawHeader(it.key(), it.value());
}
_bandwidthManager->registerDownloadJob(this);
}
- if( reply()->error() != QNetworkReply::NoError ) {
+ if (reply()->error() != QNetworkReply::NoError) {
qCWarning(lcGetJob) << " Network error: " << errorString();
}
connect(reply(), SIGNAL(metaDataChanged()), this, SLOT(slotMetaDataChanged()));
connect(reply(), SIGNAL(readyRead()), this, SLOT(slotReadyRead()));
- connect(reply(), SIGNAL(downloadProgress(qint64,qint64)), this, SIGNAL(downloadProgress(qint64,qint64)));
+ connect(reply(), SIGNAL(downloadProgress(qint64, qint64)), this, SIGNAL(downloadProgress(qint64, qint64)));
connect(this, SIGNAL(networkActivity()), account().data(), SIGNAL(propagatorNetworkActivity()));
AbstractNetworkJob::start();
reply()->abort();
return;
} else if (!_expectedEtagForResume.isEmpty() && _expectedEtagForResume != _etag) {
- qCWarning(lcGetJob) << "We received a different E-Tag for resuming!"
- << _expectedEtagForResume << "vs" << _etag;
+ qCWarning(lcGetJob) << "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;
reply()->abort();
}
}
if (start != _resumeStart) {
- qCWarning(lcGetJob) << "Wrong content-range: "<< ranges << " while expecting start was" << _resumeStart;
+ qCWarning(lcGetJob) << "Wrong content-range: " << ranges << " while expecting start was" << _resumeStart;
if (ranges.isEmpty()) {
// device doesn't support range, just try again from scratch
_device->close();
{
if (!reply())
return;
- int bufferSize = qMin(1024*8ll , reply()->bytesAvailable());
+ int bufferSize = qMin(1024 * 8ll, reply()->bytesAvailable());
QByteArray buffer(bufferSize, Qt::Uninitialized);
- while(reply()->bytesAvailable() > 0) {
+ while (reply()->bytesAvailable() > 0) {
if (_bandwidthChoked) {
qCWarning(lcGetJob) << "Download choked";
break;
if (w != r) {
_errorString = _device->errorString();
_errorStatus = SyncFileItem::NormalError;
- qCWarning(lcGetJob) << "Error while writing to file" << w << r << _errorString;
+ qCWarning(lcGetJob) << "Error while writing to file" << w << r << _errorString;
reply()->abort();
return;
}
}
if (!_hasEmittedFinishedSignal) {
qCInfo(lcGetJob) << "GET of" << reply()->request().url().toString() << "FINISHED WITH STATUS"
- << reply()->error()
- << (reply()->error() == QNetworkReply::NoError ? QLatin1String("") : errorString())
- << reply()->rawHeader("Content-Range") << reply()->rawHeader("Content-Length");
+ << reply()->error()
+ << (reply()->error() == QNetworkReply::NoError ? QLatin1String("") : errorString())
+ << reply()->rawHeader("Content-Range") << reply()->rawHeader("Content-Length");
emit finishedSignal();
}
qCWarning(lcGetJob) << "Timeout" << (reply() ? reply()->request().url() : path());
if (!reply())
return;
- _errorString = tr("Connection Timeout");
+ _errorString = tr("Connection Timeout");
_errorStatus = SyncFileItem::FatalError;
reply()->abort();
}
}
// do a klaas' case clash check.
- if( propagator()->localFileNameClash(_item->_file) ) {
- done( SyncFileItem::NormalError, tr("File %1 can not be downloaded because of a local file name clash!")
- .arg(QDir::toNativeSeparators(_item->_file)) );
+ if (propagator()->localFileNameClash(_item->_file)) {
+ done(SyncFileItem::NormalError, tr("File %1 can not be downloaded because of a local file name clash!").arg(QDir::toNativeSeparators(_item->_file)));
return;
}
tmpFileName = progressInfo._tmpfile;
expectedEtagForResume = progressInfo._etag;
}
-
}
if (tmpFileName.isEmpty()) {
if (diskSpaceResult == OwncloudPropagator::DiskSpaceFailure) {
_item->_errorMayBeBlacklisted = true;
done(SyncFileItem::NormalError,
- tr("The download would reduce free disk space below %1").arg(
- Utility::octetsToString(freeSpaceLimit())));
+ tr("The download would reduce free disk space below %1").arg(Utility::octetsToString(freeSpaceLimit())));
} else if (diskSpaceResult == OwncloudPropagator::DiskSpaceCritical) {
done(SyncFileItem::FatalError,
- tr("Free space on disk is less than %1").arg(
- Utility::octetsToString(criticalFreeSpaceLimit())));
+ tr("Free space on disk is less than %1").arg(Utility::octetsToString(criticalFreeSpaceLimit())));
}
// Remove the temporary, if empty.
if (_item->_directDownloadUrl.isEmpty()) {
// Normal job, download from oC instance
_job = new GETFileJob(propagator()->account(),
- propagator()->_remoteFolder + _item->_file,
- &_tmpFile, headers, expectedEtagForResume, _resumeStart, this);
+ propagator()->_remoteFolder + _item->_file,
+ &_tmpFile, headers, expectedEtagForResume, _resumeStart, this);
} else {
// We were provided a direct URL, use that one
qCInfo(lcPropagateDownload) << "directDownloadUrl given for " << _item->_file << _item->_directDownloadUrl;
QUrl url = QUrl::fromUserInput(_item->_directDownloadUrl);
_job = new GETFileJob(propagator()->account(),
- url,
- &_tmpFile, headers, expectedEtagForResume, _resumeStart, this);
+ url,
+ &_tmpFile, headers, expectedEtagForResume, _resumeStart, this);
}
_job->setBandwidthManager(&propagator()->_bandwidthManager);
connect(_job, SIGNAL(finishedSignal()), this, SLOT(slotGetFinished()));
- connect(_job, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(slotDownloadProgress(qint64,qint64)));
+ connect(_job, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(slotDownloadProgress(qint64, qint64)));
propagator()->_activeJobList.append(this);
_job->start();
}
propagator()->_journal->setDownloadInfo(_item->_file, SyncJournalDb::DownloadInfo());
}
- if(!_item->_directDownloadUrl.isEmpty() && err != QNetworkReply::OperationCanceledError) {
+ if (!_item->_directDownloadUrl.isEmpty() && err != QNetworkReply::OperationCanceledError) {
// If this was with a direct download, retry without direct download
qCWarning(lcPropagateDownload) << "Direct download of" << _item->_directDownloadUrl << "failed. Retrying through owncloud.";
_item->_directDownloadUrl.clear();
SyncFileItem::Status status = job->errorStatus();
if (status == SyncFileItem::NoStatus) {
status = classifyError(err, _item->_httpErrorCode,
- &propagator()->_anotherSyncNeeded);
+ &propagator()->_anotherSyncNeeded);
}
done(status, job->errorString());
return;
}
- if(bodySize > 0 && bodySize != _tmpFile.size() - job->resumeStart() ) {
+ if (bodySize > 0 && 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."));
if (_tmpFile.size() == 0 && _item->_size > 0) {
FileSystem::remove(_tmpFile.fileName());
done(SyncFileItem::NormalError,
- tr("The downloaded file is empty despite the server announced it should have been %1.")
+ tr("The downloaded file is empty despite the server announced it should have been %1.")
.arg(Utility::octetsToString(_item->_size)));
return;
}
// will also emit the validated() signal to continue the flow in slot transmissionChecksumValidated()
// as this is (still) also correct.
ValidateChecksumHeader *validator = new ValidateChecksumHeader(this);
- connect(validator, SIGNAL(validated(QByteArray,QByteArray)),
- SLOT(transmissionChecksumValidated(QByteArray,QByteArray)));
+ connect(validator, SIGNAL(validated(QByteArray, QByteArray)),
+ SLOT(transmissionChecksumValidated(QByteArray, QByteArray)));
connect(validator, SIGNAL(validationFailed(QString)),
- SLOT(slotChecksumFail(QString)));
+ SLOT(slotChecksumFail(QString)));
auto checksumHeader = job->reply()->rawHeader(checkSumHeaderC);
validator->start(_tmpFile.fileName(), checksumHeader);
}
-void PropagateDownloadFile::slotChecksumFail( const QString& errMsg )
+void PropagateDownloadFile::slotChecksumFail(const QString &errMsg)
{
FileSystem::remove(_tmpFile.fileName());
propagator()->_anotherSyncNeeded = true;
- done(SyncFileItem::SoftError, errMsg ); // tr("The file downloaded with a broken checksum, will be redownloaded."));
+ done(SyncFileItem::SoftError, errMsg); // tr("The file downloaded with a broken checksum, will be redownloaded."));
}
void PropagateDownloadFile::deleteExistingFolder()
// Delete the directory if it is empty!
QDir dir(existingDir);
- if (dir.entryList(QDir::NoDotAndDotDot|QDir::AllEntries).count() == 0) {
+ if (dir.entryList(QDir::NoDotAndDotDot | QDir::AllEntries).count() == 0) {
if (dir.rmdir(existingDir)) {
return;
}
}
QString conflictDir = FileSystem::makeConflictFileName(
- existingDir, Utility::qDateTimeFromTime_t(FileSystem::getModTime(existingDir)));
+ existingDir, Utility::qDateTimeFromTime_t(FileSystem::getModTime(existingDir)));
emit propagator()->touchedFile(existingDir);
emit propagator()->touchedFile(conflictDir);
}
namespace { // Anonymous namespace for the recall feature
-static QString makeRecallFileName(const QString &fn)
-{
- QString recallFileName(fn);
- // Add _recall-XXXX before the extension.
- int dotLocation = recallFileName.lastIndexOf('.');
- // If no extension, add it at the end (take care of cases like foo/.hidden or foo.bar/file)
- if (dotLocation <= recallFileName.lastIndexOf('/') + 1) {
- dotLocation = recallFileName.size();
- }
+ static QString makeRecallFileName(const QString &fn)
+ {
+ QString recallFileName(fn);
+ // Add _recall-XXXX before the extension.
+ int dotLocation = recallFileName.lastIndexOf('.');
+ // If no extension, add it at the end (take care of cases like foo/.hidden or foo.bar/file)
+ if (dotLocation <= recallFileName.lastIndexOf('/') + 1) {
+ dotLocation = recallFileName.size();
+ }
- QString timeString = QDateTime::currentDateTime().toString("yyyyMMdd-hhmmss");
- recallFileName.insert(dotLocation, "_.sys.admin#recall#-" + timeString);
+ QString timeString = QDateTime::currentDateTime().toString("yyyyMMdd-hhmmss");
+ recallFileName.insert(dotLocation, "_.sys.admin#recall#-" + timeString);
- return recallFileName;
-}
+ return recallFileName;
+ }
-void handleRecallFile(const QString& filePath, const QString& folderPath, SyncJournalDb& journal)
-{
- qCDebug(lcPropagateDownload) << "handleRecallFile: " << filePath;
+ void handleRecallFile(const QString &filePath, const QString &folderPath, SyncJournalDb &journal)
+ {
+ qCDebug(lcPropagateDownload) << "handleRecallFile: " << filePath;
- FileSystem::setFileHidden(filePath, true);
+ FileSystem::setFileHidden(filePath, true);
- QFile file(filePath);
- if (!file.open(QIODevice::ReadOnly)) {
- qCWarning(lcPropagateDownload) << "Could not open recall file" << file.errorString();
- return;
- }
- QFileInfo existingFile(filePath);
- QDir baseDir = existingFile.dir();
+ QFile file(filePath);
+ if (!file.open(QIODevice::ReadOnly)) {
+ qCWarning(lcPropagateDownload) << "Could not open recall file" << file.errorString();
+ return;
+ }
+ QFileInfo existingFile(filePath);
+ QDir baseDir = existingFile.dir();
- while (!file.atEnd()) {
- QByteArray line = file.readLine();
- line.chop(1); // remove trailing \n
+ while (!file.atEnd()) {
+ QByteArray line = file.readLine();
+ line.chop(1); // remove trailing \n
- QString recalledFile = QDir::cleanPath(baseDir.filePath(line));
- if (!recalledFile.startsWith(folderPath) || !recalledFile.startsWith(baseDir.path())) {
- qCWarning(lcPropagateDownload) << "Ignoring recall of " << recalledFile;
- continue;
- }
+ QString recalledFile = QDir::cleanPath(baseDir.filePath(line));
+ if (!recalledFile.startsWith(folderPath) || !recalledFile.startsWith(baseDir.path())) {
+ qCWarning(lcPropagateDownload) << "Ignoring recall of " << recalledFile;
+ continue;
+ }
- // Path of the recalled file in the local folder
- QString localRecalledFile = recalledFile.mid(folderPath.size());
+ // Path of the recalled file in the local folder
+ QString localRecalledFile = recalledFile.mid(folderPath.size());
- SyncJournalFileRecord record = journal.getFileRecord(localRecalledFile);
- if (!record.isValid()) {
- qCWarning(lcPropagateDownload) << "No db entry for recall of" << localRecalledFile;
- continue;
- }
+ SyncJournalFileRecord record = journal.getFileRecord(localRecalledFile);
+ if (!record.isValid()) {
+ qCWarning(lcPropagateDownload) << "No db entry for recall of" << localRecalledFile;
+ continue;
+ }
- qCInfo(lcPropagateDownload) << "Recalling" << localRecalledFile << "Checksum:" << record._contentChecksumType << record._contentChecksum;
+ qCInfo(lcPropagateDownload) << "Recalling" << localRecalledFile << "Checksum:" << record._contentChecksumType << record._contentChecksum;
- QString targetPath = makeRecallFileName(recalledFile);
+ QString targetPath = makeRecallFileName(recalledFile);
- qCDebug(lcPropagateDownload) << "Copy recall file: " << recalledFile << " -> " << targetPath;
- // Remove the target first, QFile::copy will not overwrite it.
- FileSystem::remove(targetPath);
- QFile::copy(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);
+ }
}
-}
-static void preserveGroupOwnership(const QString& fileName, const QFileInfo& fi)
-{
+ static void preserveGroupOwnership(const QString &fileName, const QFileInfo &fi)
+ {
#ifdef Q_OS_UNIX
- chown(fileName.toLocal8Bit().constData(), -1, fi.groupId());
+ chown(fileName.toLocal8Bit().constData(), -1, fi.groupId());
#else
- Q_UNUSED(fileName);
- Q_UNUSED(fi);
+ Q_UNUSED(fileName);
+ Q_UNUSED(fi);
#endif
-}
+ }
} // end namespace
void PropagateDownloadFile::transmissionChecksumValidated(const QByteArray &checksumType, const QByteArray &checksum)
auto computeChecksum = new ComputeChecksum(this);
computeChecksum->setChecksumType(theContentChecksumType);
- connect(computeChecksum, SIGNAL(done(QByteArray,QByteArray)),
- SLOT(contentChecksumComputed(QByteArray,QByteArray)));
+ connect(computeChecksum, SIGNAL(done(QByteArray, QByteArray)),
+ SLOT(contentChecksumComputed(QByteArray, QByteArray)));
computeChecksum->start(_tmpFile.fileName());
}
// In case of file name clash, report an error
// This can happen if another parallel download saved a clashing file.
if (propagator()->localFileNameClash(_item->_file)) {
- done( SyncFileItem::NormalError, tr("File %1 cannot be saved because of a local file name clash!")
- .arg(QDir::toNativeSeparators(_item->_file)) );
+ done(SyncFileItem::NormalError, tr("File %1 cannot be saved because of a local file name clash!").arg(QDir::toNativeSeparators(_item->_file)));
return;
}
// In case of conflict, make a backup of the old file
// Ignore conflicts where both files are binary equal
bool isConflict = _item->_instruction == CSYNC_INSTRUCTION_CONFLICT
- && !FileSystem::fileEquals(fn, _tmpFile.fileName());
+ && !FileSystem::fileEquals(fn, _tmpFile.fileName());
if (isConflict) {
QString renameError;
QString conflictFileName = FileSystem::makeConflictFileName(
- fn, Utility::qDateTimeFromTime_t(FileSystem::getModTime(fn)));
+ fn, Utility::qDateTimeFromTime_t(FileSystem::getModTime(fn)));
if (!FileSystem::rename(fn, conflictFileName, &renameError)) {
// If the rename fails, don't replace it.
// the discovery phase and now.
const qint64 expectedSize = _item->log._other_size;
const time_t expectedMtime = _item->log._other_modtime;
- if (! FileSystem::verifyFileUnchanged(fn, expectedSize, expectedMtime)) {
+ if (!FileSystem::verifyFileUnchanged(fn, expectedSize, expectedMtime)) {
propagator()->_anotherSyncNeeded = true;
done(SyncFileItem::SoftError, tr("File has changed since discovery"));
return;
const int serverVersionGoodRemotePerm = Account::makeServerVersion(7, 0, 0);
if (propagator()->account()->serverVersionInt() >= serverVersionGoodRemotePerm) {
FileSystem::setFileReadOnlyWeak(_tmpFile.fileName(),
- !_item->_remotePerm.contains('W'));
+ !_item->_remotePerm.contains('W'));
}
QString error;
done(isConflict ? SyncFileItem::Conflict : SyncFileItem::Success);
// handle the special recall file
- if(!_item->_remotePerm.contains("S")
- && (_item->_file == QLatin1String(".sys.admin#recall#")
- || _item->_file.endsWith("/.sys.admin#recall#"))) {
+ if (!_item->_remotePerm.contains("S")
+ && (_item->_file == QLatin1String(".sys.admin#recall#")
+ || _item->_file.endsWith("/.sys.admin#recall#"))) {
handleRecallFile(fn, propagator()->_localDir, *propagator()->_journal);
}
qint64 duration = _stopwatch.elapsed();
- if (isLikelyFinishedQuickly() && duration > 5*1000) {
+ if (isLikelyFinishedQuickly() && duration > 5 * 1000) {
qCWarning(lcPropagateDownload) << "WARNING: Unexpectedly slow connection, took" << duration << "msec for" << _item->_size - _resumeStart << "bytes for" << _item->_file;
}
}
void PropagateDownloadFile::slotDownloadProgress(qint64 received, qint64)
{
- if (!_job) return;
+ if (!_job)
+ return;
_downloadProgress = received;
propagator()->reportProgress(*_item, _resumeStart + received);
}
void PropagateDownloadFile::abort()
{
- if (_job && _job->reply())
+ if (_job && _job->reply())
_job->reply()->abort();
}
-
-
}
* @brief The GETFileJob class
* @ingroup libsync
*/
-class GETFileJob : public AbstractNetworkJob {
+class GETFileJob : public AbstractNetworkJob
+{
Q_OBJECT
- QFile* _device;
+ QFile *_device;
QMap<QByteArray, QByteArray> _headers;
QString _errorString;
QByteArray _expectedEtagForResume;
QPointer<BandwidthManager> _bandwidthManager;
bool _hasEmittedFinishedSignal;
time_t _lastModified;
-public:
+public:
// DOES NOT take ownership of the device.
- explicit GETFileJob(AccountPtr account, const QString& path, QFile *device,
- const QMap<QByteArray, QByteArray> &headers, const QByteArray &expectedEtagForResume,
- quint64 resumeStart, QObject* parent = 0);
+ explicit GETFileJob(AccountPtr account, const QString &path, QFile *device,
+ const QMap<QByteArray, QByteArray> &headers, const QByteArray &expectedEtagForResume,
+ quint64 resumeStart, QObject *parent = 0);
// For directDownloadUrl:
- explicit GETFileJob(AccountPtr account, const QUrl& url, QFile *device,
- const QMap<QByteArray, QByteArray> &headers, const QByteArray &expectedEtagForResume,
- quint64 resumeStart, QObject* parent = 0);
- virtual ~GETFileJob() {
+ explicit GETFileJob(AccountPtr account, const QUrl &url, QFile *device,
+ const QMap<QByteArray, QByteArray> &headers, const QByteArray &expectedEtagForResume,
+ quint64 resumeStart, QObject *parent = 0);
+ virtual ~GETFileJob()
+ {
if (_bandwidthManager) {
_bandwidthManager->unregisterDownloadJob(this);
}
}
virtual void start() Q_DECL_OVERRIDE;
- virtual bool finished() Q_DECL_OVERRIDE {
+ virtual bool finished() Q_DECL_OVERRIDE
+ {
if (reply()->bytesAvailable()) {
return false;
} else {
qint64 currentDownloadPosition();
QString errorString() const;
- void setErrorString(const QString& s) { _errorString = s; }
+ void setErrorString(const QString &s) { _errorString = s; }
SyncFileItem::Status errorStatus() { return _errorStatus; }
- void setErrorStatus(const SyncFileItem::Status & s) { _errorStatus = s; }
+ void setErrorStatus(const SyncFileItem::Status &s) { _errorStatus = s; }
void onTimedOut() Q_DECL_OVERRIDE;
signals:
void finishedSignal();
- void downloadProgress(qint64,qint64);
+ void downloadProgress(qint64, qint64);
private slots:
void slotReadyRead();
void slotMetaDataChanged();
* @brief The PropagateDownloadFile class
* @ingroup libsync
*/
-class PropagateDownloadFile : public PropagateItemJob {
+class PropagateDownloadFile : public PropagateItemJob
+{
Q_OBJECT
public:
- PropagateDownloadFile(OwncloudPropagator* propagator,const SyncFileItemPtr& item)
- : PropagateItemJob(propagator, item), _resumeStart(0), _downloadProgress(0), _deleteExisting(false) {}
+ PropagateDownloadFile(OwncloudPropagator *propagator, const SyncFileItemPtr &item)
+ : PropagateItemJob(propagator, item)
+ , _resumeStart(0)
+ , _downloadProgress(0)
+ , _deleteExisting(false)
+ {
+ }
void start() Q_DECL_OVERRIDE;
qint64 committedDiskSpace() const Q_DECL_OVERRIDE;
private slots:
void slotGetFinished();
void abort() Q_DECL_OVERRIDE;
- void transmissionChecksumValidated(const QByteArray& checksumType, const QByteArray& checksum);
- void contentChecksumComputed(const QByteArray& checksumType, const QByteArray& checksum);
+ void transmissionChecksumValidated(const QByteArray &checksumType, const QByteArray &checksum);
+ void contentChecksumComputed(const QByteArray &checksumType, const QByteArray &checksum);
void downloadFinished();
- void slotDownloadProgress(qint64,qint64);
- void slotChecksumFail( const QString& errMsg );
+ void slotDownloadProgress(qint64, qint64);
+ void slotChecksumFail(const QString &errMsg);
private:
void deleteExistingFolder();
QElapsedTimer _stopwatch;
};
-
}
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)
+DeleteJob::DeleteJob(AccountPtr account, const QString &path, QObject *parent)
: AbstractNetworkJob(account, path, parent)
-{ }
+{
+}
-DeleteJob::DeleteJob(AccountPtr account, const QUrl& url, QObject* parent)
- : AbstractNetworkJob(account, QString(), parent), _url(url)
-{ }
+DeleteJob::DeleteJob(AccountPtr account, const QUrl &url, QObject *parent)
+ : AbstractNetworkJob(account, QString(), parent)
+ , _url(url)
+{
+}
void DeleteJob::start()
{
sendRequest("DELETE", makeDavUrl(path()), req);
}
- if( reply()->error() != QNetworkReply::NoError ) {
+ if (reply()->error() != QNetworkReply::NoError) {
qCWarning(lcDeleteJob) << " Network error: " << reply()->errorString();
}
AbstractNetworkJob::start();
bool DeleteJob::finished()
{
qCInfo(lcDeleteJob) << "DELETE of" << reply()->request().url() << "FINISHED WITH STATUS"
- << reply()->error()
- << (reply()->error() == QNetworkReply::NoError ? QLatin1String("") : errorString());
+ << reply()->error()
+ << (reply()->error() == QNetworkReply::NoError ? QLatin1String("") : errorString());
emit finishedSignal();
return true;
qCDebug(lcPropagateRemoteDelete) << _item->_file;
_job = new DeleteJob(propagator()->account(),
- propagator()->_remoteFolder + _item->_file,
- this);
+ propagator()->_remoteFolder + _item->_file,
+ this);
connect(_job, SIGNAL(finishedSignal()), this, SLOT(slotDeleteJobFinished()));
propagator()->_activeJobList.append(this);
_job->start();
void PropagateRemoteDelete::abort()
{
- if (_job && _job->reply())
+ if (_job && _job->reply())
_job->reply()->abort();
}
_item->_httpErrorCode = httpStatus;
if (err != QNetworkReply::NoError && err != QNetworkReply::ContentNotFoundError) {
-
- if( checkForProblemsWithShared(_item->_httpErrorCode,
- tr("The file has been removed from a read only share. It was restored.")) ) {
+ if (checkForProblemsWithShared(_item->_httpErrorCode,
+ tr("The file has been removed from a read only share. It was restored."))) {
return;
}
SyncFileItem::Status status = classifyError(err, _item->_httpErrorCode,
- &propagator()->_anotherSyncNeeded);
+ &propagator()->_anotherSyncNeeded);
done(status, _job->errorString());
return;
}
// If it is not the case, it might be because of a proxy or gateway intercepting the request, so we must
// throw an error.
done(SyncFileItem::NormalError,
- tr("Wrong HTTP code returned by server. Expected 204, but received \"%1 %2\".")
- .arg(_item->_httpErrorCode)
- .arg(_job->reply()->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString()));
+ tr("Wrong HTTP code returned by server. Expected 204, but received \"%1 %2\".")
+ .arg(_item->_httpErrorCode)
+ .arg(_job->reply()->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString()));
return;
}
propagator()->_journal->commit("Remote Remove");
done(SyncFileItem::Success);
}
-
-
}
-
* @brief The DeleteJob class
* @ingroup libsync
*/
-class DeleteJob : public AbstractNetworkJob {
+class DeleteJob : public AbstractNetworkJob
+{
Q_OBJECT
QUrl _url; // Only used if the constructor taking a url is taken.
public:
- explicit DeleteJob(AccountPtr account, const QString& path, QObject* parent = 0);
- explicit DeleteJob(AccountPtr account, const QUrl& url, QObject* parent = 0);
+ explicit DeleteJob(AccountPtr account, const QString &path, QObject *parent = 0);
+ explicit DeleteJob(AccountPtr account, const QUrl &url, QObject *parent = 0);
void start() Q_DECL_OVERRIDE;
bool finished() Q_DECL_OVERRIDE;
* @brief The PropagateRemoteDelete class
* @ingroup libsync
*/
-class PropagateRemoteDelete : public PropagateItemJob {
+class PropagateRemoteDelete : public PropagateItemJob
+{
Q_OBJECT
QPointer<DeleteJob> _job;
+
public:
- PropagateRemoteDelete (OwncloudPropagator* propagator,const SyncFileItemPtr& item)
- : PropagateItemJob(propagator, item) {}
+ PropagateRemoteDelete(OwncloudPropagator *propagator, const SyncFileItemPtr &item)
+ : PropagateItemJob(propagator, item)
+ {
+ }
void start() Q_DECL_OVERRIDE;
void abort() Q_DECL_OVERRIDE;
private slots:
void slotDeleteJobFinished();
-
};
-
}
}
_job = new DeleteJob(propagator()->account(),
- propagator()->_remoteFolder + _item->_file,
- this);
+ propagator()->_remoteFolder + _item->_file,
+ this);
connect(_job, SIGNAL(finishedSignal()), SLOT(slotStartMkcolJob()));
_job->start();
}
qCDebug(lcPropagateRemoteMkdir) << _item->_file;
_job = new MkColJob(propagator()->account(),
- propagator()->_remoteFolder + _item->_file,
- this);
+ propagator()->_remoteFolder + _item->_file,
+ this);
connect(_job, SIGNAL(finished(QNetworkReply::NetworkError)), this, SLOT(slotMkcolJobFinished()));
_job->start();
}
void PropagateRemoteMkdir::abort()
{
- if (_job && _job->reply())
+ if (_job && _job->reply())
_job->reply()->abort();
}
// This happens when the directory already exists. Nothing to do.
} else if (err != QNetworkReply::NoError) {
SyncFileItem::Status status = classifyError(err, _item->_httpErrorCode,
- &propagator()->_anotherSyncNeeded);
+ &propagator()->_anotherSyncNeeded);
done(status, _job->errorString());
return;
} else if (_item->_httpErrorCode != 201) {
// If it is not the case, it might be because of a proxy or gateway intercepting the request, so we must
// throw an error.
done(SyncFileItem::NormalError,
- tr("Wrong HTTP code returned by server. Expected 201, but received \"%1 %2\".")
- .arg(_item->_httpErrorCode)
- .arg(_job->reply()->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString()));
+ tr("Wrong HTTP code returned by server. Expected 201, but received \"%1 %2\".")
+ .arg(_item->_httpErrorCode)
+ .arg(_job->reply()->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString()));
return;
}
// while files are still uploading
propagator()->_activeJobList.append(this);
auto propfindJob = new PropfindJob(_job->account(), _job->path(), this);
- propfindJob->setProperties(QList<QByteArray>() << "getetag" << "http://owncloud.org/ns:id");
+ propfindJob->setProperties(QList<QByteArray>() << "getetag"
+ << "http://owncloud.org/ns:id");
QObject::connect(propfindJob, SIGNAL(result(QVariantMap)), this, SLOT(propfindResult(QVariantMap)));
QObject::connect(propfindJob, SIGNAL(finishedWithError()), this, SLOT(propfindError()));
propfindJob->start();
done(SyncFileItem::Success);
}
-
-
-
}
-
* @brief The PropagateRemoteMkdir class
* @ingroup libsync
*/
-class PropagateRemoteMkdir : public PropagateItemJob {
+class PropagateRemoteMkdir : public PropagateItemJob
+{
Q_OBJECT
QPointer<AbstractNetworkJob> _job;
bool _deleteExisting;
friend class PropagateDirectory; // So it can access the _item;
public:
- PropagateRemoteMkdir (OwncloudPropagator* propagator,const SyncFileItemPtr& item)
- : PropagateItemJob(propagator, item), _deleteExisting(false) {}
+ PropagateRemoteMkdir(OwncloudPropagator *propagator, const SyncFileItemPtr &item)
+ : PropagateItemJob(propagator, item)
+ , _deleteExisting(false)
+ {
+ }
void start() Q_DECL_OVERRIDE;
void abort() Q_DECL_OVERRIDE;
void propfindError();
void success();
};
-
}
Q_LOGGING_CATEGORY(lcMoveJob, "sync.networkjob.move", QtInfoMsg)
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)
-{ }
-
-MoveJob::MoveJob(AccountPtr account, const QUrl& url, const QString &destination,
- QMap<QByteArray, QByteArray> extraHeaders, QObject* parent)
- : AbstractNetworkJob(account, QString(), parent), _destination(destination), _url(url)
+MoveJob::MoveJob(AccountPtr account, const QString &path,
+ const QString &destination, QObject *parent)
+ : AbstractNetworkJob(account, path, parent)
+ , _destination(destination)
+{
+}
+
+MoveJob::MoveJob(AccountPtr account, const QUrl &url, const QString &destination,
+ QMap<QByteArray, QByteArray> extraHeaders, QObject *parent)
+ : AbstractNetworkJob(account, QString(), parent)
+ , _destination(destination)
+ , _url(url)
, _extraHeaders(extraHeaders)
-{ }
+{
+}
void MoveJob::start()
{
QNetworkRequest req;
req.setRawHeader("Destination", QUrl::toPercentEncoding(_destination, "/"));
- for(auto it = _extraHeaders.constBegin(); it != _extraHeaders.constEnd(); ++it) {
+ for (auto it = _extraHeaders.constBegin(); it != _extraHeaders.constEnd(); ++it) {
req.setRawHeader(it.key(), it.value());
}
if (_url.isValid()) {
sendRequest("MOVE", makeDavUrl(path()), req);
}
- if( reply()->error() != QNetworkReply::NoError ) {
+ if (reply()->error() != QNetworkReply::NoError) {
qCWarning(lcPropagateRemoteMove) << " Network error: " << reply()->errorString();
}
AbstractNetworkJob::start();
bool MoveJob::finished()
{
qCInfo(lcMoveJob) << "MOVE of" << reply()->request().url() << "FINISHED WITH STATUS"
- << reply()->error()
- << (reply()->error() == QNetworkReply::NoError ? QLatin1String("") : errorString());
+ << reply()->error()
+ << (reply()->error() == QNetworkReply::NoError ? QLatin1String("") : errorString());
emit finishedSignal();
return true;
finalize();
return;
}
- if (_item->_file == QLatin1String("Shared") ) {
+ if (_item->_file == QLatin1String("Shared")) {
// Before owncloud 7, there was no permissions system. At the time all the shared files were
// in a directory called "Shared" and were not supposed to be moved, otherwise bad things happened
emit propagator()->touchedFile(originalFile);
emit propagator()->touchedFile(targetFile);
QString renameError;
- if( FileSystem::rename(targetFile, originalFile, &renameError) ) {
+ if (FileSystem::rename(targetFile, originalFile, &renameError)) {
done(SyncFileItem::NormalError, tr("This folder must not be renamed. It is renamed back to its original name."));
} else {
done(SyncFileItem::NormalError, tr("This folder must not be renamed. Please name it back to Shared."));
}
QString destination = QDir::cleanPath(propagator()->account()->url().path() + QLatin1Char('/')
- + propagator()->account()->davPath() + propagator()->_remoteFolder + _item->_renameTarget);
+ + propagator()->account()->davPath() + propagator()->_remoteFolder + _item->_renameTarget);
_job = new MoveJob(propagator()->account(),
- propagator()->_remoteFolder + _item->_file,
- destination, this);
+ propagator()->_remoteFolder + _item->_file,
+ destination, this);
connect(_job, SIGNAL(finishedSignal()), this, SLOT(slotMoveJobFinished()));
propagator()->_activeJobList.append(this);
_job->start();
-
}
void PropagateRemoteMove::abort()
{
- if (_job && _job->reply())
+ if (_job && _job->reply())
_job->reply()->abort();
}
_item->_httpErrorCode = _job->reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
if (err != QNetworkReply::NoError) {
-
- if( checkForProblemsWithShared(_item->_httpErrorCode,
+ if (checkForProblemsWithShared(_item->_httpErrorCode,
tr("The file was renamed but is part of a read only share. The original file was restored."))) {
return;
}
SyncFileItem::Status status = classifyError(err, _item->_httpErrorCode,
- &propagator()->_anotherSyncNeeded);
+ &propagator()->_anotherSyncNeeded);
done(status, _job->errorString());
return;
}
_item->_responseTimeStamp = _job->responseTimestamp();
- if (_item->_httpErrorCode != 201 ) {
+ if (_item->_httpErrorCode != 201) {
// Normally we expect "201 Created"
// If it is not the case, it might be because of a proxy or gateway intercepting the request, so we must
// throw an error.
done(SyncFileItem::NormalError,
- tr("Wrong HTTP code returned by server. Expected 201, but received \"%1 %2\".")
- .arg(_item->_httpErrorCode)
- .arg(_job->reply()->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString()));
+ tr("Wrong HTTP code returned by server. Expected 201, but received \"%1 %2\".")
+ .arg(_item->_httpErrorCode)
+ .arg(_job->reply()->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString()));
return;
}
finalize();
-
}
void PropagateRemoteMove::finalize()
{
SyncJournalFileRecord oldRecord =
- propagator()->_journal->getFileRecord(_item->_originalFile);
+ propagator()->_journal->getFileRecord(_item->_originalFile);
// if reading from db failed still continue hoping that deleteFileRecord
// reopens the db successfully.
// The db is only queried to transfer the content checksum from the old
}
return true;
}
-
}
-
* @brief The MoveJob class
* @ingroup libsync
*/
-class MoveJob : public AbstractNetworkJob {
+class MoveJob : public AbstractNetworkJob
+{
Q_OBJECT
const QString _destination;
const QUrl _url; // Only used (instead of path) when the constructor taking an URL is used
QMap<QByteArray, QByteArray> _extraHeaders;
+
public:
- explicit MoveJob(AccountPtr account, const QString& path, const QString &destination, QObject* parent = 0);
- explicit MoveJob(AccountPtr account, const QUrl& url, const QString &destination,
- QMap<QByteArray, QByteArray> _extraHeaders, QObject* parent = 0);
+ explicit MoveJob(AccountPtr account, const QString &path, const QString &destination, QObject *parent = 0);
+ explicit MoveJob(AccountPtr account, const QUrl &url, const QString &destination,
+ QMap<QByteArray, QByteArray> _extraHeaders, QObject *parent = 0);
void start() Q_DECL_OVERRIDE;
bool finished() Q_DECL_OVERRIDE;
* @brief The PropagateRemoteMove class
* @ingroup libsync
*/
-class PropagateRemoteMove : public PropagateItemJob {
+class PropagateRemoteMove : public PropagateItemJob
+{
Q_OBJECT
QPointer<MoveJob> _job;
+
public:
- PropagateRemoteMove (OwncloudPropagator* propagator,const SyncFileItemPtr& item)
- : PropagateItemJob(propagator, item) {}
+ PropagateRemoteMove(OwncloudPropagator *propagator, const SyncFileItemPtr &item)
+ : PropagateItemJob(propagator, item)
+ {
+ }
void start() Q_DECL_OVERRIDE;
void abort() Q_DECL_OVERRIDE;
JobParallelism parallelism() Q_DECL_OVERRIDE { return _item->_isDirectory ? WaitForFinished : FullParallelism; }
void slotMoveJobFinished();
void finalize();
};
-
}
* manager. If that delay between file-change notification and sync
* has passed, we should accept the file for upload here.
*/
-static bool fileIsStillChanging(const SyncFileItem & item)
+static bool fileIsStillChanging(const SyncFileItem &item)
{
const QDateTime modtime = Utility::qDateTimeFromTime_t(item._modtime);
const qint64 msSinceMod = modtime.msecsTo(QDateTime::currentDateTime());
return msSinceMod < SyncEngine::minimumFileAgeForUpload
- // if the mtime is too much in the future we *do* upload the file
- && msSinceMod > -10000;
+ // if the mtime is too much in the future we *do* upload the file
+ && msSinceMod > -10000;
}
PUTFileJob::~PUTFileJob()
setReply(0);
}
-void PUTFileJob::start() {
+void PUTFileJob::start()
+{
QNetworkRequest req;
- for(QMap<QByteArray, QByteArray>::const_iterator it = _headers.begin(); it != _headers.end(); ++it) {
+ for (QMap<QByteArray, QByteArray>::const_iterator it = _headers.begin(); it != _headers.end(); ++it) {
req.setRawHeader(it.key(), it.value());
}
sendRequest("PUT", makeDavUrl(path()), req, _device);
}
- if( reply()->error() != QNetworkReply::NoError ) {
+ if (reply()->error() != QNetworkReply::NoError) {
qCWarning(lcPutJob) << " Network error: " << reply()->errorString();
}
- connect(reply(), SIGNAL(uploadProgress(qint64,qint64)), this, SIGNAL(uploadProgress(qint64,qint64)));
+ connect(reply(), SIGNAL(uploadProgress(qint64, qint64)), this, SIGNAL(uploadProgress(qint64, qint64)));
connect(this, SIGNAL(networkActivity()), account().data(), SIGNAL(propagatorNetworkActivity()));
- // For Qt versions not including https://codereview.qt-project.org/110150
- // Also do the runtime check if compiled with an old Qt but running with fixed one.
- // (workaround disabled on windows and mac because the binaries we ship have patched qt)
+// For Qt versions not including https://codereview.qt-project.org/110150
+// Also do the runtime check if compiled with an old Qt but running with fixed one.
+// (workaround disabled on windows and mac because the binaries we ship have patched qt)
#if QT_VERSION < QT_VERSION_CHECK(5, 4, 2) && !defined Q_OS_WIN && !defined Q_OS_MAC
if (QLatin1String(qVersion()) < QLatin1String("5.4.2"))
connect(_device, SIGNAL(wasReset()), this, SLOT(slotSoftAbort()));
}
#if QT_VERSION < QT_VERSION_CHECK(5, 4, 2)
-void PUTFileJob::slotSoftAbort() {
+void PUTFileJob::slotSoftAbort()
+{
reply()->setProperty(owncloudShouldSoftCancelPropertyName, true);
reply()->abort();
}
{
setTimeout(120 * 1000);
QUrl accountUrl = account()->url();
- QUrl finalUrl = QUrl::fromUserInput(accountUrl.scheme() + QLatin1String("://") + accountUrl.authority()
+ QUrl finalUrl = QUrl::fromUserInput(accountUrl.scheme() + QLatin1String("://") + accountUrl.authority()
+ (path().startsWith('/') ? QLatin1String("") : QLatin1String("/")) + path());
sendRequest("GET", finalUrl);
- connect(reply(), SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(resetTimeout()));
+ connect(reply(), SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(resetTimeout()));
AbstractNetworkJob::start();
}
if (_item->_status == SyncFileItem::FatalError || _item->_httpErrorCode >= 400) {
if (_item->_status != SyncFileItem::FatalError
- && _item->_httpErrorCode != 503) {
+ && _item->_httpErrorCode != 503) {
SyncJournalDb::PollInfo info;
info._file = _item->_file;
// no info._url removes it from the database
_journal->setPollInfo(info);
_journal->commit("remove poll info");
-
}
emit finishedSignal();
return true;
}
// Check if the specific file can be accessed
- if( propagator()->hasCaseClashAccessibilityProblem(_item->_file) ) {
- done( SyncFileItem::NormalError, tr("File %1 cannot be uploaded because another file with the same name, differing only in case, exists")
- .arg(QDir::toNativeSeparators(_item->_file)) );
+ if (propagator()->hasCaseClashAccessibilityProblem(_item->_file)) {
+ done(SyncFileItem::NormalError, tr("File %1 cannot be uploaded because another file with the same name, differing only in case, exists").arg(QDir::toNativeSeparators(_item->_file)));
return;
}
}
auto job = new DeleteJob(propagator()->account(),
- propagator()->_remoteFolder + _item->_file,
- this);
+ propagator()->_remoteFolder + _item->_file,
+ this);
_jobs.append(job);
connect(job, SIGNAL(finishedSignal()), SLOT(slotComputeContentChecksum()));
- connect(job, SIGNAL(destroyed(QObject*)), SLOT(slotJobDestroyed(QObject*)));
+ connect(job, SIGNAL(destroyed(QObject *)), SLOT(slotJobDestroyed(QObject *)));
job->start();
}
// Maybe the discovery already computed the checksum?
if (_item->_contentChecksumType == checksumType
- && !_item->_contentChecksum.isEmpty()) {
+ && !_item->_contentChecksum.isEmpty()) {
slotComputeTransmissionChecksum(checksumType, _item->_contentChecksum);
return;
}
auto computeChecksum = new ComputeChecksum(this);
computeChecksum->setChecksumType(checksumType);
- connect(computeChecksum, SIGNAL(done(QByteArray,QByteArray)),
- SLOT(slotComputeTransmissionChecksum(QByteArray,QByteArray)));
- connect(computeChecksum, SIGNAL(done(QByteArray,QByteArray)),
- computeChecksum, SLOT(deleteLater()));
+ connect(computeChecksum, SIGNAL(done(QByteArray, QByteArray)),
+ SLOT(slotComputeTransmissionChecksum(QByteArray, QByteArray)));
+ connect(computeChecksum, SIGNAL(done(QByteArray, QByteArray)),
+ computeChecksum, SLOT(deleteLater()));
computeChecksum->start(filePath);
}
-void PropagateUploadFileCommon::slotComputeTransmissionChecksum(const QByteArray& contentChecksumType, const QByteArray& contentChecksum)
+void PropagateUploadFileCommon::slotComputeTransmissionChecksum(const QByteArray &contentChecksumType, const QByteArray &contentChecksum)
{
_item->_contentChecksum = contentChecksum;
_item->_contentChecksumType = contentChecksumType;
// Reuse the content checksum as the transmission checksum if possible
const auto supportedTransmissionChecksums =
- propagator()->account()->capabilities().supportedChecksumTypes();
+ propagator()->account()->capabilities().supportedChecksumTypes();
if (supportedTransmissionChecksums.contains(contentChecksumType)) {
slotStartUpload(contentChecksumType, contentChecksum);
return;
computeChecksum->setChecksumType(QByteArray());
}
- connect(computeChecksum, SIGNAL(done(QByteArray,QByteArray)),
- SLOT(slotStartUpload(QByteArray,QByteArray)));
- connect(computeChecksum, SIGNAL(done(QByteArray,QByteArray)),
- computeChecksum, SLOT(deleteLater()));
+ connect(computeChecksum, SIGNAL(done(QByteArray, QByteArray)),
+ SLOT(slotStartUpload(QByteArray, QByteArray)));
+ connect(computeChecksum, SIGNAL(done(QByteArray, QByteArray)),
+ computeChecksum, SLOT(deleteLater()));
const QString filePath = propagator()->getFilePath(_item->_file);
computeChecksum->start(filePath);
}
-void PropagateUploadFileCommon::slotStartUpload(const QByteArray& transmissionChecksumType, const QByteArray& transmissionChecksum)
+void PropagateUploadFileCommon::slotStartUpload(const QByteArray &transmissionChecksumType, const QByteArray &transmissionChecksum)
{
// Remove ourselfs from the list of active job, before any posible call to done()
// When we start chunks, we will add it again, once for every chunks.
_transmissionChecksum = transmissionChecksum;
_transmissionChecksumType = transmissionChecksumType;
- if (_item->_contentChecksum.isEmpty() && _item->_contentChecksumType.isEmpty()) {
+ if (_item->_contentChecksum.isEmpty() && _item->_contentChecksumType.isEmpty()) {
// If the _contentChecksum was not set, reuse the transmission checksum as the content checksum.
_item->_contentChecksum = transmissionChecksum;
_item->_contentChecksumType = transmissionChecksumType;
// have been changed again, so better check again here.
_item->_modtime = FileSystem::getModTime(fullFilePath);
- if( prevModtime != _item->_modtime ) {
+ if (prevModtime != _item->_modtime) {
propagator()->_anotherSyncNeeded = true;
done(SyncFileItem::SoftError, tr("Local file changed during syncing. It will be resumed."));
return;
}
UploadDevice::UploadDevice(BandwidthManager *bwm)
- : _read(0),
- _bandwidthManager(bwm),
- _bandwidthQuota(0),
- _readWithProgress(0),
- _bandwidthLimited(false), _choked(false)
+ : _read(0)
+ , _bandwidthManager(bwm)
+ , _bandwidthQuota(0)
+ , _readWithProgress(0)
+ , _bandwidthLimited(false)
+ , _choked(false)
{
_bandwidthManager->registerUploadDevice(this);
}
-UploadDevice::~UploadDevice() {
+UploadDevice::~UploadDevice()
+{
if (_bandwidthManager) {
_bandwidthManager->unregisterUploadDevice(this);
}
}
-bool UploadDevice::prepareAndOpen(const QString& fileName, qint64 start, qint64 size)
+bool UploadDevice::prepareAndOpen(const QString &fileName, qint64 start, qint64 size)
{
_data.clear();
_read = 0;
}
-qint64 UploadDevice::writeData(const char* , qint64 ) {
+qint64 UploadDevice::writeData(const char *, qint64)
+{
ASSERT(false, "write to read only device");
return 0;
}
-qint64 UploadDevice::readData(char* data, qint64 maxlen) {
+qint64 UploadDevice::readData(char *data, qint64 maxlen)
+{
if (_data.size() - _read <= 0) {
// at end
if (_bandwidthManager) {
}
if (isBandwidthLimited()) {
maxlen = qMin(maxlen, _bandwidthQuota);
- if (maxlen <= 0) { // no quota
+ if (maxlen <= 0) { // no quota
return 0;
}
_bandwidthQuota -= maxlen;
}
- std::memcpy(data, _data.data()+_read, maxlen);
+ std::memcpy(data, _data.data() + _read, maxlen);
_read += maxlen;
return maxlen;
}
_readWithProgress = sent;
}
-bool UploadDevice::atEnd() const {
+bool UploadDevice::atEnd() const
+{
return _read >= _data.size();
}
-qint64 UploadDevice::size() const{
+qint64 UploadDevice::size() const
+{
return _data.size();
}
}
// random access, we can seek
-bool UploadDevice::isSequential() const{
+bool UploadDevice::isSequential() const
+{
return false;
}
-bool UploadDevice::seek ( qint64 pos ) {
- if (! QIODevice::seek(pos)) {
+bool UploadDevice::seek(qint64 pos)
+{
+ if (!QIODevice::seek(pos)) {
return false;
}
if (pos < 0 || pos > _data.size()) {
return true;
}
-void UploadDevice::giveBandwidthQuota(qint64 bwq) {
+void UploadDevice::giveBandwidthQuota(qint64 bwq)
+{
if (!atEnd()) {
_bandwidthQuota = bwq;
QMetaObject::invokeMethod(this, "readyRead", Qt::QueuedConnection); // tell QNAM that we have quota
}
}
-void UploadDevice::setBandwidthLimited(bool b) {
+void UploadDevice::setBandwidthLimited(bool b)
+{
_bandwidthLimited = b;
QMetaObject::invokeMethod(this, "readyRead", Qt::QueuedConnection);
}
-void UploadDevice::setChoked(bool b) {
+void UploadDevice::setChoked(bool b)
+{
_choked = b;
if (!_choked) {
QMetaObject::invokeMethod(this, "readyRead", Qt::QueuedConnection);
}
}
-void PropagateUploadFileCommon::startPollJob(const QString& path)
+void PropagateUploadFileCommon::startPollJob(const QString &path)
{
- PollJob* job = new PollJob(propagator()->account(), path, _item,
- propagator()->_journal, propagator()->_localDir, this);
+ PollJob *job = new PollJob(propagator()->account(), path, _item,
+ propagator()->_journal, propagator()->_localDir, this);
connect(job, SIGNAL(finishedSignal()), SLOT(slotPollFinished()));
SyncJournalDb::PollInfo info;
info._file = _item->_file;
void PropagateUploadFileCommon::checkResettingErrors()
{
if (_item->_httpErrorCode == 412
- || propagator()->account()->capabilities().httpErrorCodesThatResetFailingChunkedUploads()
- .contains(_item->_httpErrorCode)) {
+ || propagator()->account()->capabilities().httpErrorCodesThatResetFailingChunkedUploads().contains(_item->_httpErrorCode)) {
auto uploadInfo = propagator()->_journal->getUploadInfo(_item->_file);
uploadInfo._errorCount += 1;
if (uploadInfo._errorCount > 3) {
qCInfo(lcPropagateUpload) << "Reset transfer of" << _item->_file
- << "due to repeated error" << _item->_httpErrorCode;
+ << "due to repeated error" << _item->_httpErrorCode;
uploadInfo = SyncJournalDb::UploadInfo();
} else {
qCInfo(lcPropagateUpload) << "Error count for maybe-reset error" << _item->_httpErrorCode
- << "on file" << _item->_file
- << "is" << uploadInfo._errorCount;
+ << "on file" << _item->_file
+ << "is" << uploadInfo._errorCount;
}
propagator()->_journal->setUploadInfo(_item->_file, uploadInfo);
propagator()->_journal->commit("Upload info");
}
}
-void PropagateUploadFileCommon::slotJobDestroyed(QObject* job)
+void PropagateUploadFileCommon::slotJobDestroyed(QObject *job)
{
- _jobs.erase(std::remove(_jobs.begin(), _jobs.end(), job) , _jobs.end());
+ _jobs.erase(std::remove(_jobs.begin(), _jobs.end(), job), _jobs.end());
}
void PropagateUploadFileCommon::abort()
{
- foreach(auto *job, _jobs) {
+ foreach (auto *job, _jobs) {
if (job->reply()) {
job->reply()->abort();
}
headers["Content-Type"] = "application/octet-stream";
headers["X-OC-Mtime"] = QByteArray::number(qint64(_item->_modtime));
- if(_item->_file.contains(".sys.admin#recall#")) {
+ if (_item->_file.contains(".sys.admin#recall#")) {
// This is a file recall triggered by the admin. Note: the
// recall list file created by the admin and downloaded by the
// client (.sys.admin#recall#) also falls into this category
}
if (!_item->_etag.isEmpty() && _item->_etag != "empty_etag"
- && _item->_instruction != CSYNC_INSTRUCTION_NEW // On new files never send a If-Match
+ && _item->_instruction != CSYNC_INSTRUCTION_NEW // On new files never send a If-Match
&& _item->_instruction != CSYNC_INSTRUCTION_TYPE_CHANGE
- && !_deleteExisting
- ) {
+ && !_deleteExisting) {
// We add quotes because the owncloud server always adds quotes around the etag, and
// csync_owncloud.c's owncloud_file_id always strips the quotes.
headers["If-Match"] = '"' + _item->_etag + '"';
done(SyncFileItem::Success);
}
-
-
}
* @brief The UploadDevice class
* @ingroup libsync
*/
-class UploadDevice : public QIODevice {
+class UploadDevice : public QIODevice
+{
Q_OBJECT
public:
UploadDevice(BandwidthManager *bwm);
~UploadDevice();
/** Reads the data from the file and opens the device */
- bool prepareAndOpen(const QString& fileName, qint64 start, qint64 size);
+ bool prepareAndOpen(const QString &fileName, qint64 start, qint64 size);
- qint64 writeData(const char* , qint64 ) Q_DECL_OVERRIDE;
- qint64 readData(char* data, qint64 maxlen) Q_DECL_OVERRIDE;
+ qint64 writeData(const char *, qint64) Q_DECL_OVERRIDE;
+ qint64 readData(char *data, qint64 maxlen) Q_DECL_OVERRIDE;
bool atEnd() const Q_DECL_OVERRIDE;
qint64 size() const Q_DECL_OVERRIDE;
qint64 bytesAvailable() const Q_DECL_OVERRIDE;
bool isSequential() const Q_DECL_OVERRIDE;
- bool seek ( qint64 pos ) Q_DECL_OVERRIDE;
+ bool seek(qint64 pos) Q_DECL_OVERRIDE;
#if QT_VERSION < QT_VERSION_CHECK(5, 4, 2)
- bool reset() Q_DECL_OVERRIDE { emit wasReset(); return QIODevice::reset(); }
+ bool reset() Q_DECL_OVERRIDE
+ {
+ emit wasReset();
+ return QIODevice::reset();
+ }
#endif
void setBandwidthLimited(bool);
#endif
private:
-
// The file data
QByteArray _data;
// Position in the data
* @brief The PUTFileJob class
* @ingroup libsync
*/
-class PUTFileJob : public AbstractNetworkJob {
+class PUTFileJob : public AbstractNetworkJob
+{
Q_OBJECT
private:
- QIODevice* _device;
+ QIODevice *_device;
QMap<QByteArray, QByteArray> _headers;
QString _errorString;
QUrl _url;
public:
// Takes ownership of the device
- explicit PUTFileJob(AccountPtr account, const QString& path, QIODevice *device,
- const QMap<QByteArray, QByteArray> &headers, int chunk, QObject* parent = 0)
- : AbstractNetworkJob(account, path, parent), _device(device), _headers(headers), _chunk(chunk)
+ explicit PUTFileJob(AccountPtr account, const QString &path, QIODevice *device,
+ const QMap<QByteArray, QByteArray> &headers, int chunk, QObject *parent = 0)
+ : AbstractNetworkJob(account, path, parent)
+ , _device(device)
+ , _headers(headers)
+ , _chunk(chunk)
{
_device->setParent(this);
}
- explicit PUTFileJob(AccountPtr account, const QUrl& url, QIODevice *device,
- const QMap<QByteArray, QByteArray> &headers, int chunk, QObject* parent = 0)
- : AbstractNetworkJob(account, QString(), parent), _device(device), _headers(headers)
- , _url(url), _chunk(chunk)
+ explicit PUTFileJob(AccountPtr account, const QUrl &url, QIODevice *device,
+ const QMap<QByteArray, QByteArray> &headers, int chunk, QObject *parent = 0)
+ : AbstractNetworkJob(account, QString(), parent)
+ , _device(device)
+ , _headers(headers)
+ , _url(url)
+ , _chunk(chunk)
{
_device->setParent(this);
}
virtual void start() Q_DECL_OVERRIDE;
- virtual bool finished() Q_DECL_OVERRIDE {
+ virtual bool finished() Q_DECL_OVERRIDE
+ {
qCInfo(lcPutJob) << "PUT of" << reply()->request().url().toString() << "FINISHED WITH STATUS"
- << reply()->error()
- << (reply()->error() == QNetworkReply::NoError ? QLatin1String("") : errorString())
- << reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute)
- << reply()->attribute(QNetworkRequest::HttpReasonPhraseAttribute);
+ << reply()->error()
+ << (reply()->error() == QNetworkReply::NoError ? QLatin1String("") : errorString())
+ << reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute)
+ << reply()->attribute(QNetworkRequest::HttpReasonPhraseAttribute);
emit finishedSignal();
return true;
}
- QString errorString() {
+ QString errorString()
+ {
return _errorString.isEmpty() ? AbstractNetworkJob::errorString() : _errorString;
}
- quint64 msSinceStart() const {
+ quint64 msSinceStart() const
+ {
return _requestTimer.elapsed();
}
signals:
void finishedSignal();
- void uploadProgress(qint64,qint64);
+ void uploadProgress(qint64, qint64);
private slots:
#if QT_VERSION < 0x050402
* replies with an etag. https://github.com/owncloud/core/issues/12097
* @ingroup libsync
*/
-class PollJob : public AbstractNetworkJob {
+class PollJob : public AbstractNetworkJob
+{
Q_OBJECT
SyncJournalDb *_journal;
QString _localPath;
+
public:
SyncFileItemPtr _item;
// Takes ownership of the device
explicit PollJob(AccountPtr account, const QString &path, const SyncFileItemPtr &item,
- SyncJournalDb *journal, const QString &localPath, QObject *parent)
- : AbstractNetworkJob(account, path, parent), _journal(journal), _localPath(localPath), _item(item) {}
+ SyncJournalDb *journal, const QString &localPath, QObject *parent)
+ : AbstractNetworkJob(account, path, parent)
+ , _journal(journal)
+ , _localPath(localPath)
+ , _item(item)
+ {
+ }
void start() Q_DECL_OVERRIDE;
bool finished() Q_DECL_OVERRIDE;
* v
* finalize() or abortWithError() or startPollJob()
*/
-class PropagateUploadFileCommon : public PropagateItemJob {
+class PropagateUploadFileCommon : public PropagateItemJob
+{
Q_OBJECT
protected:
- QVector<AbstractNetworkJob*> _jobs; /// network jobs that are currently in transit
+ QVector<AbstractNetworkJob *> _jobs; /// network jobs that are currently in transit
bool _finished BITFIELD(1); /// Tells that all the jobs have been finished
bool _deleteExisting BITFIELD(1);
- // measure the performance of checksum calc and upload
+// measure the performance of checksum calc and upload
#ifdef WITH_TESTING
Utility::StopWatch _stopWatch;
#endif
QByteArray _transmissionChecksumType;
public:
- PropagateUploadFileCommon(OwncloudPropagator* propagator,const SyncFileItemPtr& item)
- : PropagateItemJob(propagator, item), _finished(false), _deleteExisting(false) {}
+ PropagateUploadFileCommon(OwncloudPropagator *propagator, const SyncFileItemPtr &item)
+ : PropagateItemJob(propagator, item)
+ , _finished(false)
+ , _deleteExisting(false)
+ {
+ }
/**
* Whether an existing entity with the same name may be deleted before
private slots:
void slotComputeContentChecksum();
// Content checksum computed, compute the transmission checksum
- void slotComputeTransmissionChecksum(const QByteArray& contentChecksumType, const QByteArray& contentChecksum);
+ void slotComputeTransmissionChecksum(const QByteArray &contentChecksumType, const QByteArray &contentChecksum);
// transmission checksum computed, prepare the upload
- void slotStartUpload(const QByteArray& transmissionChecksumType, const QByteArray& transmissionChecksum);
+ void slotStartUpload(const QByteArray &transmissionChecksumType, const QByteArray &transmissionChecksum);
+
public:
virtual void doStartUpload() = 0;
- void startPollJob(const QString& path);
+ void startPollJob(const QString &path);
void finalize();
void abortWithError(SyncFileItem::Status status, const QString &error);
// Bases headers that need to be sent with every chunk
QMap<QByteArray, QByteArray> headers();
-
};
/**
* Propagation job, impementing the old chunking agorithm
*
*/
-class PropagateUploadFileV1 : public PropagateUploadFileCommon {
+class PropagateUploadFileV1 : public PropagateUploadFileCommon
+{
Q_OBJECT
private:
public:
- PropagateUploadFileV1(OwncloudPropagator* propagator,const SyncFileItemPtr& item) :
- PropagateUploadFileCommon(propagator,item) {}
+ PropagateUploadFileV1(OwncloudPropagator *propagator, const SyncFileItemPtr &item)
+ : PropagateUploadFileCommon(propagator, item)
+ {
+ }
void doStartUpload() Q_DECL_OVERRIDE;
private slots:
void startNextChunk();
void slotPutFinished();
- void slotUploadProgress(qint64,qint64);
+ void slotUploadProgress(qint64, qint64);
};
/**
* Propagation job, impementing the new chunking agorithm
*
*/
-class PropagateUploadFileNG : public PropagateUploadFileCommon {
+class PropagateUploadFileNG : public PropagateUploadFileCommon
+{
Q_OBJECT
private:
quint64 _sent; /// amount of data (bytes) that was already sent
// Map chunk number with its size from the PROPFIND on resume.
// (Only used from slotPropfindIterate/slotPropfindFinished because the LsColJob use signals to report data.)
- struct ServerChunkInfo { quint64 size; QString originalName; };
+ struct ServerChunkInfo
+ {
+ quint64 size;
+ QString originalName;
+ };
QMap<int, ServerChunkInfo> _serverChunks;
/**
QUrl chunkUrl(int chunk = -1);
public:
- PropagateUploadFileNG(OwncloudPropagator* propagator,const SyncFileItemPtr& item) :
- PropagateUploadFileCommon(propagator,item), _currentChunkSize(0) {}
+ PropagateUploadFileNG(OwncloudPropagator *propagator, const SyncFileItemPtr &item)
+ : PropagateUploadFileCommon(propagator, item)
+ , _currentChunkSize(0)
+ {
+ }
void doStartUpload() Q_DECL_OVERRIDE;
private slots:
void slotPropfindFinished();
void slotPropfindFinishedWithError();
- void slotPropfindIterate(const QString &name, const QMap<QString,QString> &properties);
+ void slotPropfindIterate(const QString &name, const QMap<QString, QString> &properties);
void slotDeleteJobFinished();
void slotMkColFinished(QNetworkReply::NetworkError);
void slotPutFinished();
void slotMoveJobFinished();
- void slotUploadProgress(qint64,qint64);
+ void slotUploadProgress(qint64, qint64);
};
-
-
}
-
propagator()->_activeJobList.append(this);
const SyncJournalDb::UploadInfo progressInfo = propagator()->_journal->getUploadInfo(_item->_file);
- if (progressInfo._valid && Utility::qDateTimeToTime_t(progressInfo._modtime) == _item->_modtime ) {
+ if (progressInfo._valid && Utility::qDateTimeToTime_t(progressInfo._modtime) == _item->_modtime) {
_transferId = progressInfo._transferid;
auto url = chunkUrl();
auto job = new LsColJob(propagator()->account(), url, this);
_jobs.append(job);
- job->setProperties(QList<QByteArray>() << "resourcetype" << "getcontentlength");
+ job->setProperties(QList<QByteArray>() << "resourcetype"
+ << "getcontentlength");
connect(job, SIGNAL(finishedWithoutError()), this, SLOT(slotPropfindFinished()));
- connect(job, SIGNAL(finishedWithError(QNetworkReply*)),
- this, SLOT(slotPropfindFinishedWithError()));
- connect(job, SIGNAL(destroyed(QObject*)), this, SLOT(slotJobDestroyed(QObject*)));
- connect(job, SIGNAL(directoryListingIterated(QString,QMap<QString,QString>)),
- this, SLOT(slotPropfindIterate(QString,QMap<QString,QString>)));
+ connect(job, SIGNAL(finishedWithError(QNetworkReply *)),
+ this, SLOT(slotPropfindFinishedWithError()));
+ connect(job, SIGNAL(destroyed(QObject *)), this, SLOT(slotJobDestroyed(QObject *)));
+ connect(job, SIGNAL(directoryListingIterated(QString, QMap<QString, QString>)),
+ this, SLOT(slotPropfindIterate(QString, QMap<QString, QString>)));
job->start();
return;
} else if (progressInfo._valid) {
startNewUpload();
}
-void PropagateUploadFileNG::slotPropfindIterate(const QString &name, const QMap<QString,QString> &properties)
+void PropagateUploadFileNG::slotPropfindIterate(const QString &name, const QMap<QString, QString> &properties)
{
if (name == chunkUrl().path()) {
return; // skip the info about the path itself
}
bool ok = false;
- QString chunkName = name.mid(name.lastIndexOf('/')+1);
+ QString chunkName = name.mid(name.lastIndexOf('/') + 1);
auto chunkId = chunkName.toUInt(&ok);
if (ok) {
ServerChunkInfo chunkinfo = { properties["getcontentlength"].toULongLong(), chunkName };
// 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.
qCCritical(lcPropagateUpload) << "Inconsistency while resuming " << _item->_file
- << ": the size on the server (" << _sent << ") is bigger than the size of the file ("
- << _item->_size << ")";
+ << ": the size on the server (" << _sent << ") is bigger than the size of the file ("
+ << _item->_size << ")";
startNewUpload();
return;
}
- qCInfo(lcPropagateUpload) << "Resuming "<< _item->_file << " from chunk " << _currentChunk << "; sent ="<< _sent;
+ qCInfo(lcPropagateUpload) << "Resuming " << _item->_file << " from chunk " << _currentChunk << "; sent =" << _sent;
if (!_serverChunks.isEmpty()) {
qCInfo(lcPropagateUpload) << "To Delete" << _serverChunks.keys();
}
-
void PropagateUploadFileNG::startNewUpload()
{
ASSERT(propagator()->_activeJobList.count(this) == 1);
SyncJournalDb::UploadInfo pi;
pi._valid = true;
pi._transferid = _transferId;
- pi._modtime = Utility::qDateTimeFromTime_t(_item->_modtime);
+ pi._modtime = Utility::qDateTimeFromTime_t(_item->_modtime);
propagator()->_journal->setUploadInfo(_item->_file, pi);
propagator()->_journal->commit("Upload info");
QMap<QByteArray, QByteArray> headers;
auto job = new MkColJob(propagator()->account(), chunkUrl(), headers, this);
connect(job, SIGNAL(finished(QNetworkReply::NetworkError)),
- this, SLOT(slotMkColFinished(QNetworkReply::NetworkError)));
- connect(job, SIGNAL(destroyed(QObject*)), this, SLOT(slotJobDestroyed(QObject*)));
+ this, SLOT(slotMkColFinished(QNetworkReply::NetworkError)));
+ connect(job, SIGNAL(destroyed(QObject *)), this, SLOT(slotJobDestroyed(QObject *)));
job->start();
}
if (err != QNetworkReply::NoError || _item->_httpErrorCode != 201) {
SyncFileItem::Status status = classifyError(err, _item->_httpErrorCode,
- &propagator()->_anotherSyncNeeded);
+ &propagator()->_anotherSyncNeeded);
abortWithError(status, job->errorStringParsingBody());
return;
}
// "If-Match applies to the source, but we are interested in comparing the etag of the destination
auto ifMatch = headers.take("If-Match");
if (!ifMatch.isEmpty()) {
- headers["If"] = "<" + destination.toUtf8() + "> ([" + ifMatch + "])";
+ headers["If"] = "<" + destination.toUtf8() + "> ([" + ifMatch + "])";
}
if (!_transmissionChecksumType.isEmpty()) {
headers[checkSumHeaderC] = makeChecksumHeader(
headers["OC-Total-Length"] = QByteArray::number(fileSize);
auto job = new MoveJob(propagator()->account(), Utility::concatUrlPath(chunkUrl(), "/.file"),
- destination, headers, this);
+ destination, headers, this);
_jobs.append(job);
connect(job, SIGNAL(finishedSignal()), this, SLOT(slotMoveJobFinished()));
- connect(job, SIGNAL(destroyed(QObject*)), this, SLOT(slotJobDestroyed(QObject*)));
+ connect(job, SIGNAL(destroyed(QObject *)), this, SLOT(slotJobDestroyed(QObject *)));
propagator()->_activeJobList.append(this);
job->start();
return;
auto device = new UploadDevice(&propagator()->_bandwidthManager);
const QString fileName = propagator()->getFilePath(_item->_file);
- if (! device->prepareAndOpen(fileName, _sent, _currentChunkSize)) {
+ if (!device->prepareAndOpen(fileName, _sent, _currentChunkSize)) {
qCWarning(lcPropagateUpload) << "Could not prepare upload device: " << device->errorString();
// If the file is currently locked, we want to retry the sync
emit propagator()->seenLockedFile(fileName);
}
// Soft error because this is likely caused by the user modifying his files while syncing
- abortWithError( SyncFileItem::SoftError, device->errorString() );
+ abortWithError(SyncFileItem::SoftError, device->errorString());
return;
}
QUrl url = chunkUrl(_currentChunk);
// job takes ownership of device via a QScopedPointer. Job deletes itself when finishing
- PUTFileJob* job = new PUTFileJob(propagator()->account(), url, device, headers, _currentChunk, this);
+ PUTFileJob *job = new PUTFileJob(propagator()->account(), url, device, headers, _currentChunk, this);
_jobs.append(job);
connect(job, SIGNAL(finishedSignal()), this, SLOT(slotPutFinished()));
- connect(job, SIGNAL(uploadProgress(qint64,qint64)),
- this, SLOT(slotUploadProgress(qint64,qint64)));
- connect(job, SIGNAL(uploadProgress(qint64,qint64)),
- device, SLOT(slotJobUploadProgress(qint64,qint64)));
- connect(job, SIGNAL(destroyed(QObject*)), this, SLOT(slotJobDestroyed(QObject*)));
+ connect(job, SIGNAL(uploadProgress(qint64, qint64)),
+ this, SLOT(slotUploadProgress(qint64, qint64)));
+ connect(job, SIGNAL(uploadProgress(qint64, qint64)),
+ device, SLOT(slotJobUploadProgress(qint64, qint64)));
+ connect(job, SIGNAL(destroyed(QObject *)), this, SLOT(slotJobDestroyed(QObject *)));
job->start();
propagator()->_activeJobList.append(this);
_currentChunk++;
// FIXME! parallel chunk?
-
}
void PropagateUploadFileNG::slotPutFinished()
checkResettingErrors();
SyncFileItem::Status status = classifyError(err, _item->_httpErrorCode,
- &propagator()->_anotherSyncNeeded);
+ &propagator()->_anotherSyncNeeded);
abortWithError(status, errorString);
return;
}
double uploadTime = job->msSinceStart();
auto predictedGoodSize = static_cast<quint64>(
- _currentChunkSize / uploadTime * targetDuration);
+ _currentChunkSize / uploadTime * targetDuration);
// The whole targeting is heuristic. The predictedGoodSize will fluctuate
// quite a bit because of external factors (like available bandwidth)
quint64 targetSize = (propagator()->_chunkSize + predictedGoodSize) / 2;
propagator()->_chunkSize = qBound(
- propagator()->syncOptions()._minChunkSize,
- targetSize,
- propagator()->syncOptions()._maxChunkSize);
+ propagator()->syncOptions()._minChunkSize,
+ targetSize,
+ propagator()->syncOptions()._maxChunkSize);
qCInfo(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";
+ << "ms, desired is" << targetDuration << "ms, expected good chunk size is"
+ << predictedGoodSize << "bytes and nudged next chunk size to "
+ << propagator()->_chunkSize << "bytes";
}
bool finished = _sent == _item->_size;
// Check if the file still exists
const QString fullFilePath(propagator()->getFilePath(_item->_file));
- if( !FileSystem::fileExists(fullFilePath) ) {
+ if (!FileSystem::fileExists(fullFilePath)) {
if (!finished) {
abortWithError(SyncFileItem::SoftError, tr("The local file was removed during sync."));
return;
}
// Check whether the file changed since discovery.
- if (! FileSystem::verifyFileUnchanged(fullFilePath, _item->_size, _item->_modtime)) {
+ if (!FileSystem::verifyFileUnchanged(fullFilePath, _item->_size, _item->_modtime)) {
propagator()->_anotherSyncNeeded = true;
- if( !finished ) {
+ if (!finished) {
abortWithError(SyncFileItem::SoftError, tr("Local file changed during sync."));
return;
}
checkResettingErrors();
SyncFileItem::Status status = classifyError(err, _item->_httpErrorCode,
- &propagator()->_anotherSyncNeeded);
+ &propagator()->_anotherSyncNeeded);
abortWithError(status, job->errorStringParsingBody());
return;
}
}
QByteArray fid = job->reply()->rawHeader("OC-FileID");
- if(fid.isEmpty()) {
+ if (fid.isEmpty()) {
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 ) {
+ if (!_item->_fileId.isEmpty() && _item->_fileId != fid) {
qCWarning(lcPropagateUpload) << "File ID changed!" << _item->_fileId << fid;
}
_item->_fileId = fid;
}
- _item->_etag = getEtagFromReply(job->reply());;
+ _item->_etag = getEtagFromReply(job->reply());
+ ;
if (_item->_etag.isEmpty()) {
qCWarning(lcPropagateUpload) << "Server did not return an ETAG" << _item->_file;
abortWithError(SyncFileItem::NormalError, tr("Missing ETag from server"));
// performance logging
quint64 duration = _stopWatch.stop();
qCDebug(lcPropagateUpload) << "*==* duration UPLOAD" << _item->_size
- << _stopWatch.durationOfLap(QLatin1String("ContentChecksum"))
- << _stopWatch.durationOfLap(QLatin1String("TransmissionChecksum"))
- << duration;
+ << _stopWatch.durationOfLap(QLatin1String("ContentChecksum"))
+ << _stopWatch.durationOfLap(QLatin1String("TransmissionChecksum"))
+ << duration;
// The job might stay alive for the whole sync, release this tiny bit of memory.
_stopWatch.reset();
#endif
}
propagator()->reportProgress(*_item, _sent + sent - total);
}
-
}
const SyncJournalDb::UploadInfo progressInfo = propagator()->_journal->getUploadInfo(_item->_file);
- if (progressInfo._valid && Utility::qDateTimeToTime_t(progressInfo._modtime) == _item->_modtime ) {
+ if (progressInfo._valid && Utility::qDateTimeToTime_t(progressInfo._modtime) == _item->_modtime) {
_startChunk = progressInfo._chunk;
_transferId = progressInfo._transferid;
qCInfo(lcPropagateUpload) << _item->_file << ": Resuming from chunk " << _startChunk;
if (propagator()->_abortRequested.fetchAndAddRelaxed(0))
return;
- if (! _jobs.isEmpty() && _currentChunk + _startChunk >= _chunkCount - 1) {
+ if (!_jobs.isEmpty() && _currentChunk + _startChunk >= _chunkCount - 1) {
// Don't do parallel upload of chunk if this might be the last chunk because the server cannot handle that
// https://github.com/owncloud/core/issues/11106
// We return now and when the _jobs are finished we will proceed with the last chunk
quint64 fileSize = _item->_size;
auto headers = PropagateUploadFileCommon::headers();
headers["OC-Total-Length"] = QByteArray::number(fileSize);
- headers["OC-Chunk-Size"]= QByteArray::number(quint64(chunkSize()));
+ headers["OC-Chunk-Size"] = QByteArray::number(quint64(chunkSize()));
QString path = _item->_file;
// XOR with chunk size to make sure everything goes well if chunk size changes between runs
uint transid = _transferId ^ chunkSize();
qCInfo(lcPropagateUpload) << "Upload chunk" << sendingChunk << "of" << _chunkCount << "transferid(remote)=" << transid;
- path += QString("-chunking-%1-%2-%3").arg(transid).arg(_chunkCount).arg(sendingChunk);
+ path += QString("-chunking-%1-%2-%3").arg(transid).arg(_chunkCount).arg(sendingChunk);
headers["OC-Chunked"] = "1";
currentChunkSize = chunkSize();
if (sendingChunk == _chunkCount - 1) { // last chunk
currentChunkSize = (fileSize % chunkSize());
- if( currentChunkSize == 0 ) { // if the last chunk pretends to be 0, its actually the full chunk size.
+ if (currentChunkSize == 0) { // if the last chunk pretends to be 0, its actually the full chunk size.
currentChunkSize = chunkSize();
}
isFinalChunk = true;
if (isFinalChunk && !_transmissionChecksumType.isEmpty()) {
headers[checkSumHeaderC] = makeChecksumHeader(
- _transmissionChecksumType, _transmissionChecksum);
+ _transmissionChecksumType, _transmissionChecksum);
}
const QString fileName = propagator()->getFilePath(_item->_file);
- if (! device->prepareAndOpen(fileName, chunkStart, currentChunkSize)) {
+ if (!device->prepareAndOpen(fileName, chunkStart, currentChunkSize)) {
qCWarning(lcPropagateUpload) << "Could not prepare upload device: " << device->errorString();
// If the file is currently locked, we want to retry the sync
emit propagator()->seenLockedFile(fileName);
}
// Soft error because this is likely caused by the user modifying his files while syncing
- abortWithError( SyncFileItem::SoftError, device->errorString() );
+ abortWithError(SyncFileItem::SoftError, device->errorString());
delete device;
return;
}
// job takes ownership of device via a QScopedPointer. Job deletes itself when finishing
- PUTFileJob* job = new PUTFileJob(propagator()->account(), propagator()->_remoteFolder + path, device, headers, _currentChunk, this);
+ PUTFileJob *job = new PUTFileJob(propagator()->account(), propagator()->_remoteFolder + path, device, headers, _currentChunk, this);
_jobs.append(job);
connect(job, SIGNAL(finishedSignal()), this, SLOT(slotPutFinished()));
- connect(job, SIGNAL(uploadProgress(qint64,qint64)), this, SLOT(slotUploadProgress(qint64,qint64)));
- connect(job, SIGNAL(uploadProgress(qint64,qint64)), device, SLOT(slotJobUploadProgress(qint64,qint64)));
- connect(job, SIGNAL(destroyed(QObject*)), this, SLOT(slotJobDestroyed(QObject*)));
+ connect(job, SIGNAL(uploadProgress(qint64, qint64)), this, SLOT(slotUploadProgress(qint64, qint64)));
+ connect(job, SIGNAL(uploadProgress(qint64, qint64)), device, SLOT(slotJobUploadProgress(qint64, qint64)));
+ connect(job, SIGNAL(destroyed(QObject *)), this, SLOT(slotJobDestroyed(QObject *)));
job->start();
propagator()->_activeJobList.append(this);
_currentChunk++;
}
if (parallelChunkUpload && (propagator()->_activeJobList.count() < propagator()->maximumActiveTransferJob())
- && _currentChunk < _chunkCount ) {
+ && _currentChunk < _chunkCount) {
startNextChunk();
}
if (!parallelChunkUpload || _chunkCount - _currentChunk <= 0) {
QNetworkReply::NetworkError err = job->reply()->error();
#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.
+ 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.
qCWarning(lcPropagateUpload) << "Forcing job abort on HTTP connection reset with Qt < 5.4.2.";
propagator()->_anotherSyncNeeded = true;
if (err != QNetworkReply::NoError) {
_item->_httpErrorCode = job->reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
- if(checkForProblemsWithShared(_item->_httpErrorCode,
- tr("The file was edited locally but is part of a read only share. "
- "It is restored and your edit is in the conflict file."))) {
+ if (checkForProblemsWithShared(_item->_httpErrorCode,
+ tr("The file was edited locally but is part of a read only share. "
+ "It is restored and your edit is in the conflict file."))) {
return;
}
QByteArray replyContent;
checkResettingErrors();
SyncFileItem::Status status = classifyError(err, _item->_httpErrorCode,
- &propagator()->_anotherSyncNeeded);
+ &propagator()->_anotherSyncNeeded);
abortWithError(status, errorString);
return;
}
// The server needs some time to process the request and provide us with a poll URL
if (_item->_httpErrorCode == 202) {
_finished = true;
- QString path = QString::fromUtf8(job->reply()->rawHeader("OC-Finish-Poll"));
+ QString path = QString::fromUtf8(job->reply()->rawHeader("OC-Finish-Poll"));
if (path.isEmpty()) {
done(SyncFileItem::NormalError, tr("Poll URL missing"));
return;
// Check if the file still exists
const QString fullFilePath(propagator()->getFilePath(_item->_file));
- if( !FileSystem::fileExists(fullFilePath) ) {
+ if (!FileSystem::fileExists(fullFilePath)) {
if (!finished) {
abortWithError(SyncFileItem::SoftError, tr("The local file was removed during sync."));
return;
}
// Check whether the file changed since discovery.
- if (! FileSystem::verifyFileUnchanged(fullFilePath, _item->_size, _item->_modtime)) {
+ if (!FileSystem::verifyFileUnchanged(fullFilePath, _item->_size, _item->_modtime)) {
propagator()->_anotherSyncNeeded = true;
- if( !finished ) {
+ if (!finished) {
abortWithError(SyncFileItem::SoftError, tr("Local file changed during sync."));
// FIXME: the legacy code was retrying for a few seconds.
// and also checking that after the last chunk, and removed the file in case of INSTRUCTION_NEW
auto currentChunk = job->_chunk;
foreach (auto *job, _jobs) {
// Take the minimum finished one
- if (auto putJob = qobject_cast<PUTFileJob*>(job)) {
+ if (auto putJob = qobject_cast<PUTFileJob *>(job)) {
currentChunk = qMin(currentChunk, putJob->_chunk - 1);
}
}
- pi._chunk = (currentChunk + _startChunk + 1) % _chunkCount ; // next chunk to start with
+ pi._chunk = (currentChunk + _startChunk + 1) % _chunkCount; // next chunk to start with
pi._transferid = _transferId;
- pi._modtime = Utility::qDateTimeFromTime_t(_item->_modtime);
+ pi._modtime = Utility::qDateTimeFromTime_t(_item->_modtime);
pi._errorCount = 0; // successful chunk upload resets
propagator()->_journal->setUploadInfo(_item->_file, pi);
propagator()->_journal->commit("Upload info");
_finished = true;
// the file id should only be empty for new files up- or downloaded
QByteArray fid = job->reply()->rawHeader("OC-FileID");
- if( !fid.isEmpty() ) {
- if( !_item->_fileId.isEmpty() && _item->_fileId != fid ) {
+ if (!fid.isEmpty()) {
+ if (!_item->_fileId.isEmpty() && _item->_fileId != fid) {
qCWarning(lcPropagateUpload) << "File ID changed!" << _item->_fileId << fid;
}
_item->_fileId = fid;
// performance logging
quint64 duration = _stopWatch.stop();
qCDebug(lcPropagateUpload) << "*==* duration UPLOAD" << _item->_size
- << _stopWatch.durationOfLap(QLatin1String("ContentChecksum"))
- << _stopWatch.durationOfLap(QLatin1String("TransmissionChecksum"))
- << duration;
+ << _stopWatch.durationOfLap(QLatin1String("ContentChecksum"))
+ << _stopWatch.durationOfLap(QLatin1String("TransmissionChecksum"))
+ << duration;
// The job might stay alive for the whole sync, release this tiny bit of memory.
_stopWatch.reset();
#endif
sender()->setProperty("byteWritten", sent);
if (_jobs.count() > 1) {
- amount -= (_jobs.count() -1) * chunkSize();
+ amount -= (_jobs.count() - 1) * chunkSize();
foreach (QObject *j, _jobs) {
amount += j->property("byteWritten").toULongLong();
}
}
propagator()->reportProgress(*_item, amount);
}
-
}
*
* \a path is relative to propagator()->_localDir + _item->_file and should start with a slash
*/
-bool PropagateLocalRemove::removeRecursively(const QString& path)
+bool PropagateLocalRemove::removeRecursively(const QString &path)
{
bool success = true;
QString absolute = propagator()->_localDir + _item->_file + path;
while (di.hasNext()) {
di.next();
- const QFileInfo& fi = di.fileInfo();
+ const QFileInfo &fi = di.fileInfo();
bool ok;
// The use of isSymLink here is okay:
// we never want to go into this branch for .lnk files
QString removeError;
ok = FileSystem::remove(di.filePath(), &removeError);
if (!ok) {
- _error += PropagateLocalRemove::tr("Error removing '%1': %2;").
- arg(QDir::toNativeSeparators(di.filePath()), removeError) + " ";
+ _error += PropagateLocalRemove::tr("Error removing '%1': %2;").arg(QDir::toNativeSeparators(di.filePath()), removeError) + " ";
qCWarning(lcPropagateLocalRemove) << "Error removing " << di.filePath() << ':' << removeError;
}
}
if (success && !ok) {
// We need to delete the entries from the database now from the deleted vector
- foreach(const auto &it, deleted) {
+ foreach (const auto &it, deleted) {
propagator()->_journal->deleteFileRecord(_item->_originalFile + path + QLatin1Char('/') + it.first,
- it.second);
+ it.second);
}
success = false;
deleted.clear();
if (!success && ok) {
// This succeeded, so we need to delete it from the database now because the caller won't
propagator()->_journal->deleteFileRecord(_item->_originalFile + path + QLatin1Char('/') + di.fileName(),
- isDir);
+ isDir);
}
}
if (success) {
success = QDir().rmdir(absolute);
if (!success) {
_error += PropagateLocalRemove::tr("Could not remove folder '%1'")
- .arg(QDir::toNativeSeparators(absolute)) + " ";
+ .arg(QDir::toNativeSeparators(absolute))
+ + " ";
qCWarning(lcPropagateLocalRemove) << "Error removing folder" << absolute;
}
}
if (propagator()->_abortRequested.fetchAndAddRelaxed(0))
return;
- QString filename = propagator()->_localDir + _item->_file;
+ QString filename = propagator()->_localDir + _item->_file;
qCDebug(lcPropagateLocalRemove) << filename;
- if( propagator()->localFileNameClash(_item->_file)) {
- done(SyncFileItem::NormalError, tr("Could not remove %1 because of a local file name clash")
- .arg(QDir::toNativeSeparators(filename)));
+ if (propagator()->localFileNameClash(_item->_file)) {
+ done(SyncFileItem::NormalError, tr("Could not remove %1 because of a local file name clash").arg(QDir::toNativeSeparators(filename)));
return;
}
} else {
QString removeError;
if (FileSystem::fileExists(filename)
- && !FileSystem::remove(filename, &removeError)) {
+ && !FileSystem::remove(filename, &removeError)) {
done(SyncFileItem::NormalError, removeError);
return;
}
if (_deleteExistingFile && fi.exists() && fi.isFile()) {
QString removeError;
if (!FileSystem::remove(newDirStr, &removeError)) {
- done( SyncFileItem::NormalError,
- tr("could not delete file %1, error: %2")
- .arg(newDirStr, removeError));
+ done(SyncFileItem::NormalError,
+ tr("could not delete file %1, error: %2")
+ .arg(newDirStr, removeError));
return;
}
}
- if( Utility::fsCasePreserving() && propagator()->localFileNameClash(_item->_file ) ) {
+ if (Utility::fsCasePreserving() && propagator()->localFileNameClash(_item->_file)) {
qCWarning(lcPropagateLocalMkdir) << "New folder to create locally already exists with different case:" << _item->_file;
- done( SyncFileItem::NormalError, tr("Attention, possible case sensitivity clash with %1").arg(newDirStr) );
+ done(SyncFileItem::NormalError, tr("Attention, possible case sensitivity clash with %1").arg(newDirStr));
return;
}
emit propagator()->touchedFile(newDirStr);
QDir localDir(propagator()->_localDir);
if (!localDir.mkpath(_item->_file)) {
- done( SyncFileItem::NormalError, tr("could not create folder %1").arg(newDirStr) );
+ done(SyncFileItem::NormalError, tr("could not create folder %1").arg(newDirStr));
return;
}
qCDebug(lcPropagateLocalRename) << "MOVE " << existingFile << " => " << targetFile;
if (QString::compare(_item->_file, _item->_renameTarget, Qt::CaseInsensitive) != 0
- && propagator()->localFileNameClash(_item->_renameTarget)) {
+ && propagator()->localFileNameClash(_item->_renameTarget)) {
// Only use localFileNameClash for the destination if we know that the source was not
// the one conflicting (renaming A.txt -> a.txt is OK)
// Fixme: the file that is the reason for the clash could be named here,
// it would have to come out the localFileNameClash function
done(SyncFileItem::NormalError,
- tr( "File %1 can not be renamed to %2 because of a local file name clash")
- .arg(QDir::toNativeSeparators(_item->_file))
- .arg(QDir::toNativeSeparators(_item->_renameTarget)) );
+ tr("File %1 can not be renamed to %2 because of a local file name clash")
+ .arg(QDir::toNativeSeparators(_item->_file))
+ .arg(QDir::toNativeSeparators(_item->_renameTarget)));
return;
}
}
SyncJournalFileRecord oldRecord =
- propagator()->_journal->getFileRecord(_item->_originalFile);
+ propagator()->_journal->getFileRecord(_item->_originalFile);
propagator()->_journal->deleteFileRecord(_item->_originalFile);
// store the rename file name in the item.
done(SyncFileItem::Success);
}
-
}
* @brief Declaration of the other propagation jobs
* @ingroup libsync
*/
-class PropagateLocalRemove : public PropagateItemJob {
+class PropagateLocalRemove : public PropagateItemJob
+{
Q_OBJECT
public:
- PropagateLocalRemove (OwncloudPropagator* propagator,const SyncFileItemPtr& item) : PropagateItemJob(propagator, item) {}
+ PropagateLocalRemove(OwncloudPropagator *propagator, const SyncFileItemPtr &item)
+ : PropagateItemJob(propagator, item)
+ {
+ }
void start() Q_DECL_OVERRIDE;
+
private:
bool removeRecursively(const QString &path);
QString _error;
* @brief The PropagateLocalMkdir class
* @ingroup libsync
*/
-class PropagateLocalMkdir : public PropagateItemJob {
+class PropagateLocalMkdir : public PropagateItemJob
+{
Q_OBJECT
public:
- PropagateLocalMkdir (OwncloudPropagator* propagator,const SyncFileItemPtr& item)
- : PropagateItemJob(propagator, item), _deleteExistingFile(false) {}
+ PropagateLocalMkdir(OwncloudPropagator *propagator, const SyncFileItemPtr &item)
+ : PropagateItemJob(propagator, item)
+ , _deleteExistingFile(false)
+ {
+ }
void start() Q_DECL_OVERRIDE;
/**
* @brief The PropagateLocalRename class
* @ingroup libsync
*/
-class PropagateLocalRename : public PropagateItemJob {
+class PropagateLocalRename : public PropagateItemJob
+{
Q_OBJECT
public:
- PropagateLocalRename (OwncloudPropagator* propagator,const SyncFileItemPtr& item) : PropagateItemJob(propagator, item) {}
+ PropagateLocalRename(OwncloudPropagator *propagator, const SyncFileItemPtr &item)
+ : PropagateItemJob(propagator, item)
+ {
+ }
void start() Q_DECL_OVERRIDE;
JobParallelism parallelism() Q_DECL_OVERRIDE { return _item->_isDirectory ? WaitForFinished : FullParallelism; }
};
-
}
qint64 SyncEngine::minimumFileAgeForUpload = 2000;
-SyncEngine::SyncEngine(AccountPtr account, const QString& localPath,
- const QString& remotePath, OCC::SyncJournalDb* journal)
- : _account(account)
- , _needsUpdate(false)
- , _syncRunning(false)
- , _localPath(localPath)
- , _remotePath(remotePath)
- , _journal(journal)
- , _progressInfo(new ProgressInfo)
- , _hasNoneFiles(false)
- , _hasRemoveFile(false)
- , _hasForwardInTimeFiles(false)
- , _backInTimeFiles(0)
- , _uploadLimit(0)
- , _downloadLimit(0)
- , _checksum_hook(journal)
- , _anotherSyncNeeded(NoFollowUpSync)
+SyncEngine::SyncEngine(AccountPtr account, const QString &localPath,
+ const QString &remotePath, OCC::SyncJournalDb *journal)
+ : _account(account)
+ , _needsUpdate(false)
+ , _syncRunning(false)
+ , _localPath(localPath)
+ , _remotePath(remotePath)
+ , _journal(journal)
+ , _progressInfo(new ProgressInfo)
+ , _hasNoneFiles(false)
+ , _hasRemoveFile(false)
+ , _hasForwardInTimeFiles(false)
+ , _backInTimeFiles(0)
+ , _uploadLimit(0)
+ , _downloadLimit(0)
+ , _checksum_hook(journal)
+ , _anotherSyncNeeded(NoFollowUpSync)
{
qRegisterMetaType<SyncFileItem>("SyncFileItem");
qRegisterMetaType<SyncFileItemPtr>("SyncFileItemPtr");
_syncFileStatusTracker.reset(new SyncFileStatusTracker(this));
_clearTouchedFilesTimer.setSingleShot(true);
- _clearTouchedFilesTimer.setInterval(30*1000);
+ _clearTouchedFilesTimer.setInterval(30 * 1000);
connect(&_clearTouchedFilesTimer, SIGNAL(timeout()), SLOT(slotClearTouchedFiles()));
_thread.setObjectName("SyncEngine_Thread");
{
QString errStr;
- switch( err ) {
+ switch (err) {
case CSYNC_STATUS_OK:
errStr = tr("Success.");
break;
errStr = tr("Error while reading folder.");
break;
case CSYNC_STATUS_INVALID_CHARACTERS:
- // Handled in callee
+ // Handled in callee
default:
- errStr = tr("An internal error number %1 occurred.").arg( (int) err );
+ errStr = tr("An internal error number %1 occurred.").arg((int)err);
}
return errStr;
-
}
/**
* and proper error message, and return true.
* If the item is not in the blacklist, or the blacklist is stale, return false.
*/
-bool SyncEngine::checkErrorBlacklisting( SyncFileItem &item )
+bool SyncEngine::checkErrorBlacklisting(SyncFileItem &item)
{
- if( !_journal ) {
+ if (!_journal) {
qCCritical(lcEngine) << "Journal is undefined!";
return false;
}
SyncJournalErrorBlacklistRecord entry = _journal->errorBlacklistEntry(item._file);
item._hasBlacklistEntry = false;
- if( !entry.isValid() ) {
+ if (!entry.isValid()) {
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 ) {
+ if (now >= entry._lastTryTime + entry._ignoreDuration) {
qCInfo(lcEngine) << "blacklist entry for " << item._file << " has expired!";
return false;
}
// If the file has changed locally or on the server, the blacklist
// entry no longer applies
- if( item._direction == SyncFileItem::Up ) { // check the modtime
- if(item._modtime == 0 || entry._lastTryModtime == 0) {
+ if (item._direction == SyncFileItem::Up) { // check the modtime
+ if (item._modtime == 0 || entry._lastTryModtime == 0) {
return false;
- } else if( item._modtime != entry._lastTryModtime ) {
+ } else if (item._modtime != entry._lastTryModtime) {
qCInfo(lcEngine) << item._file << " is blacklisted, but has changed mtime!";
return false;
- } else if( item._renameTarget != entry._renameTarget) {
+ } else if (item._renameTarget != entry._renameTarget) {
qCInfo(lcEngine) << item._file << " is blacklisted, but rename target changed from" << entry._renameTarget;
return false;
}
- } else if( item._direction == SyncFileItem::Down ) {
+ } else if (item._direction == SyncFileItem::Down) {
// download, check the etag.
- if( item._etag.isEmpty() || entry._lastTryEtag.isEmpty() ) {
+ if (item._etag.isEmpty() || entry._lastTryEtag.isEmpty()) {
qCInfo(lcEngine) << item._file << "one ETag is empty, no blacklisting";
return false;
- } else if( item._etag != entry._lastTryEtag ) {
+ } else if (item._etag != entry._lastTryEtag) {
qCInfo(lcEngine) << item._file << " is blacklisted, but has changed etag!";
return false;
}
}
qCInfo(lcEngine) << "Item is on blacklist: " << entry._file
- << "retries:" << entry._retryCount
- << "for another" << (entry._lastTryTime + entry._ignoreDuration - now) << "s";
+ << "retries:" << entry._retryCount
+ << "for another" << (entry._lastTryTime + entry._ignoreDuration - now) << "s";
item._instruction = CSYNC_INSTRUCTION_ERROR;
item._status = SyncFileItem::FileIgnored;
item._errorString = tr("The item is not synced because of previous errors: %1").arg(entry._errorString);
{
// Find all downloadinfo paths that we want to preserve.
QSet<QString> download_file_paths;
- foreach(const SyncFileItemPtr &it, syncItems) {
+ foreach (const SyncFileItemPtr &it, syncItems) {
if (it->_direction == SyncFileItem::Down
- && it->_type == SyncFileItem::File)
- {
+ && it->_type == SyncFileItem::File) {
download_file_paths.insert(it->_file);
}
}
// Delete from journal and from filesystem.
const QVector<SyncJournalDb::DownloadInfo> deleted_infos =
- _journal->getAndDeleteStaleDownloadInfos(download_file_paths);
- foreach (const SyncJournalDb::DownloadInfo & deleted_info, deleted_infos) {
+ _journal->getAndDeleteStaleDownloadInfos(download_file_paths);
+ foreach (const SyncJournalDb::DownloadInfo &deleted_info, deleted_infos) {
const QString tmppath = _propagator->getFilePath(deleted_info._tmpfile);
qCInfo(lcEngine) << "Deleting stale temporary file: " << tmppath;
FileSystem::remove(tmppath);
{
// Find all blacklisted paths that we want to preserve.
QSet<QString> upload_file_paths;
- foreach(const SyncFileItemPtr &it, syncItems) {
+ foreach (const SyncFileItemPtr &it, syncItems) {
if (it->_direction == SyncFileItem::Up
- && it->_type == SyncFileItem::File)
- {
+ && it->_type == SyncFileItem::File) {
upload_file_paths.insert(it->_file);
}
}
// Delete the stales chunk on the server.
if (account()->capabilities().chunkingNg()) {
foreach (uint transferId, ids) {
- QUrl url = Utility::concatUrlPath(account()->url(), QLatin1String("remote.php/dav/uploads/")
- + account()->davUser() + QLatin1Char('/') + QString::number(transferId));
+ QUrl url = Utility::concatUrlPath(account()->url(), QLatin1String("remote.php/dav/uploads/") + account()->davUser() + QLatin1Char('/') + QString::number(transferId));
(new DeleteJob(account(), url, this))->start();
}
}
{
// Find all blacklisted paths that we want to preserve.
QSet<QString> blacklist_file_paths;
- foreach(const SyncFileItemPtr &it, syncItems) {
+ foreach (const SyncFileItemPtr &it, syncItems) {
if (it->_hasBlacklistEntry)
blacklist_file_paths.insert(it->_file);
}
_journal->deleteStaleErrorBlacklistEntries(blacklist_file_paths);
}
-int SyncEngine::treewalkLocal( TREE_WALK_FILE* file, void *data )
+int SyncEngine::treewalkLocal(TREE_WALK_FILE *file, void *data)
{
- return static_cast<SyncEngine*>(data)->treewalkFile( file, false );
+ return static_cast<SyncEngine *>(data)->treewalkFile(file, false);
}
-int SyncEngine::treewalkRemote( TREE_WALK_FILE* file, void *data )
+int SyncEngine::treewalkRemote(TREE_WALK_FILE *file, void *data)
{
- return static_cast<SyncEngine*>(data)->treewalkFile( file, true );
+ return static_cast<SyncEngine *>(data)->treewalkFile(file, true);
}
/**
*
* See doc/dev/sync-algorithm.md for an overview.
*/
-int SyncEngine::treewalkFile( TREE_WALK_FILE *file, bool remote )
+int SyncEngine::treewalkFile(TREE_WALK_FILE *file, bool remote)
{
- if( ! file ) return -1;
+ if (!file)
+ return -1;
QTextCodec::ConverterState utf8State;
static QTextCodec *codec = QTextCodec::codecForName("UTF-8");
item->_originalFile = item->_file;
if (item->_instruction == CSYNC_INSTRUCTION_NONE
- || (item->_instruction == CSYNC_INSTRUCTION_IGNORE && instruction != CSYNC_INSTRUCTION_NONE)) {
+ || (item->_instruction == CSYNC_INSTRUCTION_IGNORE && instruction != CSYNC_INSTRUCTION_NONE)) {
item->_instruction = instruction;
item->_modtime = file->modtime;
} else {
item->_fileId = file->file_id;
}
if (file->directDownloadUrl) {
- item->_directDownloadUrl = QString::fromUtf8( file->directDownloadUrl );
+ item->_directDownloadUrl = QString::fromUtf8(file->directDownloadUrl);
}
if (file->directDownloadCookies) {
- item->_directDownloadCookies = QString::fromUtf8( file->directDownloadCookies );
+ item->_directDownloadCookies = QString::fromUtf8(file->directDownloadCookies);
}
if (file->remotePerm && file->remotePerm[0]) {
item->_remotePerm = QByteArray(file->remotePerm);
* It needs to go to the sync journal becasue the stat information about remote
* files are often read from database rather than being pulled from remote.
*/
- if( remote ) {
- item->_serverHasIgnoredFiles = (file->has_ignored_files > 0);
+ if (remote) {
+ item->_serverHasIgnoredFiles = (file->has_ignored_files > 0);
}
// Sometimes the discovery computes checksums for local files
_seenFiles.insert(renameTarget);
}
- switch(file->error_status) {
+ switch (file->error_status) {
case CSYNC_STATUS_OK:
break;
case CSYNC_STATUS_INDIVIDUAL_IS_SYMLINK:
item->_errorString = tr("File names ending with a period are not supported on this file system.");
} else {
char invalid = '\0';
- foreach(char x, QByteArray("\\:?*\"<>|")) {
+ foreach (char x, QByteArray("\\:?*\"<>|")) {
if (item->_file.contains(x)) {
invalid = x;
break;
}
if (invalid) {
item->_errorString = tr("File names containing the character '%1' are not supported on this file system.")
- .arg(QLatin1Char(invalid));
+ .arg(QLatin1Char(invalid));
} else {
item->_errorString = tr("The file name is a reserved name on this file system.");
}
item->_inode = file->inode;
}
- switch( file->type ) {
+ switch (file->type) {
case CSYNC_FTW_TYPE_DIR:
item->_type = SyncFileItem::Directory;
break;
SyncFileItem::Direction dir = SyncFileItem::None;
int re = 0;
- switch(file->instruction) {
+ switch (file->instruction) {
case CSYNC_INSTRUCTION_NONE: {
// Any files that are instruction NONE?
if (!isDirectory && file->other.instruction == CSYNC_INSTRUCTION_NONE) {
_hasNoneFiles = true;
} else if (!isDirectory) {
auto difftime = std::difftime(file->modtime, file->other.modtime);
- if (difftime < -3600*2) {
+ if (difftime < -3600 * 2) {
// We are going back on time
// We only increment if the difference is more than two hours to avoid clock skew
// issues or DST changes. (We simply ignore files that goes in the past less than
if (instruction != CSYNC_INSTRUCTION_NONE) {
// check for blacklisting of this item.
// if the item is on blacklist, the instruction was set to ERROR
- checkErrorBlacklisting( *item );
+ checkErrorBlacklisting(*item);
}
_progressInfo->adjustTotalsForFile(*item);
_needsUpdate = true;
- item->log._other_etag = file->other.etag;
- item->log._other_fileId = file->other.file_id;
+ item->log._other_etag = file->other.etag;
+ item->log._other_fileId = file->other.file_id;
item->log._other_instruction = file->other.instruction;
- item->log._other_modtime = file->other.modtime;
- item->log._other_size = file->other.size;
+ item->log._other_modtime = file->other.modtime;
+ item->log._other_size = file->other.size;
_syncItemMap.insert(key, item);
return re;
}
-void SyncEngine::handleSyncError(CSYNC *ctx, const char *state) {
- CSYNC_STATUS err = csync_get_status( ctx );
- const char *errMsg = csync_get_status_string( ctx );
+void SyncEngine::handleSyncError(CSYNC *ctx, const char *state)
+{
+ CSYNC_STATUS err = csync_get_status(ctx);
+ const char *errMsg = csync_get_status_string(ctx);
QString errStr = csyncErrorToString(err);
- if( errMsg ) {
- if( !errStr.endsWith(" ")) {
+ if (errMsg) {
+ if (!errStr.endsWith(" ")) {
errStr.append(" ");
}
errStr += QString::fromUtf8(errMsg);
}
// if there is csyncs url modifier in the error message, replace it.
- if( errStr.contains("ownclouds://") ) errStr.replace("ownclouds://", "https://");
- if( errStr.contains("owncloud://") ) errStr.replace("owncloud://", "http://");
+ if (errStr.contains("ownclouds://"))
+ errStr.replace("ownclouds://", "https://");
+ if (errStr.contains("owncloud://"))
+ errStr.replace("owncloud://", "http://");
- qCWarning(lcEngine) << "ERROR during "<< state << ": " << errStr;
+ qCWarning(lcEngine) << "ERROR during " << state << ": " << errStr;
- if( CSYNC_STATUS_IS_EQUAL( err, CSYNC_STATUS_ABORTED) ) {
+ if (CSYNC_STATUS_IS_EQUAL(err, CSYNC_STATUS_ABORTED)) {
qCInfo(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 )) {
+ } else if (CSYNC_STATUS_IS_EQUAL(err, CSYNC_STATUS_SERVICE_UNAVAILABLE) || CSYNC_STATUS_IS_EQUAL(err, CSYNC_STATUS_CONNECT_ERROR)) {
emit csyncUnavailable();
} else {
emit csyncError(errStr);
void SyncEngine::startSync()
{
if (_journal->exists()) {
- QVector< SyncJournalDb::PollInfo > pollInfos = _journal->getPollInfos();
+ QVector<SyncJournalDb::PollInfo> pollInfos = _journal->getPollInfos();
if (!pollInfos.isEmpty()) {
qCInfo(lcEngine) << "Finish Poll jobs before starting a sync";
CleanupPollsJob *job = new CleanupPollsJob(pollInfos, _account,
- _journal, _localPath, this);
+ _journal, _localPath, this);
connect(job, SIGNAL(finished()), this, SLOT(startSync()));
connect(job, SIGNAL(aborted(QString)), this, SLOT(slotCleanPollsJobAborted(QString)));
job->start();
const qint64 freeBytes = Utility::freeDiskSpace(_localPath);
if (freeBytes >= 0) {
qCInfo(lcEngine) << "There are" << freeBytes << "bytes available at" << _localPath
- << "and at least" << minFree << "are required";
+ << "and at least" << minFree << "are required";
if (freeBytes < minFree) {
_anotherSyncNeeded = DelayedFollowUp;
emit csyncError(tr("Only %1 are available, need at least %2 to start",
- "Placeholders are postfixed with file sizes using Utility::octetsToString()").arg(
- Utility::octetsToString(freeBytes),
- Utility::octetsToString(minFree)));
+ "Placeholders are postfixed with file sizes using Utility::octetsToString()")
+ .arg(
+ Utility::octetsToString(freeBytes),
+ Utility::octetsToString(minFree)));
finalize(false);
return;
}
}
QString verStr("Using Qt ");
- verStr.append( qVersion() );
+ verStr.append(qVersion());
-#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
- verStr.append( " SSL library " ).append(QSslSocket::sslLibraryVersionString().toUtf8().data());
+#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());
+ verStr.append(" on ").append(Utility::platformName());
qCInfo(lcEngine) << verStr;
fileRecordCount = _journal->getFileRecordCount(); // this creates the DB if it does not exist yet
- if( fileRecordCount == -1 ) {
+ if (fileRecordCount == -1) {
qCWarning(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);
_discoveryMainThread->setParent(this);
connect(this, SIGNAL(finished(bool)), _discoveryMainThread, SLOT(deleteLater()));
qCInfo(lcEngine) << "Server" << account()->serverVersion()
- << QString("rootEtagChangesNotOnlySubFolderEtags=%1").arg(account()->rootEtagChangesNotOnlySubFolderEtags());
+ << QString("rootEtagChangesNotOnlySubFolderEtags=%1").arg(account()->rootEtagChangesNotOnlySubFolderEtags());
if (account()->rootEtagChangesNotOnlySubFolderEtags()) {
connect(_discoveryMainThread, SIGNAL(etag(QString)), this, SLOT(slotRootEtagReceived(QString)));
} else {
discoveryJob->_syncOptions = _syncOptions;
discoveryJob->moveToThread(&_thread);
connect(discoveryJob, SIGNAL(finished(int)), this, SLOT(slotDiscoveryJobFinished(int)));
- connect(discoveryJob, SIGNAL(folderDiscovered(bool,QString)),
- this, SIGNAL(folderDiscovered(bool,QString)));
+ connect(discoveryJob, SIGNAL(folderDiscovered(bool, QString)),
+ this, SIGNAL(folderDiscovered(bool, QString)));
- connect(discoveryJob, SIGNAL(newBigFolder(QString,bool)),
- this, SIGNAL(newBigFolder(QString,bool)));
+ connect(discoveryJob, SIGNAL(newBigFolder(QString, bool)),
+ this, SIGNAL(newBigFolder(QString, bool)));
// This is used for the DiscoveryJob to be able to request the main thread/
// to read in directory contents.
- _discoveryMainThread->setupHooks( discoveryJob, _remotePath);
+ _discoveryMainThread->setupHooks(discoveryJob, _remotePath);
// Starts the update in a seperate thread
QMetaObject::invokeMethod(discoveryJob, "start", Qt::QueuedConnection);
}
-void SyncEngine::slotRootEtagReceived(const QString &e) {
+void SyncEngine::slotRootEtagReceived(const QString &e)
+{
if (_remoteRootEtag.isEmpty()) {
qCDebug(lcEngine) << "Root etag:" << e;
_remoteRootEtag = e;
// To clean the progress info
emit folderDiscovered(false, QString());
- if (discoveryResult < 0 ) {
+ if (discoveryResult < 0) {
handleSyncError(_csync_ctx, "csync_update");
return;
}
_journal->commitIfNeededAndStartNewTransaction("Post discovery");
}
- if( csync_reconcile(_csync_ctx) < 0 ) {
+ if (csync_reconcile(_csync_ctx) < 0) {
handleSyncError(_csync_ctx, "csync_reconcile");
return;
}
_temporarilyUnavailablePaths.clear();
_renamedFolders.clear();
- if( csync_walk_local_tree(_csync_ctx, &treewalkLocal, 0) < 0 ) {
+ if (csync_walk_local_tree(_csync_ctx, &treewalkLocal, 0) < 0) {
qCWarning(lcEngine) << "Error in local treewalk.";
walkOk = false;
}
- if( walkOk && csync_walk_remote_tree(_csync_ctx, &treewalkRemote, 0) < 0 ) {
+ if (walkOk && csync_walk_remote_tree(_csync_ctx, &treewalkRemote, 0) < 0) {
qCWarning(lcEngine) << "Error in remote treewalk.";
}
// Adjust the paths for the renames.
for (SyncFileItemVector::iterator it = syncItems.begin();
- it != syncItems.end(); ++it) {
+ it != syncItems.end(); ++it) {
(*it)->_file = adjustRenamedPath((*it)->_file);
}
// Server version older than 8.1 don't support these character in filename.
static const QRegExp invalidCharRx("[\\\\:?*\"<>|]");
for (auto it = syncItems.begin(); it != syncItems.end(); ++it) {
- if ((*it)->_direction == SyncFileItem::Up &&
- (*it)->destination().contains(invalidCharRx)) {
- (*it)->_errorString = tr("File name contains at least one invalid character");
+ if ((*it)->_direction == SyncFileItem::Up && (*it)->destination().contains(invalidCharRx)) {
+ (*it)->_errorString = tr("File name contains at least one invalid character");
(*it)->_instruction = CSYNC_INSTRUCTION_IGNORE;
}
}
// (for example, upgrading from a previous version, or first sync)
// Note that an empty ("") fingerprint is valid and means it was empty on the server before.
if (!databaseFingerprint.isNull()
- && _discoveryMainThread->_dataFingerprint != databaseFingerprint) {
+ && _discoveryMainThread->_dataFingerprint != databaseFingerprint) {
qCInfo(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)) {
+ && _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.
_progressInfo->startEstimateUpdates();
// post update phase script: allow to tweak stuff by a custom script in debug mode.
- if( !qgetenv("OWNCLOUD_POST_UPDATE_SCRIPT").isEmpty() ) {
+ if (!qgetenv("OWNCLOUD_POST_UPDATE_SCRIPT").isEmpty()) {
#ifndef NDEBUG
QString script = qgetenv("OWNCLOUD_POST_UPDATE_SCRIPT");
qCDebug(lcEngine) << "Post Update Script: " << script;
QProcess::execute(script.toUtf8());
#else
- qCWarning(lcEngine) << "**** 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
}
_journal->commit("post treewalk");
_propagator = QSharedPointer<OwncloudPropagator>(
- new OwncloudPropagator (_account, _localPath, _remotePath, _journal));
+ new OwncloudPropagator(_account, _localPath, _remotePath, _journal));
_propagator->setSyncOptions(_syncOptions);
connect(_propagator.data(), SIGNAL(itemCompleted(const SyncFileItemPtr &)),
- this, SLOT(slotItemCompleted(const SyncFileItemPtr &)));
- connect(_propagator.data(), SIGNAL(progress(const SyncFileItem &,quint64)),
- this, SLOT(slotProgress(const SyncFileItem &,quint64)));
+ this, SLOT(slotItemCompleted(const SyncFileItemPtr &)));
+ connect(_propagator.data(), SIGNAL(progress(const SyncFileItem &, quint64)),
+ this, SLOT(slotProgress(const SyncFileItem &, quint64)));
connect(_propagator.data(), SIGNAL(finished(bool)), this, SLOT(slotFinished(bool)), Qt::QueuedConnection);
connect(_propagator.data(), SIGNAL(seenLockedFile(QString)), SIGNAL(seenLockedFile(QString)));
connect(_propagator.data(), SIGNAL(touchedFile(QString)), SLOT(slotAddTouchedFile(QString)));
_uploadLimit = upload;
_downloadLimit = download;
- if( !_propagator ) return;
+ if (!_propagator)
+ return;
_propagator->_uploadLimit = upload;
_propagator->_downloadLimit = download;
int propDownloadLimit = _propagator->_downloadLimit
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
- .load()
+ .load()
#endif
- ;
+ ;
int propUploadLimit = _propagator->_uploadLimit
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
- .load()
+ .load()
#endif
- ;
+ ;
- if( propDownloadLimit != 0 || propUploadLimit != 0 ) {
+ if (propDownloadLimit != 0 || propUploadLimit != 0) {
qCInfo(lcEngine) << "Network Limits (down/up) " << propDownloadLimit << propUploadLimit;
}
}
}
// emit the treewalk results.
- if( ! _journal->postSyncCleanup( _seenFiles, _temporarilyUnavailablePaths ) ) {
+ if (!_journal->postSyncCleanup(_seenFiles, _temporarilyUnavailablePaths)) {
qCDebug(lcEngine) << "Cleaning of synced ";
}
_clearTouchedFilesTimer.start();
}
-void SyncEngine::slotProgress(const SyncFileItem& item, quint64 current)
+void SyncEngine::slotProgress(const SyncFileItem &item, quint64 current)
{
_progressInfo->setProgressItem(item, current);
emit transmissionProgress(*_progressInfo);
/* Given a path on the remote, give the path as it is when the rename is done */
-QString SyncEngine::adjustRenamedPath(const QString& original)
+QString SyncEngine::adjustRenamedPath(const QString &original)
{
int slashPos = original.size();
- while ((slashPos = original.lastIndexOf('/' , slashPos - 1)) > 0) {
- QHash< QString, QString >::const_iterator it = _renamedFolders.constFind(original.left(slashPos));
+ while ((slashPos = original.lastIndexOf('/', slashPos - 1)) > 0) {
+ QHash<QString, QString>::const_iterator it = _renamedFolders.constFind(original.left(slashPos));
if (it != _renamedFolders.constEnd()) {
return *it + original.mid(slashPos);
}
// if reading the selective sync list from db failed, lets ignore all rather than nothing.
if (!selectiveListOk || std::binary_search(selectiveSyncBlackList.constBegin(), selectiveSyncBlackList.constEnd(),
- path)) {
+ path)) {
(*it)->_instruction = CSYNC_INSTRUCTION_IGNORE;
(*it)->_status = SyncFileItem::FileIgnored;
(*it)->_errorString = tr("Ignored because of the \"choose what to sync\" blacklist");
continue;
}
- switch((*it)->_instruction) {
- case CSYNC_INSTRUCTION_TYPE_CHANGE:
- case CSYNC_INSTRUCTION_NEW: {
- int slashPos = (*it)->_file.lastIndexOf('/');
- QString parentDir = slashPos <= 0 ? "" : (*it)->_file.mid(0, slashPos);
- const QByteArray perms = getPermissions(parentDir);
- if (perms.isNull()) {
- // No permissions set
- break;
- } else if ((*it)->_isDirectory && !perms.contains("K")) {
- qCWarning(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");
+ switch ((*it)->_instruction) {
+ case CSYNC_INSTRUCTION_TYPE_CHANGE:
+ case CSYNC_INSTRUCTION_NEW: {
+ int slashPos = (*it)->_file.lastIndexOf('/');
+ QString parentDir = slashPos <= 0 ? "" : (*it)->_file.mid(0, slashPos);
+ const QByteArray perms = getPermissions(parentDir);
+ if (perms.isNull()) {
+ // No permissions set
+ break;
+ } else if ((*it)->_isDirectory && !perms.contains("K")) {
+ qCWarning(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");
- for (SyncFileItemVector::iterator it_next = it + 1; it_next != syncItems.end() && (*it_next)->destination().startsWith(path); ++it_next) {
- it = it_next;
- if ((*it)->_instruction == CSYNC_INSTRUCTION_RENAME) {
- // The file was most likely moved in this directory.
- // If the file was read only or could not be moved or removed, it should
- // be restored. Do that in the next sync by not considering as a rename
- // but delete and upload. It will then be restored if needed.
- _journal->avoidRenamesOnNextSync((*it)->_file);
- _anotherSyncNeeded = ImmediateFollowUp;
- qCWarning(lcEngine) << "Moving of " << (*it)->_file << " canceled because no permission to add parent folder";
- }
- (*it)->_instruction = CSYNC_INSTRUCTION_ERROR;
- (*it)->_status = SyncFileItem::SoftError;
- (*it)->_errorString = tr("Not allowed because you don't have permission to add parent folder");
+ for (SyncFileItemVector::iterator it_next = it + 1; it_next != syncItems.end() && (*it_next)->destination().startsWith(path); ++it_next) {
+ it = it_next;
+ if ((*it)->_instruction == CSYNC_INSTRUCTION_RENAME) {
+ // The file was most likely moved in this directory.
+ // If the file was read only or could not be moved or removed, it should
+ // be restored. Do that in the next sync by not considering as a rename
+ // but delete and upload. It will then be restored if needed.
+ _journal->avoidRenamesOnNextSync((*it)->_file);
+ _anotherSyncNeeded = ImmediateFollowUp;
+ qCWarning(lcEngine) << "Moving of " << (*it)->_file << " canceled because no permission to add parent folder";
}
-
- } else if (!(*it)->_isDirectory && !perms.contains("C")) {
- qCWarning(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");
+ (*it)->_status = SyncFileItem::SoftError;
+ (*it)->_errorString = tr("Not allowed because you don't have permission to add parent folder");
}
- break;
+
+ } else if (!(*it)->_isDirectory && !perms.contains("C")) {
+ qCWarning(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");
}
- case CSYNC_INSTRUCTION_SYNC: {
- const QByteArray perms = getPermissions((*it)->_file);
- if (perms.isNull()) {
- // No permissions set
- break;
- } if (!perms.contains("W")) {
- qCWarning(lcEngine) << "checkForPermission: RESTORING" << (*it)->_file;
- (*it)->_instruction = CSYNC_INSTRUCTION_CONFLICT;
- (*it)->_direction = SyncFileItem::Down;
- (*it)->_isRestoration = true;
- // take the things to write to the db from the "other" node (i.e: info from server)
- (*it)->_modtime = (*it)->log._other_modtime;
- (*it)->_size = (*it)->log._other_size;
- (*it)->_fileId = (*it)->log._other_fileId;
- (*it)->_etag = (*it)->log._other_etag;
- (*it)->_errorString = tr("Not allowed to upload this file because it is read-only on the server, restoring");
- continue;
- }
+ break;
+ }
+ case CSYNC_INSTRUCTION_SYNC: {
+ const QByteArray perms = getPermissions((*it)->_file);
+ if (perms.isNull()) {
+ // No permissions set
break;
}
- case CSYNC_INSTRUCTION_REMOVE: {
- const QByteArray perms = getPermissions((*it)->_file);
- if (perms.isNull()) {
- // No permissions set
- break;
- }
- if (!perms.contains("D")) {
- qCWarning(lcEngine) << "checkForPermission: RESTORING" << (*it)->_file;
- (*it)->_instruction = CSYNC_INSTRUCTION_NEW;
- (*it)->_direction = SyncFileItem::Down;
- (*it)->_isRestoration = true;
- (*it)->_errorString = tr("Not allowed to remove, restoring");
-
- if ((*it)->_isDirectory) {
- // restore all sub items
- for (SyncFileItemVector::iterator it_next = it + 1;
- it_next != syncItems.end() && (*it_next)->_file.startsWith(path); ++it_next) {
- it = it_next;
-
- if ((*it)->_instruction != CSYNC_INSTRUCTION_REMOVE) {
- qCWarning(lcEngine) << "non-removed job within a removed folder"
- << (*it)->_file << (*it)->_instruction;
- continue;
- }
-
- qCWarning(lcEngine) << "checkForPermission: RESTORING" << (*it)->_file;
-
- (*it)->_instruction = CSYNC_INSTRUCTION_NEW;
- (*it)->_direction = SyncFileItem::Down;
- (*it)->_isRestoration = true;
- (*it)->_errorString = tr("Not allowed to remove, restoring");
- }
- }
- } else if(perms.contains("S") && perms.contains("D")) {
- // this is a top level shared dir which can be removed to unshare it,
- // regardless if it is a read only share or not.
- // To avoid that we try to restore files underneath this dir which have
- // not delete permission we fast forward the iterator and leave the
- // delete jobs intact. It is not physically tried to remove this files
- // underneath, propagator sees that.
- if( (*it)->_isDirectory ) {
- // put a more descriptive message if a top level share dir really is removed.
- if( it == syncItems.begin() || !(path.startsWith((*(it-1))->_file)) ) {
- (*it)->_errorString = tr("Local files and share folder removed.");
- }
-
- for (SyncFileItemVector::iterator it_next = it + 1;
- it_next != syncItems.end() && (*it_next)->_file.startsWith(path); ++it_next) {
- it = it_next;
- }
- }
- }
+ if (!perms.contains("W")) {
+ qCWarning(lcEngine) << "checkForPermission: RESTORING" << (*it)->_file;
+ (*it)->_instruction = CSYNC_INSTRUCTION_CONFLICT;
+ (*it)->_direction = SyncFileItem::Down;
+ (*it)->_isRestoration = true;
+ // take the things to write to the db from the "other" node (i.e: info from server)
+ (*it)->_modtime = (*it)->log._other_modtime;
+ (*it)->_size = (*it)->log._other_size;
+ (*it)->_fileId = (*it)->log._other_fileId;
+ (*it)->_etag = (*it)->log._other_etag;
+ (*it)->_errorString = tr("Not allowed to upload this file because it is read-only on the server, restoring");
+ continue;
+ }
+ break;
+ }
+ case CSYNC_INSTRUCTION_REMOVE: {
+ const QByteArray perms = getPermissions((*it)->_file);
+ if (perms.isNull()) {
+ // No permissions set
break;
}
+ if (!perms.contains("D")) {
+ qCWarning(lcEngine) << "checkForPermission: RESTORING" << (*it)->_file;
+ (*it)->_instruction = CSYNC_INSTRUCTION_NEW;
+ (*it)->_direction = SyncFileItem::Down;
+ (*it)->_isRestoration = true;
+ (*it)->_errorString = tr("Not allowed to remove, restoring");
+
+ if ((*it)->_isDirectory) {
+ // restore all sub items
+ for (SyncFileItemVector::iterator it_next = it + 1;
+ it_next != syncItems.end() && (*it_next)->_file.startsWith(path); ++it_next) {
+ it = it_next;
- case CSYNC_INSTRUCTION_RENAME: {
-
- int slashPos = (*it)->_renameTarget.lastIndexOf('/');
- const QString parentDir = slashPos <= 0 ? "" : (*it)->_renameTarget.mid(0, slashPos);
- const QByteArray destPerms = getPermissions(parentDir);
- const QByteArray filePerms = getPermissions((*it)->_file);
-
- //true when it is just a rename in the same directory. (not a move)
- bool isRename = (*it)->_file.startsWith(parentDir) && (*it)->_file.lastIndexOf('/') == slashPos;
+ if ((*it)->_instruction != CSYNC_INSTRUCTION_REMOVE) {
+ qCWarning(lcEngine) << "non-removed job within a removed folder"
+ << (*it)->_file << (*it)->_instruction;
+ continue;
+ }
+ qCWarning(lcEngine) << "checkForPermission: RESTORING" << (*it)->_file;
- // Check if we are allowed to move to the destination.
- bool destinationOK = true;
- if (isRename || destPerms.isNull()) {
- // no need to check for the destination dir permission
- destinationOK = true;
- } else if ((*it)->_isDirectory && !destPerms.contains("K")) {
- destinationOK = false;
- } else if (!(*it)->_isDirectory && !destPerms.contains("C")) {
- destinationOK = false;
+ (*it)->_instruction = CSYNC_INSTRUCTION_NEW;
+ (*it)->_direction = SyncFileItem::Down;
+ (*it)->_isRestoration = true;
+ (*it)->_errorString = tr("Not allowed to remove, restoring");
+ }
}
+ } else if (perms.contains("S") && perms.contains("D")) {
+ // this is a top level shared dir which can be removed to unshare it,
+ // regardless if it is a read only share or not.
+ // To avoid that we try to restore files underneath this dir which have
+ // not delete permission we fast forward the iterator and leave the
+ // delete jobs intact. It is not physically tried to remove this files
+ // underneath, propagator sees that.
+ if ((*it)->_isDirectory) {
+ // put a more descriptive message if a top level share dir really is removed.
+ if (it == syncItems.begin() || !(path.startsWith((*(it - 1))->_file))) {
+ (*it)->_errorString = tr("Local files and share folder removed.");
+ }
- // check if we are allowed to move from the source
- bool sourceOK = true;
- if (!filePerms.isNull()
- && ((isRename && !filePerms.contains("N"))
- || (!isRename && !filePerms.contains("V")))) {
+ for (SyncFileItemVector::iterator it_next = it + 1;
+ it_next != syncItems.end() && (*it_next)->_file.startsWith(path); ++it_next) {
+ it = it_next;
+ }
+ }
+ }
+ break;
+ }
- // We are not allowed to move or rename this file
- sourceOK = false;
+ case CSYNC_INSTRUCTION_RENAME: {
+ int slashPos = (*it)->_renameTarget.lastIndexOf('/');
+ const QString parentDir = slashPos <= 0 ? "" : (*it)->_renameTarget.mid(0, slashPos);
+ const QByteArray destPerms = getPermissions(parentDir);
+ const QByteArray filePerms = getPermissions((*it)->_file);
+
+ //true when it is just a rename in the same directory. (not a move)
+ bool isRename = (*it)->_file.startsWith(parentDir) && (*it)->_file.lastIndexOf('/') == slashPos;
+
+
+ // Check if we are allowed to move to the destination.
+ bool destinationOK = true;
+ if (isRename || destPerms.isNull()) {
+ // no need to check for the destination dir permission
+ destinationOK = true;
+ } else if ((*it)->_isDirectory && !destPerms.contains("K")) {
+ destinationOK = false;
+ } else if (!(*it)->_isDirectory && !destPerms.contains("C")) {
+ destinationOK = false;
+ }
- if (filePerms.contains("D") && destinationOK) {
- // but we are allowed to delete it
- // TODO! simulate delete & upload
- }
+ // check if we are allowed to move from the source
+ bool sourceOK = true;
+ if (!filePerms.isNull()
+ && ((isRename && !filePerms.contains("N"))
+ || (!isRename && !filePerms.contains("V")))) {
+ // We are not allowed to move or rename this file
+ sourceOK = false;
+
+ if (filePerms.contains("D") && destinationOK) {
+ // but we are allowed to delete it
+ // TODO! simulate delete & upload
}
+ }
#ifdef OWNCLOUD_RESTORE_RENAME /* We don't like the idea of renaming behind user's back, as the user may be working with the files */
- if (!sourceOK && (!destinationOK || isRename)
- // (not for directory because that's more complicated with the contents that needs to be adjusted)
- && !(*it)->_isDirectory) {
- // Both the source and the destination won't allow move. Move back to the original
- std::swap((*it)->_file, (*it)->_renameTarget);
- (*it)->_direction = SyncFileItem::Down;
- (*it)->_errorString = tr("Move not allowed, item restored");
- (*it)->_isRestoration = true;
- qCWarning(lcEngine) << "checkForPermission: MOVING BACK" << (*it)->_file;
- // in case something does wrong, we will not do it next time
- _journal->avoidRenamesOnNextSync((*it)->_file);
- } else
+ if (!sourceOK && (!destinationOK || isRename)
+ // (not for directory because that's more complicated with the contents that needs to be adjusted)
+ && !(*it)->_isDirectory) {
+ // Both the source and the destination won't allow move. Move back to the original
+ std::swap((*it)->_file, (*it)->_renameTarget);
+ (*it)->_direction = SyncFileItem::Down;
+ (*it)->_errorString = tr("Move not allowed, item restored");
+ (*it)->_isRestoration = true;
+ qCWarning(lcEngine) << "checkForPermission: MOVING BACK" << (*it)->_file;
+ // in case something does wrong, we will not do it next time
+ _journal->avoidRenamesOnNextSync((*it)->_file);
+ } else
#endif
if (!sourceOK || !destinationOK) {
- // One of them is not possible, just throw an error
- (*it)->_instruction = CSYNC_INSTRUCTION_ERROR;
- (*it)->_status = SyncFileItem::NormalError;
- const QString errorString = tr("Move not allowed because %1 is read-only").arg(
- sourceOK ? tr("the destination") : tr("the source"));
- (*it)->_errorString = errorString;
-
- qCWarning(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
- // At this point we would need to go back to the propagate phase on both remote to take
- // the decision.
- _journal->avoidRenamesOnNextSync((*it)->_file);
- _anotherSyncNeeded = ImmediateFollowUp;
-
-
- if ((*it)->_isDirectory) {
- for (SyncFileItemVector::iterator it_next = it + 1;
- it_next != syncItems.end() && (*it_next)->destination().startsWith(path); ++it_next) {
- it = it_next;
- (*it)->_instruction = CSYNC_INSTRUCTION_ERROR;
- (*it)->_status = SyncFileItem::NormalError;
- (*it)->_errorString = errorString;
- qCWarning(lcEngine) << "checkForPermission: ERROR MOVING" << (*it)->_file;
- }
+ // One of them is not possible, just throw an error
+ (*it)->_instruction = CSYNC_INSTRUCTION_ERROR;
+ (*it)->_status = SyncFileItem::NormalError;
+ const QString errorString = tr("Move not allowed because %1 is read-only").arg(sourceOK ? tr("the destination") : tr("the source"));
+ (*it)->_errorString = errorString;
+
+ qCWarning(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
+ // At this point we would need to go back to the propagate phase on both remote to take
+ // the decision.
+ _journal->avoidRenamesOnNextSync((*it)->_file);
+ _anotherSyncNeeded = ImmediateFollowUp;
+
+
+ if ((*it)->_isDirectory) {
+ for (SyncFileItemVector::iterator it_next = it + 1;
+ it_next != syncItems.end() && (*it_next)->destination().startsWith(path); ++it_next) {
+ it = it_next;
+ (*it)->_instruction = CSYNC_INSTRUCTION_ERROR;
+ (*it)->_status = SyncFileItem::NormalError;
+ (*it)->_errorString = errorString;
+ qCWarning(lcEngine) << "checkForPermission: ERROR MOVING" << (*it)->_file;
}
}
- break;
}
- default:
- break;
+ break;
+ }
+ default:
+ break;
}
}
}
-QByteArray SyncEngine::getPermissions(const QString& file) const
+QByteArray SyncEngine::getPermissions(const QString &file) const
{
static bool isTest = qgetenv("OWNCLOUD_TEST_PERMISSIONS").toInt();
if (isTest) {
}
}
-void SyncEngine::slotAddTouchedFile(const QString& fn)
+void SyncEngine::slotAddTouchedFile(const QString &fn)
{
QString file = QDir::cleanPath(fn);
_touchedFiles.clear();
}
-qint64 SyncEngine::timeSinceFileTouched(const QString& fn) const
+qint64 SyncEngine::timeSinceFileTouched(const QString &fn) const
{
- if (! _touchedFiles.contains(fn)) {
+ if (!_touchedFiles.contains(fn)) {
return -1;
}
_discoveryMainThread->abort();
}
// For the propagator
- if(_propagator) {
+ if (_propagator) {
_propagator->abort();
}
}
class SyncJournalDb;
class OwncloudPropagator;
-enum AnotherSyncNeeded
-{
+enum AnotherSyncNeeded {
NoFollowUpSync,
ImmediateFollowUp, // schedule this again immediately (limited amount of times)
DelayedFollowUp // regularly schedule this folder again (around 1/minute, unlimited)
Q_OBJECT
public:
SyncEngine(AccountPtr account, const QString &localPath,
- const QString &remotePath, SyncJournalDb *journal);
+ const QString &remotePath, SyncJournalDb *journal);
~SyncEngine();
- static QString csyncErrorToString( CSYNC_STATUS);
+ static QString csyncErrorToString(CSYNC_STATUS);
Q_INVOKABLE void startSync();
void setNetworkLimits(int upload, int download);
*
* Thread-safe.
*/
- qint64 timeSinceFileTouched(const QString& fn) const;
+ qint64 timeSinceFileTouched(const QString &fn) const;
AccountPtr account() const;
SyncJournalDb *journal() const { return _journal; }
static qint64 minimumFileAgeForUpload; // in ms
signals:
- void csyncError( const QString& );
+ void csyncError(const QString &);
void csyncUnavailable();
// During update, before reconcile
void folderDiscovered(bool local, const QString &folderUrl);
// before actual syncing (after update+reconcile) for each item
- void syncItemDiscovered(const SyncFileItem&);
+ void syncItemDiscovered(const SyncFileItem &);
// after the above signals. with the items that actually need propagating
- void aboutToPropagate(SyncFileItemVector&);
+ void aboutToPropagate(SyncFileItemVector &);
// after each item completed by a job (successful or not)
- void itemCompleted(const SyncFileItemPtr&);
+ void itemCompleted(const SyncFileItemPtr &);
- void transmissionProgress( const ProgressInfo& progress );
+ void transmissionProgress(const ProgressInfo &progress);
void finished(bool success);
void started();
private slots:
void slotRootEtagReceived(const QString &);
- void slotItemCompleted(const SyncFileItemPtr& item);
+ void slotItemCompleted(const SyncFileItemPtr &item);
void slotFinished(bool success);
- void slotProgress(const SyncFileItem& item, quint64 curent);
+ void slotProgress(const SyncFileItem &item, quint64 curent);
void slotDiscoveryJobFinished(int updateResult);
void slotCleanPollsJobAborted(const QString &error);
/** Records that a file was touched by a job. */
- void slotAddTouchedFile(const QString& fn);
+ void slotAddTouchedFile(const QString &fn);
/** Wipes the _touchedFiles hash */
void slotClearTouchedFiles();
QString journalDbFilePath() const;
- static int treewalkLocal( TREE_WALK_FILE*, void *);
- static int treewalkRemote( TREE_WALK_FILE*, void *);
- int treewalkFile( TREE_WALK_FILE*, bool );
- bool checkErrorBlacklisting( SyncFileItem &item );
+ static int treewalkLocal(TREE_WALK_FILE *, void *);
+ static int treewalkRemote(TREE_WALK_FILE *, void *);
+ int treewalkFile(TREE_WALK_FILE *, bool);
+ bool checkErrorBlacklisting(SyncFileItem &item);
// Cleans up unnecessary downloadinfo entries in the journal as well
// as their temporary files.
QString _remoteRootEtag;
SyncJournalDb *_journal;
QPointer<DiscoveryMainThread> _discoveryMainThread;
- QSharedPointer <OwncloudPropagator> _propagator;
+ QSharedPointer<OwncloudPropagator> _propagator;
// After a sync, only the syncdb entries whose filenames appear in this
// set will be kept. See _temporarilyUnavailablePaths.
* to recover
*/
void checkForPermission(SyncFileItemVector &syncItems);
- QByteArray getPermissions(const QString& file) const;
+ QByteArray getPermissions(const QString &file) const;
/**
* Instead of downloading files from the server, upload the files to the server
/** For clearing the _touchedFiles variable after sync finished */
QTimer _clearTouchedFilesTimer;
};
-
}
#endif // CSYNCTHREAD_H
#include <csync.h>
#if defined(Q_CC_GNU) && !defined(Q_CC_INTEL) && !defined(Q_CC_CLANG) && (__GNUC__ * 100 + __GNUC_MINOR__ < 408)
- // openSuse 12.3 didn't like enum bitfields.
- #define BITFIELD(size)
+// openSuse 12.3 didn't like enum bitfields.
+#define BITFIELD(size)
#else
- #define BITFIELD(size) :size
+#define BITFIELD(size) :size
#endif
* @brief The SyncFileItem class
* @ingroup libsync
*/
-class SyncFileItem {
+class SyncFileItem
+{
public:
enum Direction {
- None = 0,
- Up,
- Down };
+ None = 0,
+ Up,
+ Down
+ };
enum Type {
- UnknownType = 0,
- File = CSYNC_FTW_TYPE_FILE,
- Directory = CSYNC_FTW_TYPE_DIR,
- SoftLink = CSYNC_FTW_TYPE_SLINK
+ UnknownType = 0,
+ File = CSYNC_FTW_TYPE_FILE,
+ Directory = CSYNC_FTW_TYPE_DIR,
+ SoftLink = CSYNC_FTW_TYPE_SLINK
};
enum Status {
Restoration ///< The file was restored because what should have been done was not allowed
};
- SyncFileItem() : _type(UnknownType), _direction(None), _isDirectory(false),
- _serverHasIgnoredFiles(false), _hasBlacklistEntry(false),
- _errorMayBeBlacklisted(false), _status(NoStatus),
- _isRestoration(false),
- _httpErrorCode(0), _affectedItems(1),
- _instruction(CSYNC_INSTRUCTION_NONE), _modtime(0), _size(0), _inode(0)
+ SyncFileItem()
+ : _type(UnknownType)
+ , _direction(None)
+ , _isDirectory(false)
+ , _serverHasIgnoredFiles(false)
+ , _hasBlacklistEntry(false)
+ , _errorMayBeBlacklisted(false)
+ , _status(NoStatus)
+ , _isRestoration(false)
+ , _httpErrorCode(0)
+ , _affectedItems(1)
+ , _instruction(CSYNC_INSTRUCTION_NONE)
+ , _modtime(0)
+ , _size(0)
+ , _inode(0)
{
}
- friend bool operator==(const SyncFileItem& item1, const SyncFileItem& item2) {
+ friend bool operator==(const SyncFileItem &item1, const SyncFileItem &item2)
+ {
return item1._originalFile == item2._originalFile;
}
- friend bool operator<(const SyncFileItem& item1, const SyncFileItem& item2) {
+ friend bool operator<(const SyncFileItem &item1, const SyncFileItem &item2)
+ {
// Sort by destination
auto d1 = item1.destination();
auto d2 = item2.destination();
// Find the length of the largest prefix
int prefixL = 0;
auto minSize = std::min(d1.size(), d2.size());
- while (prefixL < minSize && data1[prefixL] == data2[prefixL]) { prefixL++; }
+ while (prefixL < minSize && data1[prefixL] == data2[prefixL]) {
+ prefixL++;
+ }
if (prefixL == d2.size())
return false;
return data1[prefixL] < data2[prefixL];
}
- QString destination() const {
+ QString destination() const
+ {
if (!_renameTarget.isEmpty()) {
return _renameTarget;
}
return _file;
}
- bool isEmpty() const {
+ bool isEmpty() const
+ {
return _file.isEmpty();
}
* issues list on the activity page and for checking whether an
* item should be announced in the notification message.
*/
- bool hasErrorStatus() const {
+ bool hasErrorStatus() const
+ {
return _status == SyncFileItem::SoftError
- || _status == SyncFileItem::NormalError
- || _status == SyncFileItem::FatalError
- || _status == SyncFileItem::Conflict
- || !_errorString.isEmpty();
+ || _status == SyncFileItem::NormalError
+ || _status == SyncFileItem::FatalError
+ || _status == SyncFileItem::Conflict
+ || !_errorString.isEmpty();
}
// Variables useful for everybody
/// Whether there's an entry in the blacklist table.
/// Note: that entry may have retries left, so this can be true
/// without the status being FileIgnored.
- bool _hasBlacklistEntry BITFIELD(1);
+ bool _hasBlacklistEntry BITFIELD(1);
/** If true and NormalError, this error may be blacklisted
*
* Note that non-local errors (httpErrorCode!=0) may also be
* blacklisted independently of this flag.
*/
- bool _errorMayBeBlacklisted BITFIELD(1);
+ bool _errorMayBeBlacklisted BITFIELD(1);
// Variables useful to report to the user
- Status _status BITFIELD(4);
- bool _isRestoration BITFIELD(1); // The original operation was forbidden, and this is a restoration
- quint16 _httpErrorCode;
- QString _errorString; // Contains a string only in case of error
- QByteArray _responseTimeStamp;
- quint32 _affectedItems; // the number of affected items by the operation on this item.
- // usually this value is 1, but for removes on dirs, it might be much higher.
+ Status _status BITFIELD(4);
+ bool _isRestoration BITFIELD(1); // The original operation was forbidden, and this is a restoration
+ quint16 _httpErrorCode;
+ QString _errorString; // Contains a string only in case of error
+ QByteArray _responseTimeStamp;
+ quint32 _affectedItems; // the number of affected items by the operation on this item.
+ // usually this value is 1, but for removes on dirs, it might be much higher.
// Variables used by the propagator
csync_instructions_e _instruction;
- QString _originalFile; // as it is in the csync tree
- time_t _modtime;
- QByteArray _etag;
- quint64 _size;
- quint64 _inode;
- QByteArray _fileId;
- QByteArray _remotePerm;
- QByteArray _contentChecksum;
- QByteArray _contentChecksumType;
- QString _directDownloadUrl;
- QString _directDownloadCookies;
-
- struct {
- quint64 _other_size;
- time_t _other_modtime;
- QByteArray _other_etag;
- QByteArray _other_fileId;
+ QString _originalFile; // as it is in the csync tree
+ time_t _modtime;
+ QByteArray _etag;
+ quint64 _size;
+ quint64 _inode;
+ QByteArray _fileId;
+ QByteArray _remotePerm;
+ QByteArray _contentChecksum;
+ QByteArray _contentChecksumType;
+ QString _directDownloadUrl;
+ QString _directDownloadCookies;
+
+ struct
+ {
+ quint64 _other_size;
+ time_t _other_modtime;
+ QByteArray _other_etag;
+ QByteArray _other_fileId;
enum csync_instructions_e _other_instruction BITFIELD(16);
} log;
};
typedef QSharedPointer<SyncFileItem> SyncFileItemPtr;
-inline bool operator<(const SyncFileItemPtr& item1, const SyncFileItemPtr& item2) {
+inline bool operator<(const SyncFileItemPtr &item1, const SyncFileItemPtr &item2)
+{
return *item1 < *item2;
}
typedef QVector<SyncFileItemPtr> SyncFileItemVector;
-
}
Q_DECLARE_METATYPE(OCC::SyncFileItem)
namespace OCC {
SyncFileStatus::SyncFileStatus()
- :_tag(StatusNone), _sharedWithMe(false)
+ : _tag(StatusNone)
+ , _sharedWithMe(false)
{
}
SyncFileStatus::SyncFileStatus(SyncFileStatusTag tag)
- :_tag(tag), _sharedWithMe(false)
+ : _tag(tag)
+ , _sharedWithMe(false)
{
-
}
void SyncFileStatus::set(SyncFileStatusTag tag)
QString statusString;
bool canBeShared = true;
- switch(_tag)
- {
+ switch (_tag) {
case StatusNone:
statusString = QLatin1String("NOP");
canBeShared = false;
statusString = QLatin1String("ERROR");
break;
}
- if(canBeShared && _sharedWithMe) {
+ if (canBeShared && _sharedWithMe) {
statusString += QLatin1String("+SWM");
}
void set(SyncFileStatusTag tag);
SyncFileStatusTag tag() const;
- void setSharedWithMe( bool isShared );
+ void setSharedWithMe(bool isShared);
bool sharedWithMe() const;
QString toSocketAPIString() const;
+
private:
SyncFileStatusTag _tag;
bool _sharedWithMe;
-
};
-inline bool operator==(const SyncFileStatus &a, const SyncFileStatus &b) {
+inline bool operator==(const SyncFileStatus &a, const SyncFileStatus &b)
+{
return a.tag() == b.tag() && a.sharedWithMe() == b.sharedWithMe();
}
-inline bool operator!=(const SyncFileStatus &a, const SyncFileStatus &b) {
+inline bool operator!=(const SyncFileStatus &a, const SyncFileStatus &b)
+{
return !(a == b);
}
}
if (problemPath == pathToMatch) {
return severity;
} else if (severity == SyncFileStatus::StatusError
- && problemPath.startsWith(pathToMatch)
- && (pathToMatch.isEmpty() || problemPath.at(pathToMatch.size()) == '/')) {
+ && problemPath.startsWith(pathToMatch)
+ && (pathToMatch.isEmpty() || problemPath.at(pathToMatch.size()) == '/')) {
return SyncFileStatus::StatusWarning;
} else if (!problemPath.startsWith(pathToMatch)) {
// Starting at lower_bound we get the first path that is not smaller,
* icon as the problem is most likely going to resolve itself quickly and
* automatically.
*/
-static inline bool showErrorInSocketApi(const SyncFileItem& item)
+static inline bool showErrorInSocketApi(const SyncFileItem &item)
{
const auto status = item._status;
return item._instruction == CSYNC_INSTRUCTION_ERROR
|| item._hasBlacklistEntry;
}
-static inline bool showWarningInSocketApi(const SyncFileItem& item)
+static inline bool showWarningInSocketApi(const SyncFileItem &item)
{
const auto status = item._status;
return item._instruction == CSYNC_INSTRUCTION_IGNORE
SyncFileStatusTracker::SyncFileStatusTracker(SyncEngine *syncEngine)
: _syncEngine(syncEngine)
{
- connect(syncEngine, SIGNAL(aboutToPropagate(SyncFileItemVector&)),
- SLOT(slotAboutToPropagate(SyncFileItemVector&)));
- connect(syncEngine, SIGNAL(itemCompleted(const SyncFileItemPtr&)),
- SLOT(slotItemCompleted(const SyncFileItemPtr&)));
+ connect(syncEngine, SIGNAL(aboutToPropagate(SyncFileItemVector &)),
+ SLOT(slotAboutToPropagate(SyncFileItemVector &)));
+ connect(syncEngine, SIGNAL(itemCompleted(const SyncFileItemPtr &)),
+ SLOT(slotItemCompleted(const SyncFileItemPtr &)));
connect(syncEngine, SIGNAL(finished(bool)), SLOT(slotSyncFinished()));
connect(syncEngine, SIGNAL(started()), SLOT(slotSyncEngineRunningChanged()));
connect(syncEngine, SIGNAL(finished(bool)), SLOT(slotSyncEngineRunningChanged()));
}
-SyncFileStatus SyncFileStatusTracker::fileStatus(const QString& relativePath)
+SyncFileStatus SyncFileStatusTracker::fileStatus(const QString &relativePath)
{
ASSERT(!relativePath.endsWith(QLatin1Char('/')));
// update the exclude list at runtime and doing it statically here removes
// our ability to notify changes through the fileStatusChanged signal,
// it's an acceptable compromize to treat all exclude types the same.
- if( _syncEngine->excludedFiles().isExcluded(_syncEngine->localPath() + relativePath,
- _syncEngine->localPath(),
- _syncEngine->ignoreHiddenFiles()) ) {
+ if (_syncEngine->excludedFiles().isExcluded(_syncEngine->localPath() + relativePath,
+ _syncEngine->localPath(),
+ _syncEngine->ignoreHiddenFiles())) {
return SyncFileStatus(SyncFileStatus::StatusWarning);
}
- if ( _dirtyPaths.contains(relativePath) )
+ if (_dirtyPaths.contains(relativePath))
return SyncFileStatus::StatusSync;
// First look it up in the database to know if it's shared
return resolveSyncAndErrorStatus(relativePath, NotShared, PathUnknown);
}
-void SyncFileStatusTracker::slotPathTouched(const QString& fileName)
+void SyncFileStatusTracker::slotPathTouched(const QString &fileName)
{
QString folderPath = _syncEngine->localPath();
}
}
-void SyncFileStatusTracker::slotAboutToPropagate(SyncFileItemVector& items)
+void SyncFileStatusTracker::slotAboutToPropagate(SyncFileItemVector &items)
{
ASSERT(_syncCount.isEmpty());
}
ASSERT(sharedFlag != UnknownShared,
- "The shared status needs to have been fetched from a SyncFileItem or the DB at this point.");
+ "The shared status needs to have been fetched from a SyncFileItem or the DB at this point.");
if (sharedFlag == Shared)
status.setSharedWithMe(true);
return status;
}
-void SyncFileStatusTracker::invalidateParentPaths(const QString& path)
+void SyncFileStatusTracker::invalidateParentPaths(const QString &path)
{
QStringList splitPath = path.split('/', QString::SkipEmptyParts);
for (int i = 0; i < splitPath.size(); ++i) {
}
}
-QString SyncFileStatusTracker::getSystemDestination(const QString& relativePath)
+QString SyncFileStatusTracker::getSystemDestination(const QString &relativePath)
{
QString systemPath = _syncEngine->localPath() + relativePath;
// SyncEngine::localPath() has a trailing slash, make sure to remove it if the
// destination is empty.
- if( systemPath.endsWith(QLatin1Char('/')) ) {
- systemPath.truncate(systemPath.length()-1);
+ if (systemPath.endsWith(QLatin1Char('/'))) {
+ systemPath.truncate(systemPath.length() - 1);
}
return systemPath;
}
-
}
{
Q_OBJECT
public:
- explicit SyncFileStatusTracker(SyncEngine* syncEngine);
- SyncFileStatus fileStatus(const QString& relativePath);
+ explicit SyncFileStatusTracker(SyncEngine *syncEngine);
+ SyncFileStatus fileStatus(const QString &relativePath);
public slots:
- void slotPathTouched(const QString& fileName);
+ void slotPathTouched(const QString &fileName);
signals:
- void fileStatusChanged(const QString& systemFileName, SyncFileStatus fileStatus);
+ void fileStatusChanged(const QString &systemFileName, SyncFileStatus fileStatus);
private slots:
- void slotAboutToPropagate(SyncFileItemVector& items);
- void slotItemCompleted(const SyncFileItemPtr& item);
+ void slotAboutToPropagate(SyncFileItemVector &items);
+ void slotItemCompleted(const SyncFileItemPtr &item);
void slotSyncFinished();
void slotSyncEngineRunningChanged();
private:
- enum SharedFlag { UnknownShared, NotShared, Shared };
- enum PathKnownFlag { PathUnknown = 0, PathKnown };
+ enum SharedFlag { UnknownShared,
+ NotShared,
+ Shared };
+ enum PathKnownFlag { PathUnknown = 0,
+ PathKnown };
SyncFileStatus resolveSyncAndErrorStatus(const QString &relativePath, SharedFlag sharedState, PathKnownFlag isPathKnown = PathKnown);
- void invalidateParentPaths(const QString& path);
- QString getSystemDestination(const QString& relativePath);
+ void invalidateParentPaths(const QString &path);
+ QString getSystemDestination(const QString &relativePath);
void incSyncCountAndEmitStatusChanged(const QString &relativePath, SharedFlag sharedState);
void decSyncCountAndEmitStatusChanged(const QString &relativePath, SharedFlag sharedState);
- SyncEngine* _syncEngine;
+ SyncEngine *_syncEngine;
std::map<QString, SyncFileStatus::SyncFileStatusTag> _syncProblems;
QSet<QString> _dirtyPaths;
// A directory that starts/ends propagation will in turn increase/decrease its own parent by 1.
QHash<QString, int> _syncCount;
};
-
}
#endif
Q_LOGGING_CATEGORY(lcDb, "sync.database", QtInfoMsg)
-SyncJournalDb::SyncJournalDb(const QString& dbFilePath, QObject *parent) :
- QObject(parent),
- _dbFile(dbFilePath),
- _transaction(0)
+SyncJournalDb::SyncJournalDb(const QString &dbFilePath, QObject *parent)
+ : QObject(parent)
+ , _dbFile(dbFilePath)
+ , _transaction(0)
{
-
}
-QString SyncJournalDb::makeDbName(const QUrl& remoteUrl,
- const QString& remotePath,
- const QString& user)
+QString SyncJournalDb::makeDbName(const QUrl &remoteUrl,
+ const QString &remotePath,
+ const QString &user)
{
QString journalPath = QLatin1String("._sync_");
- QString key = QString::fromUtf8("%1@%2:%3").arg(
- user,
- remoteUrl.toString(),
- remotePath);
+ QString key = QString::fromUtf8("%1@%2:%3").arg(user, remoteUrl.toString(), remotePath);
QByteArray ba = QCryptographicHash::hash(key.toUtf8(), QCryptographicHash::Md5);
- journalPath.append( ba.left(6).toHex() );
+ journalPath.append(ba.left(6).toHex());
journalPath.append(".db");
return journalPath;
}
-bool SyncJournalDb::maybeMigrateDb(const QString& localPath, const QString& absoluteJournalPath)
+bool SyncJournalDb::maybeMigrateDb(const QString &localPath, const QString &absoluteJournalPath)
{
const QString oldDbName = localPath + QLatin1String(".csync_journal.db");
- if( !FileSystem::fileExists(oldDbName) ) {
+ if (!FileSystem::fileExists(oldDbName)) {
return true;
}
const QString oldDbNameShm = oldDbName + "-shm";
// and therefore already has an (outdated) new-style db file.
QString error;
- if( FileSystem::fileExists( newDbName ) ) {
- if( !FileSystem::remove(newDbName, &error) ) {
+ if (FileSystem::fileExists(newDbName)) {
+ if (!FileSystem::remove(newDbName, &error)) {
qCWarning(lcDb) << "Database migration: Could not remove db file" << newDbName
- << "due to" << error;
+ << "due to" << error;
return false;
}
}
- if( FileSystem::fileExists( newDbNameWal ) ) {
- if( !FileSystem::remove(newDbNameWal, &error) ) {
+ if (FileSystem::fileExists(newDbNameWal)) {
+ if (!FileSystem::remove(newDbNameWal, &error)) {
qCWarning(lcDb) << "Database migration: Could not remove db WAL file" << newDbNameWal
- << "due to" << error;
+ << "due to" << error;
return false;
}
}
- if( FileSystem::fileExists( newDbNameShm ) ) {
- if( !FileSystem::remove(newDbNameShm, &error) ) {
+ if (FileSystem::fileExists(newDbNameShm)) {
+ if (!FileSystem::remove(newDbNameShm, &error)) {
qCWarning(lcDb) << "Database migration: Could not remove db SHM file" << newDbNameShm
- << "due to" << error;
+ << "due to" << error;
return false;
}
}
- if( !FileSystem::rename(oldDbName, newDbName, &error) ) {
+ if (!FileSystem::rename(oldDbName, newDbName, &error)) {
qCWarning(lcDb) << "Database migration: could not rename " << oldDbName
- << "to" << newDbName << ":" << error;
+ << "to" << newDbName << ":" << error;
return false;
}
- if( !FileSystem::rename(oldDbNameWal, newDbNameWal, &error) ) {
+ if (!FileSystem::rename(oldDbNameWal, newDbNameWal, &error)) {
qCWarning(lcDb) << "Database migration: could not rename " << oldDbNameWal
- << "to" << newDbNameWal << ":" << error;
+ << "to" << newDbNameWal << ":" << error;
return false;
}
- if( !FileSystem::rename(oldDbNameShm, newDbNameShm, &error) ) {
+ if (!FileSystem::rename(oldDbNameShm, newDbNameShm, &error)) {
qCWarning(lcDb) << "Database migration: could not rename " << oldDbNameShm
- << "to" << newDbNameShm << ":" << error;
+ << "to" << newDbNameShm << ":" << error;
return false;
}
void SyncJournalDb::startTransaction()
{
- if( _transaction == 0 ) {
- if( !_db.transaction() ) {
+ if (_transaction == 0) {
+ if (!_db.transaction()) {
qCWarning(lcDb) << "ERROR starting transaction: " << _db.error();
return;
}
void SyncJournalDb::commitTransaction()
{
- if( _transaction == 1 ) {
- if( ! _db.commit() ) {
+ if (_transaction == 1) {
+ if (!_db.commit()) {
qCWarning(lcDb) << "ERROR committing to the database: " << _db.error();
return;
}
}
}
-bool SyncJournalDb::sqlFail( const QString& log, const SqlQuery& query )
+bool SyncJournalDb::sqlFail(const QString &log, const SqlQuery &query)
{
commitTransaction();
qCWarning(lcDb) << "SQL Error" << log << query.error();
return false;
}
-static QString defaultJournalMode(const QString & dbPath)
+static QString defaultJournalMode(const QString &dbPath)
{
#ifdef Q_OS_WIN
// See #2693: Some exFAT file systems seem unable to cope with the
bool SyncJournalDb::checkConnect()
{
- if( _db.isOpen() ) {
+ if (_db.isOpen()) {
return true;
}
- if( _dbFile.isEmpty()) {
+ if (_dbFile.isEmpty()) {
qCWarning(lcDb) << "Database filename" + _dbFile + " is empty";
return false;
}
// The database file is created by this call (SQLITE_OPEN_CREATE)
- if( !_db.openOrCreateReadWrite(_dbFile) ) {
+ if (!_db.openOrCreateReadWrite(_dbFile)) {
QString error = _db.error();
qCWarning(lcDb) << "Error opening the db: " << error;
return false;
}
- if( !QFile::exists(_dbFile) ) {
+ if (!QFile::exists(_dbFile)) {
qCWarning(lcDb) << "Database file" + _dbFile + " does not exist";
return false;
}
SqlQuery createQuery(_db);
createQuery.prepare("CREATE TABLE IF NOT EXISTS metadata("
- "phash INTEGER(8),"
- "pathlen INTEGER,"
- "path VARCHAR(4096),"
- "inode INTEGER,"
- "uid INTEGER,"
- "gid INTEGER,"
- "mode INTEGER,"
- "modtime INTEGER(8),"
- "type INTEGER,"
- "md5 VARCHAR(32)," /* This is the etag. Called md5 for compatibility */
+ "phash INTEGER(8),"
+ "pathlen INTEGER,"
+ "path VARCHAR(4096),"
+ "inode INTEGER,"
+ "uid INTEGER,"
+ "gid INTEGER,"
+ "mode INTEGER,"
+ "modtime INTEGER(8),"
+ "type INTEGER,"
+ "md5 VARCHAR(32)," /* This is the etag. Called md5 for compatibility */
// updateDatabaseStructure() will add
// fileid
// remotePerm
// ignoredChildrenRemote
// contentChecksum
// contentChecksumTypeId
- "PRIMARY KEY(phash)"
- ");");
+ "PRIMARY KEY(phash)"
+ ");");
if (!createQuery.exec()) {
return sqlFail("Create table metadata", createQuery);
}
createQuery.prepare("CREATE TABLE IF NOT EXISTS downloadinfo("
- "path VARCHAR(4096),"
- "tmpfile VARCHAR(4096),"
- "etag VARCHAR(32),"
- "errorcount INTEGER,"
- "PRIMARY KEY(path)"
- ");");
+ "path VARCHAR(4096),"
+ "tmpfile VARCHAR(4096),"
+ "etag VARCHAR(32),"
+ "errorcount INTEGER,"
+ "PRIMARY KEY(path)"
+ ");");
if (!createQuery.exec()) {
return sqlFail("Create table downloadinfo", createQuery);
}
createQuery.prepare("CREATE TABLE IF NOT EXISTS uploadinfo("
- "path VARCHAR(4096),"
- "chunk INTEGER,"
- "transferid INTEGER,"
- "errorcount INTEGER,"
- "size INTEGER(8),"
- "modtime INTEGER(8),"
- "PRIMARY KEY(path)"
- ");");
+ "path VARCHAR(4096),"
+ "chunk INTEGER,"
+ "transferid INTEGER,"
+ "errorcount INTEGER,"
+ "size INTEGER(8),"
+ "modtime INTEGER(8),"
+ "PRIMARY KEY(path)"
+ ");");
if (!createQuery.exec()) {
return sqlFail("Create table uploadinfo", createQuery);
}
createQuery.prepare("CREATE TABLE IF NOT EXISTS poll("
- "path VARCHAR(4096),"
- "modtime INTEGER(8),"
- "pollpath VARCHAR(4096));");
+ "path VARCHAR(4096),"
+ "modtime INTEGER(8),"
+ "pollpath VARCHAR(4096));");
if (!createQuery.exec()) {
return sqlFail("Create table poll", createQuery);
}
// create the checksumtype table.
createQuery.prepare("CREATE TABLE IF NOT EXISTS checksumtype("
- "id INTEGER PRIMARY KEY,"
- "name TEXT UNIQUE"
- ");");
+ "id INTEGER PRIMARY KEY,"
+ "name TEXT UNIQUE"
+ ");");
if (!createQuery.exec()) {
return sqlFail("Create table version", createQuery);
}
}
createQuery.prepare("CREATE TABLE IF NOT EXISTS version("
- "major INTEGER(8),"
- "minor INTEGER(8),"
- "patch INTEGER(8),"
- "custom VARCHAR(256)"
- ");");
+ "major INTEGER(8),"
+ "minor INTEGER(8),"
+ "patch INTEGER(8),"
+ "custom VARCHAR(256)"
+ ");");
if (!createQuery.exec()) {
return sqlFail("Create table version", createQuery);
}
int minor = versionQuery.intValue(1);
int patch = versionQuery.intValue(2);
- if( major == 1 && minor == 8 && (patch == 0 || patch == 1) ) {
+ if (major == 1 && minor == 8 && (patch == 0 || patch == 1)) {
qCInfo(lcDb) << "possibleUpgradeFromMirall_1_8_0_or_1 detected!";
forceRemoteDiscovery = true;
}
// There was a bug in versions <2.3.0 that could lead to stale
// local files and a remote discovery will fix them.
// See #5190 #5242.
- if( major == 2 && minor < 3) {
+ if (major == 2 && minor < 3) {
qCInfo(lcDb) << "upgrade form client < 2.3.0 detected! forcing remote discovery";
forceRemoteDiscovery = true;
}
// Not comparing the BUILD id here, correct?
- if( !(major == MIRALL_VERSION_MAJOR && minor == MIRALL_VERSION_MINOR && patch == MIRALL_VERSION_PATCH) ) {
+ if (!(major == MIRALL_VERSION_MAJOR && minor == MIRALL_VERSION_MINOR && patch == MIRALL_VERSION_PATCH)) {
createQuery.prepare("UPDATE version SET major=?1, minor=?2, patch =?3, custom=?4 "
"WHERE major=?5 AND minor=?6 AND patch=?7;");
createQuery.bindValue(1, MIRALL_VERSION_MAJOR);
if (!createQuery.exec()) {
return sqlFail("Update version", createQuery);
}
-
}
}
commitInternal("checkConnect");
bool rc = updateDatabaseStructure();
- if( !rc ) {
+ if (!rc) {
qCWarning(lcDb) << "Failed to update the database structure!";
}
" ignoredChildrenRemote, contentChecksum, contentchecksumtype.name"
" FROM metadata"
" LEFT JOIN checksumtype as contentchecksumtype ON metadata.contentChecksumTypeId == contentchecksumtype.id"
- " WHERE phash=?1" )) {
+ " WHERE phash=?1")) {
return sqlFail("prepare _getFileRecordQuery", *_getFileRecordQuery);
}
- _setFileRecordQuery.reset(new SqlQuery(_db) );
+ _setFileRecordQuery.reset(new SqlQuery(_db));
if (_setFileRecordQuery->prepare("INSERT OR REPLACE INTO metadata "
- "(phash, pathlen, path, inode, uid, gid, mode, modtime, type, md5, fileid, remotePerm, filesize, ignoredChildrenRemote, contentChecksum, contentChecksumTypeId) "
- "VALUES (?1 , ?2, ?3 , ?4 , ?5 , ?6 , ?7, ?8 , ?9 , ?10, ?11, ?12, ?13, ?14, ?15, ?16);" )) {
+ "(phash, pathlen, path, inode, uid, gid, mode, modtime, type, md5, fileid, remotePerm, filesize, ignoredChildrenRemote, contentChecksum, contentChecksumTypeId) "
+ "VALUES (?1 , ?2, ?3 , ?4 , ?5 , ?6 , ?7, ?8 , ?9 , ?10, ?11, ?12, ?13, ?14, ?15, ?16);")) {
return sqlFail("prepare _setFileRecordQuery", *_setFileRecordQuery);
}
- _setFileRecordChecksumQuery.reset(new SqlQuery(_db) );
+ _setFileRecordChecksumQuery.reset(new SqlQuery(_db));
if (_setFileRecordChecksumQuery->prepare(
"UPDATE metadata"
" SET contentChecksum = ?2, contentChecksumTypeId = ?3"
" WHERE phash == ?1;")) {
return sqlFail("prepare _setFileRecordLocalMetadataQuery", *_setFileRecordLocalMetadataQuery);
}
-
- _getDownloadInfoQuery.reset(new SqlQuery(_db) );
- if (_getDownloadInfoQuery->prepare( "SELECT tmpfile, etag, errorcount FROM "
- "downloadinfo WHERE path=?1" )) {
+
+ _getDownloadInfoQuery.reset(new SqlQuery(_db));
+ if (_getDownloadInfoQuery->prepare("SELECT tmpfile, etag, errorcount FROM "
+ "downloadinfo WHERE path=?1")) {
return sqlFail("prepare _getDownloadInfoQuery", *_getDownloadInfoQuery);
}
- _setDownloadInfoQuery.reset(new SqlQuery(_db) );
- if (_setDownloadInfoQuery->prepare( "INSERT OR REPLACE INTO downloadinfo "
- "(path, tmpfile, etag, errorcount) "
- "VALUES ( ?1 , ?2, ?3, ?4 )" )) {
+ _setDownloadInfoQuery.reset(new SqlQuery(_db));
+ if (_setDownloadInfoQuery->prepare("INSERT OR REPLACE INTO downloadinfo "
+ "(path, tmpfile, etag, errorcount) "
+ "VALUES ( ?1 , ?2, ?3, ?4 )")) {
return sqlFail("prepare _setDownloadInfoQuery", *_setDownloadInfoQuery);
}
- _deleteDownloadInfoQuery.reset(new SqlQuery(_db) );
- if (_deleteDownloadInfoQuery->prepare( "DELETE FROM downloadinfo WHERE path=?1" )) {
+ _deleteDownloadInfoQuery.reset(new SqlQuery(_db));
+ if (_deleteDownloadInfoQuery->prepare("DELETE FROM downloadinfo WHERE path=?1")) {
return sqlFail("prepare _deleteDownloadInfoQuery", *_deleteDownloadInfoQuery);
}
_getUploadInfoQuery.reset(new SqlQuery(_db));
- if (_getUploadInfoQuery->prepare( "SELECT chunk, transferid, errorcount, size, modtime FROM "
- "uploadinfo WHERE path=?1" )) {
+ if (_getUploadInfoQuery->prepare("SELECT chunk, transferid, errorcount, size, modtime FROM "
+ "uploadinfo WHERE path=?1")) {
return sqlFail("prepare _getUploadInfoQuery", *_getUploadInfoQuery);
}
_setUploadInfoQuery.reset(new SqlQuery(_db));
- if (_setUploadInfoQuery->prepare( "INSERT OR REPLACE INTO uploadinfo "
- "(path, chunk, transferid, errorcount, size, modtime) "
- "VALUES ( ?1 , ?2, ?3 , ?4 , ?5, ?6 )")) {
+ if (_setUploadInfoQuery->prepare("INSERT OR REPLACE INTO uploadinfo "
+ "(path, chunk, transferid, errorcount, size, modtime) "
+ "VALUES ( ?1 , ?2, ?3 , ?4 , ?5, ?6 )")) {
return sqlFail("prepare _setUploadInfoQuery", *_setUploadInfoQuery);
}
_deleteUploadInfoQuery.reset(new SqlQuery(_db));
- if (_deleteUploadInfoQuery->prepare("DELETE FROM uploadinfo WHERE path=?1" )) {
+ if (_deleteUploadInfoQuery->prepare("DELETE FROM uploadinfo WHERE path=?1")) {
return sqlFail("prepare _deleteUploadInfoQuery", *_deleteUploadInfoQuery);
}
return sqlFail("prepare _deleteFileRecordRecursively", *_deleteFileRecordRecursively);
}
- QString sql( "SELECT lastTryEtag, lastTryModtime, retrycount, errorstring, lastTryTime, ignoreDuration, renameTarget "
- "FROM blacklist WHERE path=?1");
- if( Utility::fsCasePreserving() ) {
+ QString sql("SELECT lastTryEtag, lastTryModtime, retrycount, errorstring, lastTryTime, ignoreDuration, renameTarget "
+ "FROM blacklist WHERE path=?1");
+ if (Utility::fsCasePreserving()) {
// if the file system is case preserving we have to check the blacklist
// case insensitively
sql += QLatin1String(" COLLATE NOCASE");
_setErrorBlacklistQuery.reset(new SqlQuery(_db));
if (_setErrorBlacklistQuery->prepare("INSERT OR REPLACE INTO blacklist "
- "(path, lastTryEtag, lastTryModtime, retrycount, errorstring, lastTryTime, ignoreDuration, renameTarget) "
- "VALUES ( ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)")) {
+ "(path, lastTryEtag, lastTryModtime, retrycount, errorstring, lastTryTime, ignoreDuration, renameTarget) "
+ "VALUES ( ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)")) {
return sqlFail("prepare _setErrorBlacklistQuery", *_setErrorBlacklistQuery);
}
bool re = true;
// check if the file_id column is there and create it if not
- if( !checkConnect() ) {
+ if (!checkConnect()) {
return false;
}
- if( columns.indexOf(QLatin1String("fileid")) == -1 ) {
+ if (columns.indexOf(QLatin1String("fileid")) == -1) {
SqlQuery query(_db);
query.prepare("ALTER TABLE metadata ADD COLUMN fileid VARCHAR(128);");
- if( !query.exec() ) {
+ if (!query.exec()) {
sqlFail("updateMetadataTableStructure: Add column fileid", query);
re = false;
}
query.prepare("CREATE INDEX metadata_file_id ON metadata(fileid);");
- if( ! query.exec() ) {
+ if (!query.exec()) {
sqlFail("updateMetadataTableStructure: create index fileid", query);
re = false;
}
commitInternal("update database structure: add fileid col");
}
- if( columns.indexOf(QLatin1String("remotePerm")) == -1 ) {
-
+ if (columns.indexOf(QLatin1String("remotePerm")) == -1) {
SqlQuery query(_db);
query.prepare("ALTER TABLE metadata ADD COLUMN remotePerm VARCHAR(128);");
- if( !query.exec()) {
+ if (!query.exec()) {
sqlFail("updateMetadataTableStructure: add column remotePerm", query);
re = false;
}
commitInternal("update database structure (remotePerm)");
}
- if( columns.indexOf(QLatin1String("filesize")) == -1 )
- {
+ if (columns.indexOf(QLatin1String("filesize")) == -1) {
SqlQuery query(_db);
query.prepare("ALTER TABLE metadata ADD COLUMN filesize BIGINT;");
- if( !query.exec()) {
+ if (!query.exec()) {
sqlFail("updateDatabaseStructure: add column filesize", query);
re = false;
}
commitInternal("update database structure: add filesize col");
}
- if( 1 ) {
+ if (1) {
SqlQuery query(_db);
query.prepare("CREATE INDEX IF NOT EXISTS metadata_inode ON metadata(inode);");
- if( !query.exec()) {
+ if (!query.exec()) {
sqlFail("updateMetadataTableStructure: create index inode", query);
re = false;
}
commitInternal("update database structure: add inode index");
-
}
- if( 1 ) {
+ if (1) {
SqlQuery query(_db);
query.prepare("CREATE INDEX IF NOT EXISTS metadata_path ON metadata(path);");
- if( !query.exec()) {
+ if (!query.exec()) {
sqlFail("updateMetadataTableStructure: create index path", query);
re = false;
}
commitInternal("update database structure: add path index");
-
}
- if( columns.indexOf(QLatin1String("ignoredChildrenRemote")) == -1 ) {
+ if (columns.indexOf(QLatin1String("ignoredChildrenRemote")) == -1) {
SqlQuery query(_db);
query.prepare("ALTER TABLE metadata ADD COLUMN ignoredChildrenRemote INT;");
- if( !query.exec()) {
+ if (!query.exec()) {
sqlFail("updateMetadataTableStructure: add ignoredChildrenRemote column", query);
re = false;
}
commitInternal("update database structure: add ignoredChildrenRemote col");
}
- if( columns.indexOf(QLatin1String("contentChecksum")) == -1 ) {
+ if (columns.indexOf(QLatin1String("contentChecksum")) == -1) {
SqlQuery query(_db);
query.prepare("ALTER TABLE metadata ADD COLUMN contentChecksum TEXT;");
- if( !query.exec()) {
+ if (!query.exec()) {
sqlFail("updateMetadataTableStructure: add contentChecksum column", query);
re = false;
}
commitInternal("update database structure: add contentChecksum col");
}
- if( columns.indexOf(QLatin1String("contentChecksumTypeId")) == -1 ) {
+ if (columns.indexOf(QLatin1String("contentChecksumTypeId")) == -1) {
SqlQuery query(_db);
query.prepare("ALTER TABLE metadata ADD COLUMN contentChecksumTypeId INTEGER;");
- if( !query.exec()) {
+ if (!query.exec()) {
sqlFail("updateMetadataTableStructure: add contentChecksumTypeId column", query);
re = false;
}
bool re = true;
// check if the file_id column is there and create it if not
- if( !checkConnect() ) {
+ if (!checkConnect()) {
return false;
}
- if( columns.indexOf(QLatin1String("lastTryTime")) == -1 ) {
+ if (columns.indexOf(QLatin1String("lastTryTime")) == -1) {
SqlQuery query(_db);
query.prepare("ALTER TABLE blacklist ADD COLUMN lastTryTime INTEGER(8);");
- if( !query.exec() ) {
+ if (!query.exec()) {
sqlFail("updateBlacklistTableStructure: Add lastTryTime fileid", query);
re = false;
}
query.prepare("ALTER TABLE blacklist ADD COLUMN ignoreDuration INTEGER(8);");
- if( !query.exec() ) {
+ if (!query.exec()) {
sqlFail("updateBlacklistTableStructure: Add ignoreDuration fileid", query);
re = false;
}
commitInternal("update database structure: add lastTryTime, ignoreDuration cols");
}
- if( columns.indexOf(QLatin1String("renameTarget")) == -1 ) {
+ if (columns.indexOf(QLatin1String("renameTarget")) == -1) {
SqlQuery query(_db);
query.prepare("ALTER TABLE blacklist ADD COLUMN renameTarget VARCHAR(4096);");
- if( !query.exec() ) {
+ if (!query.exec()) {
sqlFail("updateBlacklistTableStructure: Add renameTarget", query);
re = false;
}
SqlQuery query(_db);
query.prepare("CREATE INDEX IF NOT EXISTS blacklist_index ON blacklist(path collate nocase);");
- if( !query.exec()) {
+ if (!query.exec()) {
sqlFail("updateErrorBlacklistTableStructure: create index blacklit", query);
re = false;
}
return re;
}
-QStringList SyncJournalDb::tableColumns( const QString& table )
+QStringList SyncJournalDb::tableColumns(const QString &table)
{
QStringList columns;
- if( !table.isEmpty() ) {
-
- if( checkConnect() ) {
+ if (!table.isEmpty()) {
+ if (checkConnect()) {
QString q = QString("PRAGMA table_info('%1');").arg(table);
SqlQuery query(_db);
query.prepare(q);
- if(!query.exec()) {
+ if (!query.exec()) {
return columns;
}
- while( query.next() ) {
- columns.append( query.stringValue(1) );
+ while (query.next()) {
+ columns.append(query.stringValue(1));
}
}
}
return columns;
}
-qint64 SyncJournalDb::getPHash(const QString& file)
+qint64 SyncJournalDb::getPHash(const QString &file)
{
QByteArray utf8File = file.toUtf8();
int64_t h;
- if( file.isEmpty() ) {
+ if (file.isEmpty()) {
return -1;
}
int len = utf8File.length();
- h = c_jhash64((uint8_t *) utf8File.data(), len, 0);
+ h = c_jhash64((uint8_t *)utf8File.data(), len, 0);
return h;
}
-bool SyncJournalDb::setFileRecord( const SyncJournalFileRecord& _record )
+bool SyncJournalDb::setFileRecord(const SyncJournalFileRecord &_record)
{
SyncJournalFileRecord record = _record;
QMutexLocker locker(&_mutex);
if (!_avoidReadFromDbOnNextSyncFilter.isEmpty()) {
// If we are a directory that should not be read from db next time, don't write the etag
QString prefix = record._path + "/";
- foreach(const QString &it, _avoidReadFromDbOnNextSyncFilter) {
+ foreach (const QString &it, _avoidReadFromDbOnNextSyncFilter) {
if (it.startsWith(prefix)) {
qCInfo(lcDb) << "Filtered writing the etag of" << prefix << "because it is a prefix of" << it;
record._etag = "_invalid_";
}
}
- qCInfo(lcDb) << "Updating file record for path:" << record._path << "inode:" << record._inode
- << "modtime:" << record._modtime << "type:" << record._type
- << "etag:" << record._etag << "fileId:" << record._fileId << "remotePerm:" << record._remotePerm
- << "fileSize:" << record._fileSize << "checksum:" << record._contentChecksum << record._contentChecksumType;
+ qCInfo(lcDb) << "Updating file record for path:" << record._path << "inode:" << record._inode
+ << "modtime:" << record._modtime << "type:" << record._type
+ << "etag:" << record._etag << "fileId:" << record._fileId << "remotePerm:" << record._remotePerm
+ << "fileSize:" << record._fileSize << "checksum:" << record._contentChecksum << record._contentChecksumType;
qlonglong phash = getPHash(record._path);
- if( checkConnect() ) {
+ if (checkConnect()) {
QByteArray arr = record._path.toUtf8();
int plen = arr.length();
- QString etag( record._etag );
- if( etag.isEmpty() ) etag = "";
- QString fileId( record._fileId);
- if( fileId.isEmpty() ) fileId = "";
- QString remotePerm (record._remotePerm);
- if (remotePerm.isEmpty()) remotePerm = QString(); // have NULL in DB (vs empty)
+ QString etag(record._etag);
+ if (etag.isEmpty())
+ etag = "";
+ QString fileId(record._fileId);
+ if (fileId.isEmpty())
+ fileId = "";
+ QString remotePerm(record._remotePerm);
+ if (remotePerm.isEmpty())
+ remotePerm = QString(); // have NULL in DB (vs empty)
int contentChecksumTypeId = mapChecksumType(record._contentChecksumType);
_setFileRecordQuery->reset_and_clear_bindings();
_setFileRecordQuery->bindValue(1, QString::number(phash));
_setFileRecordQuery->bindValue(2, plen);
- _setFileRecordQuery->bindValue(3, record._path );
- _setFileRecordQuery->bindValue(4, record._inode );
- _setFileRecordQuery->bindValue(5, 0 ); // uid Not used
- _setFileRecordQuery->bindValue(6, 0 ); // gid Not used
- _setFileRecordQuery->bindValue(7, 0 ); // mode Not used
+ _setFileRecordQuery->bindValue(3, record._path);
+ _setFileRecordQuery->bindValue(4, record._inode);
+ _setFileRecordQuery->bindValue(5, 0); // uid Not used
+ _setFileRecordQuery->bindValue(6, 0); // gid Not used
+ _setFileRecordQuery->bindValue(7, 0); // mode Not used
_setFileRecordQuery->bindValue(8, QString::number(Utility::qDateTimeToTime_t(record._modtime)));
- _setFileRecordQuery->bindValue(9, QString::number(record._type) );
- _setFileRecordQuery->bindValue(10, etag );
- _setFileRecordQuery->bindValue(11, fileId );
- _setFileRecordQuery->bindValue(12, remotePerm );
- _setFileRecordQuery->bindValue(13, record._fileSize );
- _setFileRecordQuery->bindValue(14, record._serverHasIgnoredFiles ? 1:0);
- _setFileRecordQuery->bindValue(15, record._contentChecksum );
- _setFileRecordQuery->bindValue(16, contentChecksumTypeId );
-
- if( !_setFileRecordQuery->exec() ) {
+ _setFileRecordQuery->bindValue(9, QString::number(record._type));
+ _setFileRecordQuery->bindValue(10, etag);
+ _setFileRecordQuery->bindValue(11, fileId);
+ _setFileRecordQuery->bindValue(12, remotePerm);
+ _setFileRecordQuery->bindValue(13, record._fileSize);
+ _setFileRecordQuery->bindValue(14, record._serverHasIgnoredFiles ? 1 : 0);
+ _setFileRecordQuery->bindValue(15, record._contentChecksum);
+ _setFileRecordQuery->bindValue(16, contentChecksumTypeId);
+
+ if (!_setFileRecordQuery->exec()) {
return false;
}
}
}
-bool SyncJournalDb::deleteFileRecord(const QString& filename, bool recursively)
+bool SyncJournalDb::deleteFileRecord(const QString &filename, bool recursively)
{
QMutexLocker locker(&_mutex);
- if( checkConnect() ) {
+ if (checkConnect()) {
// if (!recursively) {
// always delete the actual file.
qlonglong phash = getPHash(filename);
_deleteFileRecordPhash->reset_and_clear_bindings();
- _deleteFileRecordPhash->bindValue( 1, QString::number(phash) );
+ _deleteFileRecordPhash->bindValue(1, QString::number(phash));
- if( !_deleteFileRecordPhash->exec() ) {
+ if (!_deleteFileRecordPhash->exec()) {
return false;
}
_deleteFileRecordPhash->reset_and_clear_bindings();
- if( recursively) {
+ if (recursively) {
_deleteFileRecordRecursively->reset_and_clear_bindings();
_deleteFileRecordRecursively->bindValue(1, filename);
- if( !_deleteFileRecordRecursively->exec() ) {
+ if (!_deleteFileRecordRecursively->exec()) {
return false;
}
}
-SyncJournalFileRecord SyncJournalDb::getFileRecord(const QString& filename)
+SyncJournalFileRecord SyncJournalDb::getFileRecord(const QString &filename)
{
QMutexLocker locker(&_mutex);
- qlonglong phash = getPHash( filename );
+ qlonglong phash = getPHash(filename);
SyncJournalFileRecord rec;
- if( !filename.isEmpty() && checkConnect() ) {
+ if (!filename.isEmpty() && checkConnect()) {
_getFileRecordQuery->reset_and_clear_bindings();
_getFileRecordQuery->bindValue(1, QString::number(phash));
return rec;
}
- if( _getFileRecordQuery->next() ) {
- rec._path = _getFileRecordQuery->stringValue(0);
- rec._inode = _getFileRecordQuery->intValue(1);
+ if (_getFileRecordQuery->next()) {
+ rec._path = _getFileRecordQuery->stringValue(0);
+ rec._inode = _getFileRecordQuery->intValue(1);
//rec._uid = _getFileRecordQuery->value(2).toInt(&ok); Not Used
//rec._gid = _getFileRecordQuery->value(3).toInt(&ok); Not Used
//rec._mode = _getFileRecordQuery->intValue(4);
rec._modtime = Utility::qDateTimeFromTime_t(_getFileRecordQuery->int64Value(5));
- rec._type = _getFileRecordQuery->intValue(6);
- rec._etag = _getFileRecordQuery->baValue(7);
- rec._fileId = _getFileRecordQuery->baValue(8);
+ rec._type = _getFileRecordQuery->intValue(6);
+ rec._etag = _getFileRecordQuery->baValue(7);
+ rec._fileId = _getFileRecordQuery->baValue(8);
rec._remotePerm = _getFileRecordQuery->baValue(9);
- rec._fileSize = _getFileRecordQuery->int64Value(10);
+ rec._fileSize = _getFileRecordQuery->int64Value(10);
rec._serverHasIgnoredFiles = (_getFileRecordQuery->intValue(11) > 0);
rec._contentChecksum = _getFileRecordQuery->baValue(12);
- if( !_getFileRecordQuery->nullValue(13) ) {
+ if (!_getFileRecordQuery->nullValue(13)) {
rec._contentChecksumType = _getFileRecordQuery->baValue(13);
}
_getFileRecordQuery->reset_and_clear_bindings();
} else {
int errId = _getFileRecordQuery->errorId();
- if( errId != SQLITE_DONE ) { // only do this if the problem is different from SQLITE_DONE
+ if (errId != SQLITE_DONE) { // only do this if the problem is different from SQLITE_DONE
QString err = _getFileRecordQuery->error();
qCWarning(lcDb) << "No journal entry found for " << filename << "Error: " << err;
locker.unlock();
return rec;
}
-bool SyncJournalDb::postSyncCleanup(const QSet<QString>& filepathsToKeep,
- const QSet<QString>& prefixesToKeep)
+bool SyncJournalDb::postSyncCleanup(const QSet<QString> &filepathsToKeep,
+ const QSet<QString> &prefixesToKeep)
{
QMutexLocker locker(&_mutex);
- if( !checkConnect() ) {
+ if (!checkConnect()) {
return false;
}
QStringList superfluousItems;
- while(query.next()) {
+ while (query.next()) {
const QString file = query.stringValue(1);
bool keep = filepathsToKeep.contains(file);
- if( !keep ) {
- foreach( const QString & prefix, prefixesToKeep ) {
- if( file.startsWith(prefix) ) {
+ if (!keep) {
+ foreach (const QString &prefix, prefixesToKeep) {
+ if (file.startsWith(prefix)) {
keep = true;
break;
}
}
}
- if( !keep ) {
+ if (!keep) {
superfluousItems.append(query.stringValue(0));
}
}
- if( superfluousItems.count() ) {
- QString sql = "DELETE FROM metadata WHERE phash in ("+ superfluousItems.join(",")+")";
+ if (superfluousItems.count()) {
+ QString sql = "DELETE FROM metadata WHERE phash in (" + superfluousItems.join(",") + ")";
qCInfo(lcDb) << "Sync Journal cleanup for" << superfluousItems;
SqlQuery delQuery(_db);
delQuery.prepare(sql);
- if( !delQuery.exec() ) {
+ if (!delQuery.exec()) {
return false;
}
}
{
QMutexLocker locker(&_mutex);
- if( !checkConnect() ) {
+ if (!checkConnect()) {
return -1;
}
return 0;
}
-bool SyncJournalDb::updateFileRecordChecksum(const QString& filename,
- const QByteArray& contentChecksum,
- const QByteArray& contentChecksumType)
+bool SyncJournalDb::updateFileRecordChecksum(const QString &filename,
+ const QByteArray &contentChecksum,
+ const QByteArray &contentChecksumType)
{
QMutexLocker locker(&_mutex);
qCInfo(lcDb) << "Updating file checksum" << filename << contentChecksum << contentChecksumType;
qlonglong phash = getPHash(filename);
- if( !checkConnect() ) {
+ if (!checkConnect()) {
qCWarning(lcDb) << "Failed to connect database.";
return false;
}
int checksumTypeId = mapChecksumType(contentChecksumType);
- auto & query = _setFileRecordChecksumQuery;
+ auto &query = _setFileRecordChecksumQuery;
query->reset_and_clear_bindings();
query->bindValue(1, QString::number(phash));
query->bindValue(2, contentChecksum);
query->bindValue(3, checksumTypeId);
- if( !query->exec() ) {
+ if (!query->exec()) {
return false;
}
return true;
}
-bool SyncJournalDb::updateLocalMetadata(const QString& filename,
- qint64 modtime, quint64 size, quint64 inode)
+bool SyncJournalDb::updateLocalMetadata(const QString &filename,
+ qint64 modtime, quint64 size, quint64 inode)
{
QMutexLocker locker(&_mutex);
qCInfo(lcDb) << "Updating local metadata for:" << filename << modtime << size << inode;
qlonglong phash = getPHash(filename);
- if( !checkConnect() ) {
+ if (!checkConnect()) {
qCWarning(lcDb) << "Failed to connect database.";
return false;
}
- auto & query = _setFileRecordLocalMetadataQuery;
+ auto &query = _setFileRecordLocalMetadataQuery;
query->reset_and_clear_bindings();
query->bindValue(1, QString::number(phash));
query->bindValue(3, modtime);
query->bindValue(4, size);
- if( !query->exec() ) {
+ if (!query->exec()) {
return false;
}
return true;
}
-bool SyncJournalDb::setFileRecordMetadata(const SyncJournalFileRecord& record)
+bool SyncJournalDb::setFileRecordMetadata(const SyncJournalFileRecord &record)
{
SyncJournalFileRecord existing = getFileRecord(record._path);
return setFileRecord(existing);
}
-static void toDownloadInfo(SqlQuery &query, SyncJournalDb::DownloadInfo * res)
+static void toDownloadInfo(SqlQuery &query, SyncJournalDb::DownloadInfo *res)
{
bool ok = true;
- res->_tmpfile = query.stringValue(0);
- res->_etag = query.baValue(1);
+ res->_tmpfile = query.stringValue(0);
+ res->_etag = query.baValue(1);
res->_errorCount = query.intValue(2);
- res->_valid = ok;
+ res->_valid = ok;
}
-static bool deleteBatch(SqlQuery & query, const QStringList & entries, const QString & name)
+static bool deleteBatch(SqlQuery &query, const QStringList &entries, const QString &name)
{
if (entries.isEmpty())
return true;
qCDebug(lcDb) << "Removing stale " << qPrintable(name) << " entries: " << entries.join(", ");
// FIXME: Was ported from execBatch, check if correct!
- foreach( const QString& entry, entries ) {
+ foreach (const QString &entry, entries) {
query.reset_and_clear_bindings();
query.bindValue(1, entry);
if (!query.exec()) {
return true;
}
-SyncJournalDb::DownloadInfo SyncJournalDb::getDownloadInfo(const QString& file)
+SyncJournalDb::DownloadInfo SyncJournalDb::getDownloadInfo(const QString &file)
{
QMutexLocker locker(&_mutex);
DownloadInfo res;
- if( checkConnect() ) {
+ if (checkConnect()) {
_getDownloadInfoQuery->reset_and_clear_bindings();
_getDownloadInfoQuery->bindValue(1, file);
return res;
}
- if( _getDownloadInfoQuery->next() ) {
+ if (_getDownloadInfoQuery->next()) {
toDownloadInfo(*_getDownloadInfoQuery, &res);
} else {
res._valid = false;
return res;
}
-void SyncJournalDb::setDownloadInfo(const QString& file, const SyncJournalDb::DownloadInfo& i)
+void SyncJournalDb::setDownloadInfo(const QString &file, const SyncJournalDb::DownloadInfo &i)
{
QMutexLocker locker(&_mutex);
- if( !checkConnect() ) {
+ if (!checkConnect()) {
return;
}
_setDownloadInfoQuery->reset_and_clear_bindings();
_setDownloadInfoQuery->bindValue(1, file);
_setDownloadInfoQuery->bindValue(2, i._tmpfile);
- _setDownloadInfoQuery->bindValue(3, i._etag );
- _setDownloadInfoQuery->bindValue(4, i._errorCount );
+ _setDownloadInfoQuery->bindValue(3, i._etag);
+ _setDownloadInfoQuery->bindValue(4, i._errorCount);
- if( !_setDownloadInfoQuery->exec() ) {
+ if (!_setDownloadInfoQuery->exec()) {
return;
}
} else {
_deleteDownloadInfoQuery->reset_and_clear_bindings();
- _deleteDownloadInfoQuery->bindValue( 1, file );
+ _deleteDownloadInfoQuery->bindValue(1, file);
- if( !_deleteDownloadInfoQuery->exec() ) {
+ if (!_deleteDownloadInfoQuery->exec()) {
return;
}
}
}
-QVector<SyncJournalDb::DownloadInfo> SyncJournalDb::getAndDeleteStaleDownloadInfos(const QSet<QString>& keep)
+QVector<SyncJournalDb::DownloadInfo> SyncJournalDb::getAndDeleteStaleDownloadInfos(const QSet<QString> &keep)
{
QVector<SyncJournalDb::DownloadInfo> empty_result;
QMutexLocker locker(&_mutex);
int re = 0;
QMutexLocker locker(&_mutex);
- if( checkConnect() ) {
+ if (checkConnect()) {
SqlQuery query("SELECT count(*) FROM downloadinfo", _db);
- if( ! query.exec() ) {
+ if (!query.exec()) {
sqlFail("Count number of downloadinfo entries failed", query);
}
- if( query.next() ) {
+ if (query.next()) {
re = query.intValue(0);
}
}
return re;
}
-SyncJournalDb::UploadInfo SyncJournalDb::getUploadInfo(const QString& file)
+SyncJournalDb::UploadInfo SyncJournalDb::getUploadInfo(const QString &file)
{
QMutexLocker locker(&_mutex);
UploadInfo res;
- if( checkConnect() ) {
-
+ if (checkConnect()) {
_getUploadInfoQuery->reset_and_clear_bindings();
_getUploadInfoQuery->bindValue(1, file);
return res;
}
- if( _getUploadInfoQuery->next() ) {
+ if (_getUploadInfoQuery->next()) {
bool ok = true;
- res._chunk = _getUploadInfoQuery->intValue(0);
+ res._chunk = _getUploadInfoQuery->intValue(0);
res._transferid = _getUploadInfoQuery->intValue(1);
res._errorCount = _getUploadInfoQuery->intValue(2);
- res._size = _getUploadInfoQuery->int64Value(3);
- res._modtime = Utility::qDateTimeFromTime_t(_getUploadInfoQuery->int64Value(4));
- res._valid = ok;
+ res._size = _getUploadInfoQuery->int64Value(3);
+ res._modtime = Utility::qDateTimeFromTime_t(_getUploadInfoQuery->int64Value(4));
+ res._valid = ok;
}
_getUploadInfoQuery->reset_and_clear_bindings();
}
return res;
}
-void SyncJournalDb::setUploadInfo(const QString& file, const SyncJournalDb::UploadInfo& i)
+void SyncJournalDb::setUploadInfo(const QString &file, const SyncJournalDb::UploadInfo &i)
{
QMutexLocker locker(&_mutex);
- if( !checkConnect() ) {
+ if (!checkConnect()) {
return;
}
_setUploadInfoQuery->reset_and_clear_bindings();
_setUploadInfoQuery->bindValue(1, file);
_setUploadInfoQuery->bindValue(2, i._chunk);
- _setUploadInfoQuery->bindValue(3, i._transferid );
- _setUploadInfoQuery->bindValue(4, i._errorCount );
- _setUploadInfoQuery->bindValue(5, i._size );
- _setUploadInfoQuery->bindValue(6, Utility::qDateTimeToTime_t(i._modtime) );
+ _setUploadInfoQuery->bindValue(3, i._transferid);
+ _setUploadInfoQuery->bindValue(4, i._errorCount);
+ _setUploadInfoQuery->bindValue(5, i._size);
+ _setUploadInfoQuery->bindValue(6, Utility::qDateTimeToTime_t(i._modtime));
- if( !_setUploadInfoQuery->exec() ) {
+ if (!_setUploadInfoQuery->exec()) {
return;
}
_deleteUploadInfoQuery->reset_and_clear_bindings();
_deleteUploadInfoQuery->bindValue(1, file);
- if( !_deleteUploadInfoQuery->exec() ) {
+ if (!_deleteUploadInfoQuery->exec()) {
return;
}
return ids;
}
-SyncJournalErrorBlacklistRecord SyncJournalDb::errorBlacklistEntry( const QString& file )
+SyncJournalErrorBlacklistRecord SyncJournalDb::errorBlacklistEntry(const QString &file)
{
QMutexLocker locker(&_mutex);
SyncJournalErrorBlacklistRecord entry;
- if( file.isEmpty() ) return entry;
+ if (file.isEmpty())
+ return entry;
// SELECT lastTryEtag, lastTryModtime, retrycount, errorstring
- if( checkConnect() ) {
+ if (checkConnect()) {
_getErrorBlacklistQuery->reset_and_clear_bindings();
- _getErrorBlacklistQuery->bindValue( 1, file );
- if( _getErrorBlacklistQuery->exec() ){
- if( _getErrorBlacklistQuery->next() ) {
- entry._lastTryEtag = _getErrorBlacklistQuery->baValue(0);
+ _getErrorBlacklistQuery->bindValue(1, file);
+ if (_getErrorBlacklistQuery->exec()) {
+ if (_getErrorBlacklistQuery->next()) {
+ entry._lastTryEtag = _getErrorBlacklistQuery->baValue(0);
entry._lastTryModtime = _getErrorBlacklistQuery->int64Value(1);
- entry._retryCount = _getErrorBlacklistQuery->intValue(2);
- entry._errorString = _getErrorBlacklistQuery->stringValue(3);
- entry._lastTryTime = _getErrorBlacklistQuery->int64Value(4);
+ entry._retryCount = _getErrorBlacklistQuery->intValue(2);
+ entry._errorString = _getErrorBlacklistQuery->stringValue(3);
+ entry._lastTryTime = _getErrorBlacklistQuery->int64Value(4);
entry._ignoreDuration = _getErrorBlacklistQuery->int64Value(5);
- entry._renameTarget = _getErrorBlacklistQuery->stringValue(6);
- entry._file = file;
+ entry._renameTarget = _getErrorBlacklistQuery->stringValue(6);
+ entry._file = file;
}
_getErrorBlacklistQuery->reset_and_clear_bindings();
}
int re = 0;
QMutexLocker locker(&_mutex);
- if( checkConnect() ) {
+ if (checkConnect()) {
SqlQuery query("SELECT count(*) FROM blacklist", _db);
- if( ! query.exec() ) {
+ if (!query.exec()) {
sqlFail("Count number of blacklist entries failed", query);
}
- if( query.next() ) {
+ if (query.next()) {
re = query.intValue(0);
}
}
int SyncJournalDb::wipeErrorBlacklist()
{
QMutexLocker locker(&_mutex);
- if( checkConnect() ) {
+ if (checkConnect()) {
SqlQuery query(_db);
query.prepare("DELETE FROM blacklist");
- if( ! query.exec() ) {
+ if (!query.exec()) {
sqlFail("Deletion of whole blacklist failed", query);
return -1;
}
return -1;
}
-void SyncJournalDb::wipeErrorBlacklistEntry( const QString& file )
+void SyncJournalDb::wipeErrorBlacklistEntry(const QString &file)
{
- if( file.isEmpty() ) {
+ if (file.isEmpty()) {
return;
}
QMutexLocker locker(&_mutex);
- if( checkConnect() ) {
+ if (checkConnect()) {
SqlQuery query(_db);
query.prepare("DELETE FROM blacklist WHERE path=?1");
query.bindValue(1, file);
- if( ! query.exec() ) {
+ if (!query.exec()) {
sqlFail("Deletion of blacklist item failed.", query);
}
}
}
-void SyncJournalDb::updateErrorBlacklistEntry( const SyncJournalErrorBlacklistRecord& item )
+void SyncJournalDb::updateErrorBlacklistEntry(const SyncJournalErrorBlacklistRecord &item)
{
QMutexLocker locker(&_mutex);
qCInfo(lcDb) << "Setting blacklist entry for " << item._file << item._retryCount
- << item._errorString << item._lastTryTime << item._ignoreDuration
- << item._lastTryModtime << item._lastTryEtag << item._renameTarget ;
+ << item._errorString << item._lastTryTime << item._ignoreDuration
+ << item._lastTryModtime << item._lastTryEtag << item._renameTarget;
- if( !checkConnect() ) {
+ if (!checkConnect()) {
return;
}
_setErrorBlacklistQuery->bindValue(8, item._renameTarget);
_setErrorBlacklistQuery->exec();
_setErrorBlacklistQuery->reset_and_clear_bindings();
-
}
-QVector< SyncJournalDb::PollInfo > SyncJournalDb::getPollInfos()
+QVector<SyncJournalDb::PollInfo> SyncJournalDb::getPollInfos()
{
QMutexLocker locker(&_mutex);
- QVector< SyncJournalDb::PollInfo > res;
+ QVector<SyncJournalDb::PollInfo> res;
- if( !checkConnect() )
+ if (!checkConnect())
return res;
- SqlQuery query("SELECT path, modtime, pollpath FROM poll",_db);
+ SqlQuery query("SELECT path, modtime, pollpath FROM poll", _db);
if (!query.exec()) {
return res;
}
- while( query.next() ) {
+ while (query.next()) {
PollInfo info;
info._file = query.stringValue(0);
info._modtime = query.int64Value(1);
return res;
}
-void SyncJournalDb::setPollInfo(const SyncJournalDb::PollInfo& info)
+void SyncJournalDb::setPollInfo(const SyncJournalDb::PollInfo &info)
{
QMutexLocker locker(&_mutex);
- if( !checkConnect() ) {
+ if (!checkConnect()) {
return;
}
}
}
-QStringList SyncJournalDb::getSelectiveSyncList(SyncJournalDb::SelectiveSyncListType type, bool *ok )
+QStringList SyncJournalDb::getSelectiveSyncList(SyncJournalDb::SelectiveSyncListType type, bool *ok)
{
QStringList result;
ASSERT(ok);
QMutexLocker locker(&_mutex);
- if( !checkConnect() ) {
+ if (!checkConnect()) {
*ok = false;
return result;
}
*ok = false;
return result;
}
- while( _getSelectiveSyncListQuery->next() ) {
+ while (_getSelectiveSyncListQuery->next()) {
auto entry = _getSelectiveSyncListQuery->stringValue(0);
if (!entry.endsWith(QLatin1Char('/'))) {
entry.append(QLatin1Char('/'));
return result;
}
-void SyncJournalDb::setSelectiveSyncList(SyncJournalDb::SelectiveSyncListType type, const QStringList& list)
+void SyncJournalDb::setSelectiveSyncList(SyncJournalDb::SelectiveSyncListType type, const QStringList &list)
{
QMutexLocker locker(&_mutex);
- if( !checkConnect() ) {
+ if (!checkConnect()) {
return;
}
//first, delete all entries of this type
SqlQuery delQuery("DELETE FROM selectivesync WHERE type == ?1", _db);
delQuery.bindValue(1, int(type));
- if( !delQuery.exec() ) {
+ if (!delQuery.exec()) {
qCWarning(lcDb) << "SQL error when deleting selective sync list" << list << delQuery.error();
}
- SqlQuery insQuery("INSERT INTO selectivesync VALUES (?1, ?2)" , _db);
- foreach(const auto &path, list) {
+ SqlQuery insQuery("INSERT INTO selectivesync VALUES (?1, ?2)", _db);
+ foreach (const auto &path, list) {
insQuery.reset_and_clear_bindings();
insQuery.bindValue(1, path);
insQuery.bindValue(2, int(type));
}
}
-void SyncJournalDb::avoidRenamesOnNextSync(const QString& path)
+void SyncJournalDb::avoidRenamesOnNextSync(const QString &path)
{
QMutexLocker locker(&_mutex);
- if( !checkConnect() ) {
+ if (!checkConnect()) {
return;
}
avoidReadFromDbOnNextSync(path);
}
-void SyncJournalDb::avoidReadFromDbOnNextSync(const QString& fileName)
+void SyncJournalDb::avoidReadFromDbOnNextSync(const QString &fileName)
{
// Make sure that on the next sync, fileName is not read from the DB but uses the PROPFIND to
// get the info from the server
QMutexLocker locker(&_mutex);
- if( !checkConnect() ) {
+ if (!checkConnect()) {
return;
}
{
QMutexLocker locker(&_mutex);
- if( !checkConnect() ) {
+ if (!checkConnect()) {
return;
}
QByteArray SyncJournalDb::getChecksumType(int checksumTypeId)
{
QMutexLocker locker(&_mutex);
- if( !checkConnect() ) {
+ if (!checkConnect()) {
return QByteArray();
}
// Retrieve the id
- auto & query = *_getChecksumTypeQuery;
+ auto &query = *_getChecksumTypeQuery;
query.reset_and_clear_bindings();
query.bindValue(1, checksumTypeId);
- if( !query.exec() ) {
+ if (!query.exec()) {
return 0;
}
- if( !query.next() ) {
+ if (!query.next()) {
qCWarning(lcDb) << "No checksum type mapping found for" << checksumTypeId;
return 0;
}
return query.baValue(0);
}
-int SyncJournalDb::mapChecksumType(const QByteArray& checksumType)
+int SyncJournalDb::mapChecksumType(const QByteArray &checksumType)
{
if (checksumType.isEmpty()) {
return 0;
// Ensure the checksum type is in the db
_insertChecksumTypeQuery->reset_and_clear_bindings();
_insertChecksumTypeQuery->bindValue(1, checksumType);
- if( !_insertChecksumTypeQuery->exec() ) {
+ if (!_insertChecksumTypeQuery->exec()) {
return 0;
}
// Retrieve the id
_getChecksumTypeIdQuery->reset_and_clear_bindings();
_getChecksumTypeIdQuery->bindValue(1, checksumType);
- if( !_getChecksumTypeIdQuery->exec() ) {
+ if (!_getChecksumTypeIdQuery->exec()) {
return 0;
}
- if( !_getChecksumTypeIdQuery->next() ) {
+ if (!_getChecksumTypeIdQuery->next()) {
qCWarning(lcDb) << "No checksum type mapping found for" << checksumType;
return 0;
}
query.exec();
}
-void SyncJournalDb::commit(const QString& context, bool startTrans)
+void SyncJournalDb::commit(const QString &context, bool startTrans)
{
QMutexLocker lock(&_mutex);
commitInternal(context, startTrans);
void SyncJournalDb::commitIfNeededAndStartNewTransaction(const QString &context)
{
QMutexLocker lock(&_mutex);
- if( _transaction == 1 ) {
+ if (_transaction == 1) {
commitInternal(context, true);
} else {
startTransaction();
}
-void SyncJournalDb::commitInternal(const QString& context, bool startTrans )
+void SyncJournalDb::commitInternal(const QString &context, bool startTrans)
{
qCDebug(lcDb) << "Transaction commit " << context << (startTrans ? "and starting new transaction" : "");
commitTransaction();
- if( startTrans ) {
+ if (startTrans) {
startTransaction();
}
}
return checkConnect();
}
-bool operator==(const SyncJournalDb::DownloadInfo & lhs,
- const SyncJournalDb::DownloadInfo & rhs)
+bool operator==(const SyncJournalDb::DownloadInfo &lhs,
+ const SyncJournalDb::DownloadInfo &rhs)
{
- return lhs._errorCount == rhs._errorCount
- && lhs._etag == rhs._etag
- && lhs._tmpfile == rhs._tmpfile
- && lhs._valid == rhs._valid;
-
+ return lhs._errorCount == rhs._errorCount
+ && lhs._etag == rhs._etag
+ && lhs._tmpfile == rhs._tmpfile
+ && lhs._valid == rhs._valid;
}
-bool operator==(const SyncJournalDb::UploadInfo & lhs,
- const SyncJournalDb::UploadInfo & rhs)
+bool operator==(const SyncJournalDb::UploadInfo &lhs,
+ const SyncJournalDb::UploadInfo &rhs)
{
- return lhs._errorCount == rhs._errorCount
- && lhs._chunk == rhs._chunk
- && lhs._modtime == rhs._modtime
- && lhs._valid == rhs._valid
- && lhs._size == rhs._size
- && lhs._transferid == rhs._transferid;
+ return lhs._errorCount == rhs._errorCount
+ && lhs._chunk == rhs._chunk
+ && lhs._modtime == rhs._modtime
+ && lhs._valid == rhs._valid
+ && lhs._size == rhs._size
+ && lhs._transferid == rhs._transferid;
}
} // namespace OCC
{
Q_OBJECT
public:
- explicit SyncJournalDb(const QString& dbFilePath, QObject *parent = 0);
+ explicit SyncJournalDb(const QString &dbFilePath, QObject *parent = 0);
virtual ~SyncJournalDb();
/// Create a journal path for a specific configuration
- static QString makeDbName(const QUrl& remoteUrl,
- const QString& remotePath,
- const QString& user);
+ static QString makeDbName(const QUrl &remoteUrl,
+ const QString &remotePath,
+ const QString &user);
/// Migrate a csync_journal to the new path, if necessary. Returns false on error
- static bool maybeMigrateDb(const QString& localPath, const QString& absoluteJournalPath);
+ static bool maybeMigrateDb(const QString &localPath, const QString &absoluteJournalPath);
// to verify that the record could be queried successfully check
// with SyncJournalFileRecord::isValid()
- SyncJournalFileRecord getFileRecord(const QString& filename);
- bool setFileRecord( const SyncJournalFileRecord& record );
+ SyncJournalFileRecord getFileRecord(const QString &filename);
+ bool setFileRecord(const SyncJournalFileRecord &record);
/// Like setFileRecord, but preserves checksums
- bool setFileRecordMetadata( const SyncJournalFileRecord& record );
+ bool setFileRecordMetadata(const SyncJournalFileRecord &record);
- bool deleteFileRecord( const QString& filename, bool recursively = false );
+ bool deleteFileRecord(const QString &filename, bool recursively = false);
int getFileRecordCount();
- bool updateFileRecordChecksum(const QString& filename,
- const QByteArray& contentChecksum,
- const QByteArray& contentChecksumType);
- bool updateLocalMetadata(const QString& filename,
- qint64 modtime, quint64 size, quint64 inode);
+ bool updateFileRecordChecksum(const QString &filename,
+ const QByteArray &contentChecksum,
+ const QByteArray &contentChecksumType);
+ bool updateLocalMetadata(const QString &filename,
+ qint64 modtime, quint64 size, quint64 inode);
bool exists();
void walCheckpoint();
QString databaseFilePath() const;
- static qint64 getPHash(const QString& );
+ static qint64 getPHash(const QString &);
- void updateErrorBlacklistEntry( const SyncJournalErrorBlacklistRecord& item );
- void wipeErrorBlacklistEntry(const QString& file);
+ void updateErrorBlacklistEntry(const SyncJournalErrorBlacklistRecord &item);
+ void wipeErrorBlacklistEntry(const QString &file);
int wipeErrorBlacklist();
int errorBlackListEntryCount();
- struct DownloadInfo {
- DownloadInfo() : _errorCount(0), _valid(false) {}
+ struct DownloadInfo
+ {
+ DownloadInfo()
+ : _errorCount(0)
+ , _valid(false)
+ {
+ }
QString _tmpfile;
QByteArray _etag;
int _errorCount;
bool _valid;
};
- struct UploadInfo {
- UploadInfo() : _chunk(0), _transferid(0), _size(0), _errorCount(0), _valid(false) {}
+ struct UploadInfo
+ {
+ UploadInfo()
+ : _chunk(0)
+ , _transferid(0)
+ , _size(0)
+ , _errorCount(0)
+ , _valid(false)
+ {
+ }
int _chunk;
int _transferid;
quint64 _size; //currently unused
bool _valid;
};
- struct PollInfo {
+ struct PollInfo
+ {
QString _file;
QString _url;
time_t _modtime;
DownloadInfo getDownloadInfo(const QString &file);
void setDownloadInfo(const QString &file, const DownloadInfo &i);
- QVector<DownloadInfo> getAndDeleteStaleDownloadInfos(const QSet<QString>& keep);
+ QVector<DownloadInfo> getAndDeleteStaleDownloadInfos(const QSet<QString> &keep);
int downloadInfoCount();
UploadInfo getUploadInfo(const QString &file);
void setUploadInfo(const QString &file, const UploadInfo &i);
// Return the list of transfer ids that were removed.
- QVector<uint> deleteStaleUploadInfos(const QSet<QString>& keep);
+ QVector<uint> deleteStaleUploadInfos(const QSet<QString> &keep);
- SyncJournalErrorBlacklistRecord errorBlacklistEntry( const QString& );
- bool deleteStaleErrorBlacklistEntries(const QSet<QString>& keep);
+ SyncJournalErrorBlacklistRecord errorBlacklistEntry(const QString &);
+ bool deleteStaleErrorBlacklistEntries(const QSet<QString> &keep);
void avoidRenamesOnNextSync(const QString &path);
void setPollInfo(const PollInfo &);
* Make sure that on the next sync, fileName is not read from the DB but uses the PROPFIND to
* get the info from the server
*/
- void avoidReadFromDbOnNextSync(const QString& fileName);
+ void avoidReadFromDbOnNextSync(const QString &fileName);
/**
* Ensures full remote discovery happens on the next sync.
*/
void forceRemoteDiscoveryNextSync();
- bool postSyncCleanup(const QSet<QString>& filepathsToKeep,
- const QSet<QString>& prefixesToKeep);
+ bool postSyncCleanup(const QSet<QString> &filepathsToKeep,
+ const QSet<QString> &prefixesToKeep);
/* Because sqlite transactions are really slow, we encapsulate everything in big transactions
* Commit will actually commit the transaction and create a new one.
bool updateDatabaseStructure();
bool updateMetadataTableStructure();
bool updateErrorBlacklistTableStructure();
- bool sqlFail(const QString& log, const SqlQuery &query );
+ bool sqlFail(const QString &log, const SqlQuery &query);
void commitInternal(const QString &context, bool startTrans = true);
void startTransaction();
void commitTransaction();
- QStringList tableColumns( const QString& table );
+ QStringList tableColumns(const QString &table);
bool checkConnect();
// Same as forceRemoteDiscoveryNextSync but without acquiring the lock
// Returns the integer id of the checksum type
//
// Returns 0 on failure and for empty checksum types.
- int mapChecksumType(const QByteArray& checksumType);
+ int mapChecksumType(const QByteArray &checksumType);
SqlDatabase _db;
QString _dbFile;
};
bool OWNCLOUDSYNC_EXPORT
-operator==(const SyncJournalDb::DownloadInfo & lhs,
- const SyncJournalDb::DownloadInfo & rhs);
+operator==(const SyncJournalDb::DownloadInfo &lhs,
+ const SyncJournalDb::DownloadInfo &rhs);
bool OWNCLOUDSYNC_EXPORT
-operator==(const SyncJournalDb::UploadInfo & lhs,
- const SyncJournalDb::UploadInfo & rhs);
+operator==(const SyncJournalDb::UploadInfo &lhs,
+ const SyncJournalDb::UploadInfo &rhs);
-} // namespace OCC
+} // namespace OCC
#endif // SYNCJOURNALDB_H
Q_LOGGING_CATEGORY(lcFileRecord, "sync.database.filerecord", QtInfoMsg)
SyncJournalFileRecord::SyncJournalFileRecord()
- :_inode(0), _type(0), _fileSize(0), _serverHasIgnoredFiles(false)
+ : _inode(0)
+ , _type(0)
+ , _fileSize(0)
+ , _serverHasIgnoredFiles(false)
{
}
SyncJournalFileRecord::SyncJournalFileRecord(const SyncFileItem &item, const QString &localFileName)
- : _path(item._file), _modtime(Utility::qDateTimeFromTime_t(item._modtime)),
- _type(item._type), _etag(item._etag), _fileId(item._fileId), _fileSize(item._size),
- _remotePerm(item._remotePerm), _serverHasIgnoredFiles(item._serverHasIgnoredFiles),
- _contentChecksum(item._contentChecksum),
- _contentChecksumType(item._contentChecksumType)
+ : _path(item._file)
+ , _modtime(Utility::qDateTimeFromTime_t(item._modtime))
+ , _type(item._type)
+ , _etag(item._etag)
+ , _fileId(item._fileId)
+ , _fileSize(item._size)
+ , _remotePerm(item._remotePerm)
+ , _serverHasIgnoredFiles(item._serverHasIgnoredFiles)
+ , _contentChecksum(item._contentChecksum)
+ , _contentChecksumType(item._contentChecksumType)
{
// use the "old" inode coming with the item for the case where the
// filesystem stat fails. That can happen if the the file was removed
based on code from csync_vio_local.c (csync_vio_local_stat)
Get the Windows file id as an inode replacement. */
- HANDLE h = CreateFileW( (wchar_t*) FileSystem::longWinPath(localFileName).utf16(), 0, FILE_SHARE_READ, NULL, OPEN_EXISTING,
- FILE_ATTRIBUTE_NORMAL+FILE_FLAG_BACKUP_SEMANTICS, NULL );
+ HANDLE h = CreateFileW((wchar_t *)FileSystem::longWinPath(localFileName).utf16(), 0, FILE_SHARE_READ, NULL, OPEN_EXISTING,
+ FILE_ATTRIBUTE_NORMAL + FILE_FLAG_BACKUP_SEMANTICS, NULL);
- if( h == INVALID_HANDLE_VALUE ) {
+ if (h == INVALID_HANDLE_VALUE) {
qCWarning(lcFileRecord) << "Failed to query the 'inode' because CreateFileW failed for file " << localFileName;
} else {
BY_HANDLE_FILE_INFORMATION fileInfo;
- if( GetFileInformationByHandle( h, &fileInfo ) ) {
+ if (GetFileInformationByHandle(h, &fileInfo)) {
ULARGE_INTEGER FileIndex;
FileIndex.HighPart = fileInfo.nFileIndexHigh;
FileIndex.LowPart = fileInfo.nFileIndexLow;
_inode = FileIndex.QuadPart;
} else {
qCWarning(lcFileRecord) << "Failed to query the 'inode' for file " << localFileName;
-
}
CloseHandle(h);
}
#else
struct stat sb;
- if( stat(QFile::encodeName(localFileName).constData(), &sb) < 0) {
+ if (stat(QFile::encodeName(localFileName).constData(), &sb) < 0) {
qCWarning(lcFileRecord) << "Failed to query the 'inode' for file " << localFileName;
} else {
_inode = sb.st_ino;
}
#endif
qCDebug(lcFileRecord) << localFileName << "Retrieved inode " << _inode << "(previous item inode: " << item._inode << ")";
-
}
SyncFileItem SyncJournalFileRecord::toSyncFileItem()
bool SyncJournalErrorBlacklistRecord::isValid() const
{
- return ! _file.isEmpty()
+ return !_file.isEmpty()
&& (!_lastTryEtag.isEmpty() || _lastTryModtime != 0)
&& _lastTryTime > 0;
}
-bool operator==(const SyncJournalFileRecord & lhs,
- const SyncJournalFileRecord & rhs)
+bool operator==(const SyncJournalFileRecord &lhs,
+ const SyncJournalFileRecord &rhs)
{
- return lhs._path == rhs._path
- && lhs._inode == rhs._inode
- && lhs._modtime.toTime_t() == rhs._modtime.toTime_t()
- && lhs._type == rhs._type
- && lhs._etag == rhs._etag
- && lhs._fileId == rhs._fileId
- && lhs._fileSize == rhs._fileSize
- && lhs._remotePerm == rhs._remotePerm
- && lhs._serverHasIgnoredFiles == rhs._serverHasIgnoredFiles
- && lhs._contentChecksum == rhs._contentChecksum
- && lhs._contentChecksumType == rhs._contentChecksumType;
+ return lhs._path == rhs._path
+ && lhs._inode == rhs._inode
+ && lhs._modtime.toTime_t() == rhs._modtime.toTime_t()
+ && lhs._type == rhs._type
+ && lhs._etag == rhs._etag
+ && lhs._fileId == rhs._fileId
+ && lhs._fileSize == rhs._fileSize
+ && lhs._remotePerm == rhs._remotePerm
+ && lhs._serverHasIgnoredFiles == rhs._serverHasIgnoredFiles
+ && lhs._contentChecksum == rhs._contentChecksum
+ && lhs._contentChecksumType == rhs._contentChecksumType;
}
-
}
SyncJournalFileRecord();
/// Creates a record from an existing item while updating the inode
- SyncJournalFileRecord(const SyncFileItem&, const QString &localFileName);
+ SyncJournalFileRecord(const SyncFileItem &, const QString &localFileName);
/** Creates a basic SyncFileItem from the record
*
*/
SyncFileItem toSyncFileItem();
- bool isValid() {
+ bool isValid()
+ {
return !_path.isEmpty();
}
- QString _path;
- quint64 _inode;
- QDateTime _modtime;
- int _type;
+ QString _path;
+ quint64 _inode;
+ QDateTime _modtime;
+ int _type;
QByteArray _etag;
QByteArray _fileId;
- qint64 _fileSize;
+ qint64 _fileSize;
QByteArray _remotePerm;
- bool _serverHasIgnoredFiles;
+ bool _serverHasIgnoredFiles;
QByteArray _contentChecksum;
QByteArray _contentChecksumType;
};
bool OWNCLOUDSYNC_EXPORT
-operator==(const SyncJournalFileRecord & lhs,
- const SyncJournalFileRecord & rhs);
+operator==(const SyncJournalFileRecord &lhs,
+ const SyncJournalFileRecord &rhs);
class SyncJournalErrorBlacklistRecord
{
, _lastTryModtime(0)
, _lastTryTime(0)
, _ignoreDuration(0)
- {}
+ {
+ }
/// The number of times the operation was unsuccessful so far.
- int _retryCount;
+ int _retryCount;
/// The last error string.
- QString _errorString;
+ QString _errorString;
- time_t _lastTryModtime;
+ time_t _lastTryModtime;
QByteArray _lastTryEtag;
/// The last time the operation was attempted (in s since epoch).
- time_t _lastTryTime;
+ time_t _lastTryTime;
/// The number of seconds the file shall be ignored.
- time_t _ignoreDuration;
+ time_t _ignoreDuration;
- QString _file;
- QString _renameTarget;
+ QString _file;
+ QString _renameTarget;
bool isValid() const;
};
-
}
#endif // SYNCJOURNALFILERECORD_H
#include "syncresult.h"
#include "progressdispatcher.h"
-namespace OCC
-{
+namespace OCC {
SyncResult::SyncResult()
- : _status( Undefined )
+ : _status(Undefined)
, _foundFilesNotSynced(false)
, _folderStructureWasChanged(false)
, _numNewItems(0)
QString re;
Status stat = status();
- switch( stat ){
+ switch (stat) {
case Undefined:
re = QLatin1String("Undefined");
break;
return re;
}
-void SyncResult::setStatus( Status stat )
+void SyncResult::setStatus(Status stat)
{
_status = stat;
_syncTime = QDateTime::currentDateTime();
return _errors;
}
-void SyncResult::appendErrorString( const QString& err )
+void SyncResult::appendErrorString(const QString &err)
{
- _errors.append( err );
+ _errors.append(err);
}
QString SyncResult::errorString() const
{
- if( _errors.isEmpty() ) return QString::null;
+ if (_errors.isEmpty())
+ return QString::null;
return _errors.first();
}
_errors.clear();
}
-void SyncResult::setFolder(const QString& folder)
+void SyncResult::setFolder(const QString &folder)
{
_folder = folder;
}
}
if (item->_isDirectory && (item->_instruction == CSYNC_INSTRUCTION_NEW
- || item->_instruction == CSYNC_INSTRUCTION_TYPE_CHANGE
- || item->_instruction == CSYNC_INSTRUCTION_REMOVE
- || item->_instruction == CSYNC_INSTRUCTION_RENAME)) {
+ || item->_instruction == CSYNC_INSTRUCTION_TYPE_CHANGE
+ || item->_instruction == CSYNC_INSTRUCTION_REMOVE
+ || item->_instruction == CSYNC_INSTRUCTION_RENAME)) {
_folderStructureWasChanged = true;
}
// Process the item to the gui
- if( item->_status == SyncFileItem::FatalError || item->_status == SyncFileItem::NormalError ) {
+ if (item->_status == SyncFileItem::FatalError || item->_status == SyncFileItem::NormalError) {
//: this displays an error string (%2) for a file %1
- appendErrorString( QObject::tr("%1: %2").arg(item->_file, item->_errorString) );
+ appendErrorString(QObject::tr("%1: %2").arg(item->_file, item->_errorString));
_numErrorItems++;
if (!_firstItemError) {
_firstItemError = item;
}
- } else if( item->_status == SyncFileItem::Conflict ) {
+ } else if (item->_status == SyncFileItem::Conflict) {
_numConflictItems++;
if (!_firstConflictItem) {
_firstConflictItem = item;
// nothing.
break;
}
- } else if( item->_direction == SyncFileItem::None ) {
- if( item->_instruction == CSYNC_INSTRUCTION_IGNORE ) {
+ } else if (item->_direction == SyncFileItem::None) {
+ if (item->_instruction == CSYNC_INSTRUCTION_IGNORE) {
_foundFilesNotSynced = true;
}
}
}
-
}
} // ns mirall
#include "owncloudlib.h"
#include "syncfileitem.h"
-namespace OCC
-{
+namespace OCC {
/**
* @brief The SyncResult class
class OWNCLOUDSYNC_EXPORT SyncResult
{
public:
- enum Status
- {
- Undefined,
- NotYetStarted,
- SyncPrepare,
- SyncRunning,
- SyncAbortRequested,
- Success,
- Problem,
- Error,
- SetupError,
- Paused
+ enum Status {
+ Undefined,
+ NotYetStarted,
+ SyncPrepare,
+ SyncRunning,
+ SyncAbortRequested,
+ Success,
+ Problem,
+ Error,
+ SetupError,
+ Paused
};
SyncResult();
void reset();
- void appendErrorString( const QString& );
+ void appendErrorString(const QString &);
QString errorString() const;
QStringList errorStrings() const;
- void clearErrors();
+ void clearErrors();
- void setStatus( Status );
+ void setStatus(Status);
Status status() const;
QString statusString() const;
QDateTime syncTime() const;
- void setFolder(const QString& folder);
+ void setFolder(const QString &folder);
QString folder() const;
bool foundFilesNotSynced() const { return _foundFilesNotSynced; }
int numConflictItems() const { return _numConflictItems; }
int numErrorItems() const { return _numErrorItems; }
- const SyncFileItemPtr& firstItemNew() const { return _firstItemNew; }
- const SyncFileItemPtr& firstItemDeleted() const { return _firstItemDeleted; }
- const SyncFileItemPtr& firstItemUpdated() const { return _firstItemUpdated; }
- const SyncFileItemPtr& firstItemRenamed() const { return _firstItemRenamed; }
- const SyncFileItemPtr& firstConflictItem() const { return _firstConflictItem; }
- const SyncFileItemPtr& firstItemError() const { return _firstItemError; }
+ const SyncFileItemPtr &firstItemNew() const { return _firstItemNew; }
+ const SyncFileItemPtr &firstItemDeleted() const { return _firstItemDeleted; }
+ const SyncFileItemPtr &firstItemUpdated() const { return _firstItemUpdated; }
+ const SyncFileItemPtr &firstItemRenamed() const { return _firstItemRenamed; }
+ const SyncFileItemPtr &firstConflictItem() const { return _firstConflictItem; }
+ const SyncFileItemPtr &firstItemError() const { return _firstItemError; }
void processCompletedItem(const SyncFileItemPtr &item);
private:
- Status _status;
+ Status _status;
SyncFileItemVector _syncItems;
- QDateTime _syncTime;
- QString _folder;
+ QDateTime _syncTime;
+ QString _folder;
/**
* when the sync tool support this...
*/
- QStringList _errors;
+ QStringList _errors;
bool _foundFilesNotSynced;
bool _folderStructureWasChanged;
SyncFileItemPtr _firstConflictItem;
SyncFileItemPtr _firstItemError;
};
-
}
#endif
#include "owncloudtheme.h"
#ifdef THEME_INCLUDE
-# define Mirall OCC // namespace hack to make old themes work
-# define QUOTEME(M) #M
-# define INCLUDE_FILE(M) QUOTEME(M)
-# include INCLUDE_FILE(THEME_INCLUDE)
-# undef Mirall
+#define Mirall OCC // namespace hack to make old themes work
+#define QUOTEME(M) #M
+#define INCLUDE_FILE(M) QUOTEME(M)
+#include INCLUDE_FILE(THEME_INCLUDE)
+#undef Mirall
#endif
namespace OCC {
-Theme* Theme::_instance = 0;
+Theme *Theme::_instance = 0;
-Theme* Theme::instance() {
+Theme *Theme::instance()
+{
if (!_instance) {
_instance = new THEME_CLASS;
// some themes may not call the base ctor
return _instance;
}
-Theme::~Theme() {}
+Theme::~Theme()
+{
+}
-QString Theme::statusHeaderText( SyncResult::Status status ) const
+QString Theme::statusHeaderText(SyncResult::Status status) const
{
QString resultStr;
- switch( status ) {
+ switch (status) {
case SyncResult::Undefined:
resultStr = QCoreApplication::translate("theme", "Status undefined");
break;
resultStr = QCoreApplication::translate("theme", "Sync Error");
break;
case SyncResult::SetupError:
- resultStr = QCoreApplication::translate("theme", "Setup Error" );
+ resultStr = QCoreApplication::translate("theme", "Setup Error");
break;
case SyncResult::SyncPrepare:
- resultStr = QCoreApplication::translate("theme", "Preparing to sync" );
+ resultStr = QCoreApplication::translate("theme", "Preparing to sync");
break;
case SyncResult::SyncAbortRequested:
- resultStr = QCoreApplication::translate("theme", "Aborting..." );
+ resultStr = QCoreApplication::translate("theme", "Aborting...");
break;
case SyncResult::Paused:
resultStr = QCoreApplication::translate("theme", "Sync is paused");
#ifndef TOKEN_AUTH_ONLY
-QIcon Theme::trayFolderIcon( const QString& backend ) const
+QIcon Theme::trayFolderIcon(const QString &backend) const
{
Q_UNUSED(backend)
return applicationIcon();
* helper to load a icon from either the icon theme the desktop provides or from
* the apps Qt resources.
*/
-QIcon Theme::themeIcon( const QString& name, bool sysTray, bool sysTrayMenuVisible ) const
+QIcon Theme::themeIcon(const QString &name, bool sysTray, bool sysTrayMenuVisible) const
{
QString flavor;
if (sysTray) {
}
QString key = name + "," + flavor;
- QIcon & cached = _iconCache[key];
+ QIcon &cached = _iconCache[key];
if (cached.isNull()) {
- if(QIcon::hasThemeIcon(name)) {
+ if (QIcon::hasThemeIcon(name)) {
// use from theme
return cached = QIcon::fromTheme(name);
}
QList<int> sizes;
- sizes <<16 << 22 << 32 << 48 << 64 << 128 << 256;
+ sizes << 16 << 22 << 32 << 48 << 64 << 128 << 256;
foreach (int size, sizes) {
QString pixmapName = QString::fromLatin1(":/client/theme/%1/%2-%3.png").arg(flavor).arg(name).arg(size);
if (QFile::exists(pixmapName)) {
}
}
- #ifdef Q_OS_MAC
- #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
+#ifdef Q_OS_MAC
+#if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
// This defines the icon as a template and enables automatic macOS color handling
// See https://bugreports.qt.io/browse/QTBUG-42109
cached.setIsMask(_mono && sysTray && !sysTrayMenuVisible);
- #endif
- #endif
+#endif
+#endif
return cached;
}
QString Theme::hidpiFileName(const QString &fileName, QPaintDevice *dev)
{
- #if QT_VERSION > QT_VERSION_CHECK(5, 0, 0)
- qreal devicePixelRatio = dev ? dev->devicePixelRatio() :
- qApp->primaryScreen()->devicePixelRatio();
+#if QT_VERSION > QT_VERSION_CHECK(5, 0, 0)
+ qreal devicePixelRatio = dev ? dev->devicePixelRatio() : qApp->primaryScreen()->devicePixelRatio();
if (devicePixelRatio <= 1.0) {
return fileName;
}
// try to find a 2x version
-
const int dotIndex = fileName.lastIndexOf(QLatin1Char('.'));
if (dotIndex != -1) {
QString at2xfileName = fileName;
at2xfileName.insert(dotIndex, QStringLiteral("@2x"));
- if (QFile::exists(at2xfileName)) {
+ if (QFile::exists(at2xfileName)) {
return at2xfileName;
}
}
- #endif
+#endif
return fileName;
}
#endif
-Theme::Theme() :
- QObject(0)
- ,_mono(false)
+Theme::Theme()
+ : QObject(0)
+ , _mono(false)
{
-
}
// If this option returns true, the client only supports one folder to sync.
// The Add-Button is removed accordingly.
-bool Theme::singleSyncFolder() const {
+bool Theme::singleSyncFolder() const
+{
return false;
}
return appName();
}
-QString Theme::systrayIconFlavor(bool mono, bool sysTrayMenuVisible ) const
+QString Theme::systrayIconFlavor(bool mono, bool sysTrayMenuVisible) const
{
Q_UNUSED(sysTrayMenuVisible)
QString flavor;
if (mono) {
flavor = Utility::hasDarkSystray() ? QLatin1String("white") : QLatin1String("black");
- #ifdef Q_OS_MAC
+#ifdef Q_OS_MAC
if (sysTrayMenuVisible) {
flavor = QLatin1String("white");
}
- #endif
+#endif
} else {
flavor = QLatin1String("colored");
}
QString devString;
#ifdef GIT_SHA1
const QString githubPrefix(QLatin1String(
- "https://github.com/owncloud/client/commit/"));
+ "https://github.com/owncloud/client/commit/"));
const QString gitSha1(QLatin1String(GIT_SHA1));
devString = QCoreApplication::translate("ownCloudTheme::about()",
- "<p><small>Built from Git revision <a href=\"%1\">%2</a>"
- " on %3, %4 using Qt %5, %6</small></p>")
- .arg(githubPrefix+gitSha1).arg(gitSha1.left(6))
- .arg(__DATE__).arg(__TIME__)
- .arg(QString::fromAscii(qVersion()))
+ "<p><small>Built from Git revision <a href=\"%1\">%2</a>"
+ " on %3, %4 using Qt %5, %6</small></p>")
+ .arg(githubPrefix + gitSha1)
+ .arg(gitSha1.left(6))
+ .arg(__DATE__)
+ .arg(__TIME__)
+ .arg(QString::fromAscii(qVersion()))
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
- .arg(QSslSocket::sslLibraryVersionString());
+ .arg(QSslSocket::sslLibraryVersionString());
#else
- .arg(QCoreApplication::translate("ownCloudTheme::about()", "built with %1").arg(
- QString::fromAscii(OPENSSL_VERSION_TEXT)));
+ .arg(QCoreApplication::translate("ownCloudTheme::about()", "built with %1").arg(QString::fromAscii(OPENSSL_VERSION_TEXT)));
#endif
#endif
return devString;
{
QString re;
re = tr("<p>Version %1. For more information please visit <a href='%2'>%3</a>.</p>")
- .arg(MIRALL_VERSION_STRING).arg("http://" MIRALL_STRINGIFY(APPLICATION_DOMAIN))
- .arg(MIRALL_STRINGIFY(APPLICATION_DOMAIN));
+ .arg(MIRALL_VERSION_STRING)
+ .arg("http://" MIRALL_STRINGIFY(APPLICATION_DOMAIN))
+ .arg(MIRALL_STRINGIFY(APPLICATION_DOMAIN));
re += tr("<p>Copyright ownCloud GmbH</p>");
re += tr("<p>Distributed by %1 and licensed under the GNU General Public License (GPL) Version 2.0.<br/>"
"%2 and the %2 logo are registered trademarks of %1 in the "
"United States, other countries, or both.</p>")
- .arg(APPLICATION_VENDOR).arg(APPLICATION_NAME);
+ .arg(APPLICATION_VENDOR)
+ .arg(APPLICATION_NAME);
re += gitSHA1();
return re;
}
#ifndef TOKEN_AUTH_ONLY
-QVariant Theme::customMedia( CustomMediaType type )
+QVariant Theme::customMedia(CustomMediaType type)
{
QVariant re;
QString key;
- switch ( type )
- {
+ switch (type) {
case oCSetupTop:
key = QLatin1String("oCSetupTop");
break;
}
QString imgPath = QString::fromLatin1(":/client/theme/colored/%1.png").arg(key);
- if ( QFile::exists( imgPath ) ) {
- QPixmap pix( imgPath );
- if( pix.isNull() ) {
+ if (QFile::exists(imgPath)) {
+ QPixmap pix(imgPath);
+ if (pix.isNull()) {
// pixmap loading hasn't succeeded. We take the text instead.
- re.setValue( key );
+ re.setValue(key);
} else {
- re.setValue( pix );
+ re.setValue(pix);
}
}
return re;
}
-QIcon Theme::syncStateIcon( SyncResult::Status status, bool sysTray, bool sysTrayMenuVisible ) const
+QIcon Theme::syncStateIcon(SyncResult::Status status, bool sysTray, bool sysTrayMenuVisible) const
{
// FIXME: Mind the size!
QString statusIcon;
- switch( status ) {
+ switch (status) {
case SyncResult::Undefined:
// this can happen if no sync connections are configured.
statusIcon = QLatin1String("state-information");
break;
case SyncResult::Error:
case SyncResult::SetupError:
- // FIXME: Use state-problem once we have an icon.
+ // FIXME: Use state-problem once we have an icon.
default:
statusIcon = QLatin1String("state-error");
}
- return themeIcon( statusIcon, sysTray, sysTrayMenuVisible );
+ return themeIcon(statusIcon, sysTray, sysTrayMenuVisible);
}
-QIcon Theme::folderDisabledIcon( ) const
+QIcon Theme::folderDisabledIcon() const
{
- return themeIcon( QLatin1String("state-pause") );
+ return themeIcon(QLatin1String("state-pause"));
}
-QIcon Theme::folderOfflineIcon(bool sysTray, bool sysTrayMenuVisible ) const
+QIcon Theme::folderOfflineIcon(bool sysTray, bool sysTrayMenuVisible) const
{
- return themeIcon( QLatin1String("state-offline"), sysTray, sysTrayMenuVisible );
+ return themeIcon(QLatin1String("state-offline"), sysTray, sysTrayMenuVisible);
}
QColor Theme::wizardHeaderTitleColor() const
Q_OBJECT
public:
enum CustomMediaType {
- oCSetupTop, // ownCloud connect page
+ oCSetupTop, // ownCloud connect page
oCSetupSide,
oCSetupBottom,
oCSetupResultTop // ownCloud connect result page
};
/* returns a singleton instance. */
- static Theme* instance();
+ static Theme *instance();
~Theme();
/**
* the icon that is shown in the tray context menu left of the folder name
*/
- virtual QIcon trayFolderIcon( const QString& ) const;
+ virtual QIcon trayFolderIcon(const QString &) const;
/**
* get an sync state icon
*/
- virtual QIcon syncStateIcon( SyncResult::Status, bool sysTray = false, bool sysTrayMenuVisible = false) const;
+ virtual QIcon syncStateIcon(SyncResult::Status, bool sysTray = false, bool sysTrayMenuVisible = false) const;
- virtual QIcon folderDisabledIcon() const;
- virtual QIcon folderOfflineIcon(bool sysTray = false, bool sysTrayMenuVisible = false) const;
- virtual QIcon applicationIcon() const = 0;
+ virtual QIcon folderDisabledIcon() const;
+ virtual QIcon folderOfflineIcon(bool sysTray = false, bool sysTrayMenuVisible = false) const;
+ virtual QIcon applicationIcon() const = 0;
#endif
- virtual QString statusHeaderText( SyncResult::Status ) const;
+ virtual QString statusHeaderText(SyncResult::Status) const;
virtual QString version() const;
/**
* The default implementation will try to look up
* :/client/theme/<type>.png
*/
- virtual QVariant customMedia( CustomMediaType type );
+ virtual QVariant customMedia(CustomMediaType type);
/** @return color for the setup wizard */
virtual QColor wizardHeaderTitleColor() const;
* @value UserIDEmail Wizard asks for an email as ID
* @value UserIDCustom Specify string in \ref customUserID
*/
- enum UserIDType { UserIDUserName = 0, UserIDEmail, UserIDCustom };
+ enum UserIDType { UserIDUserName = 0,
+ UserIDEmail,
+ UserIDCustom };
/** @brief What to display as the userID (e.g. in the wizards)
*
protected:
#ifndef TOKEN_AUTH_ONLY
- QIcon themeIcon(const QString& name, bool sysTray = false, bool sysTrayMenuVisible = false) const;
+ QIcon themeIcon(const QString &name, bool sysTray = false, bool sysTrayMenuVisible = false) const;
#endif
Theme();
void systrayUseMonoIconsChanged(bool);
private:
- Theme(Theme const&);
- Theme& operator=(Theme const&);
+ Theme(Theme const &);
+ Theme &operator=(Theme const &);
- static Theme* _instance;
+ static Theme *_instance;
bool _mono;
#ifndef TOKEN_AUTH_ONLY
mutable QHash<QString, QIcon> _iconCache;
#endif
};
-
}
#endif // _THEME_H
Q_LOGGING_CATEGORY(lcUtility, "sync.utility", QtInfoMsg)
-bool Utility::writeRandomFile( const QString& fname, int size )
+bool Utility::writeRandomFile(const QString &fname, int size)
{
- int maxSize = 10*10*1024;
+ int maxSize = 10 * 10 * 1024;
qsrand(QDateTime::currentMSecsSinceEpoch());
- if( size == -1 ) size = qrand() % maxSize;
+ if (size == -1)
+ size = qrand() % maxSize;
QString randString;
- for( int i = 0; i < size; i++ ) {
+ for (int i = 0; i < size; i++) {
int r = qrand() % 128;
randString.append(QChar(r));
}
QFile file(fname);
- if( file.open(QIODevice::WriteOnly | QIODevice::Text) ) {
+ if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
QTextStream out(&file);
out << randString;
- // optional, as QFile destructor will already do it:
+ // optional, as QFile destructor will already do it:
file.close();
return true;
}
return false;
-
}
-QString Utility::formatFingerprint( const QByteArray& fmhash, bool colonSeparated )
+QString Utility::formatFingerprint(const QByteArray &fmhash, bool colonSeparated)
{
QByteArray hash;
- int steps = fmhash.length()/2;
+ int steps = fmhash.length() / 2;
for (int i = 0; i < steps; i++) {
- hash.append(fmhash[i*2]);
- hash.append(fmhash[i*2+1]);
+ hash.append(fmhash[i * 2]);
+ hash.append(fmhash[i * 2 + 1]);
hash.append(' ');
}
- QString fp = QString::fromLatin1( hash.trimmed() );
+ QString fp = QString::fromLatin1(hash.trimmed());
if (colonSeparated) {
fp.replace(QChar(' '), QChar(':'));
}
setupFavLink_private(folder);
}
-QString Utility::octetsToString( qint64 octets )
+QString Utility::octetsToString(qint64 octets)
{
#define THE_FACTOR 1024
static const qint64 kb = THE_FACTOR;
} else if (octets >= kb) {
s = QCoreApplication::translate("Utility", "%L1 KB");
value /= kb;
- } else {
+ } else {
s = QCoreApplication::translate("Utility", "%L1 B");
}
// this constant "ownCloud" is defined in the default OEM theming
// that is used for the standard client. If it is changed there,
// it needs to be adjusted here.
- if( appName != QLatin1String("ownCloud") ) {
+ if (appName != QLatin1String("ownCloud")) {
re += QString(" (%1)").arg(appName);
}
return re.toLatin1();
return hasLaunchOnStartup_private(appName);
}
-void Utility::setLaunchOnStartup(const QString &appName, const QString& guiName, bool enable)
+void Utility::setLaunchOnStartup(const QString &appName, const QString &guiName, bool enable)
{
setLaunchOnStartup_private(appName, guiName, enable);
}
#if defined(Q_OS_MAC) || defined(Q_OS_FREEBSD) || defined(Q_OS_FREEBSD_KERNEL) || defined(Q_OS_NETBSD) || defined(Q_OS_OPENBSD)
struct statvfs stat;
if (statvfs(path.toLocal8Bit().data(), &stat) == 0) {
- return (qint64) stat.f_bavail * stat.f_frsize;
+ return (qint64)stat.f_bavail * stat.f_frsize;
}
#elif defined(Q_OS_UNIX)
struct statvfs64 stat;
if (statvfs64(path.toLocal8Bit().data(), &stat) == 0) {
- return (qint64) stat.f_bavail * stat.f_frsize;
+ return (qint64)stat.f_bavail * stat.f_frsize;
}
#elif defined(Q_OS_WIN)
ULARGE_INTEGER freeBytes;
freeBytes.QuadPart = 0L;
- if (GetDiskFreeSpaceEx( reinterpret_cast<const wchar_t *>(path.utf16()), &freeBytes, NULL, NULL )) {
+ if (GetDiskFreeSpaceEx(reinterpret_cast<const wchar_t *>(path.utf16()), &freeBytes, NULL, NULL)) {
return freeBytes.QuadPart;
}
#endif
return -1;
}
-QString Utility::compactFormatDouble(double value, int prec, const QString& unit)
+QString Utility::compactFormatDouble(double value, int prec, const QString &unit)
{
QLocale locale = QLocale::system();
QChar decPoint = locale.decimalPoint();
}
str.chop(1);
}
- if( !unit.isEmpty() )
- str += (QLatin1Char(' ')+unit);
+ if (!unit.isEmpty())
+ str += (QLatin1Char(' ') + unit);
return str;
}
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
// In Qt 4, QThread::sleep functions are protected.
// This is a hack to make them visible in this namespace.
-struct QThread : ::QThread {
+struct QThread : ::QThread
+{
using ::QThread::sleep;
using ::QThread::usleep;
};
return isWindows() || isMac();
}
-bool Utility::fileNamesEqual( const QString& fn1, const QString& fn2)
+bool Utility::fileNamesEqual(const QString &fn1, const QString &fn2)
{
const QDir fd1(fn1);
const QDir fd2(fn2);
// Attention: If the path does not exist, canonicalPath returns ""
// ONLY use this function with existing pathes.
const QString a = fd1.canonicalPath();
- const QString b = fd2.canonicalPath();
- bool re = !a.isEmpty() && QString::compare( a, b,
- fsCasePreserving() ? Qt::CaseInsensitive : Qt::CaseSensitive) == 0;
+ const QString b = fd2.canonicalPath();
+ bool re = !a.isEmpty() && QString::compare(a, b, fsCasePreserving() ? Qt::CaseInsensitive : Qt::CaseSensitive) == 0;
return re;
}
return QDateTime::fromMSecsSinceEpoch(t * 1000);
}
-qint64 Utility::qDateTimeToTime_t(const QDateTime& t)
+qint64 Utility::qDateTimeToTime_t(const QDateTime &t)
{
return t.toMSecsSinceEpoch() / 1000;
}
QString description(quint64 value) const
{
return QCoreApplication::translate(
- "Utility", name, 0, QCoreApplication::UnicodeUTF8,
- value);
+ "Utility", name, 0, QCoreApplication::UnicodeUTF8,
+ value);
}
};
// QTBUG-3945 and issue #4855: QT_TRANSLATE_NOOP does not work with plural form because lupdate
#undef QT_TRANSLATE_NOOP
#define QT_TRANSLATE_NOOP(ctx, str, ...) str
Q_DECL_CONSTEXPR Period periods[] = {
- { QT_TRANSLATE_NOOP("Utility", "%n year(s)" , 0, _) , 365*24*3600*1000LL },
- { QT_TRANSLATE_NOOP("Utility", "%n month(s)", 0, _) , 30*24*3600*1000LL },
- { QT_TRANSLATE_NOOP("Utility", "%n day(s)", 0, _) , 24*3600*1000LL },
- { QT_TRANSLATE_NOOP("Utility", "%n hour(s)", 0, _) , 3600*1000LL },
- { QT_TRANSLATE_NOOP("Utility", "%n minute(s)", 0, _) , 60*1000LL },
- { QT_TRANSLATE_NOOP("Utility", "%n second(s)", 0, _ ), 1000LL },
+ { QT_TRANSLATE_NOOP("Utility", "%n year(s)", 0, _), 365 * 24 * 3600 * 1000LL },
+ { QT_TRANSLATE_NOOP("Utility", "%n month(s)", 0, _), 30 * 24 * 3600 * 1000LL },
+ { QT_TRANSLATE_NOOP("Utility", "%n day(s)", 0, _), 24 * 3600 * 1000LL },
+ { QT_TRANSLATE_NOOP("Utility", "%n hour(s)", 0, _), 3600 * 1000LL },
+ { QT_TRANSLATE_NOOP("Utility", "%n minute(s)", 0, _), 60 * 1000LL },
+ { QT_TRANSLATE_NOOP("Utility", "%n second(s)", 0, _), 1000LL },
{ 0, 0 }
};
} // anonymous namespace
QString Utility::durationToDescriptiveString2(quint64 msecs)
{
int p = 0;
- while (periods[p+1].name && msecs < periods[p].msec) {
+ while (periods[p + 1].name && msecs < periods[p].msec) {
p++;
}
auto firstPart = periods[p].description(int(msecs / periods[p].msec));
- if (!periods[p+1].name) {
+ if (!periods[p + 1].name) {
return firstPart;
}
- quint64 secondPartNum = qRound( double(msecs % periods[p].msec) / periods[p+1].msec);
+ quint64 secondPartNum = qRound(double(msecs % periods[p].msec) / periods[p + 1].msec);
if (secondPartNum == 0) {
return firstPart;
}
- return QCoreApplication::translate("Utility", "%1 %2").arg(firstPart,
- periods[p+1].description(secondPartNum));
+ return QCoreApplication::translate("Utility", "%1 %2").arg(firstPart, periods[p + 1].description(secondPartNum));
}
QString Utility::durationToDescriptiveString1(quint64 msecs)
{
int p = 0;
- while (periods[p+1].name && msecs < periods[p].msec) {
+ while (periods[p + 1].name && msecs < periods[p].msec) {
p++;
}
- quint64 amount = qRound( double(msecs) / periods[p].msec );
+ quint64 amount = qRound(double(msecs) / periods[p].msec);
return periods[p].description(amount);
}
-QString Utility::fileNameForGuiUse(const QString& fName)
+QString Utility::fileNameForGuiUse(const QString &fName)
{
- if( isMac() ) {
+ if (isMac()) {
QString n(fName);
return n.replace(QChar(':'), QChar('/'));
}
QString re("Windows");
#if QT_VERSION < QT_VERSION_CHECK(5, 4, 0)
- if( isMac() ) {
+ if (isMac()) {
re = QLatin1String("MacOSX");
- } else if( isLinux() ) {
+ } else if (isLinux()) {
re = QLatin1String("Linux");
- } else if( isBSD() ) {
+ } else if (isBSD()) {
re = QLatin1String("BSD");
- } else if( isUnix() ) {
+ } else if (isUnix()) {
re = QLatin1String("Unix");
}
#else
void Utility::crash()
{
- volatile int* a = (int*)(NULL);
+ volatile int *a = (int *)(NULL);
*a = 1;
}
//
// This version only delivers output on linux, as Mac and Win get their
// restarting from the installer.
-QByteArray Utility::versionOfInstalledBinary( const QString& command )
+QByteArray Utility::versionOfInstalledBinary(const QString &command)
{
QByteArray re;
- if( isLinux() ) {
+ if (isLinux()) {
QString binary(command);
- if( binary.isEmpty() ) {
+ if (binary.isEmpty()) {
binary = qApp->arguments()[0];
}
QStringList params;
process.waitForFinished(); // sets current thread to sleep and waits for pingProcess end
re = process.readAllStandardOutput();
int newline = re.indexOf(QChar('\n'));
- if( newline > 0 ) {
- re.truncate( newline );
+ if (newline > 0) {
+ re.truncate(newline);
}
}
return re;
}
-QString Utility::timeAgoInWords(const QDateTime& dt, const QDateTime& from)
+QString Utility::timeAgoInWords(const QDateTime &dt, const QDateTime &from)
{
QDateTime now = QDateTime::currentDateTimeUtc();
- if( from.isValid() ) {
+ if (from.isValid()) {
now = from;
}
- if( dt.daysTo(now)>0 ) {
+ if (dt.daysTo(now) > 0) {
int dtn = dt.daysTo(now);
return QObject::tr("%n day(s) ago", "", dtn);
} else {
qint64 secs = dt.secsTo(now);
- if( secs < 0 ) {
+ if (secs < 0) {
return QObject::tr("in the future");
}
- if( floor(secs / 3600.0) > 0 ) {
- int hours = floor(secs/3600.0);
- return( QObject::tr("%n hour(s) ago", "", hours) );
+ if (floor(secs / 3600.0) > 0) {
+ int hours = floor(secs / 3600.0);
+ return (QObject::tr("%n hour(s) ago", "", hours));
} else {
- int minutes = qRound(secs/60.0);
- if( minutes == 0 ) {
- if(secs < 5) {
+ int minutes = qRound(secs / 60.0);
+ if (minutes == 0) {
+ if (secs < 5) {
return QObject::tr("now");
} else {
return QObject::tr("Less than a minute ago");
}
}
- return( QObject::tr("%n minute(s) ago", "", minutes) );
+ return (QObject::tr("%n minute(s) ago", "", minutes));
}
}
return QObject::tr("Some time ago");
_lapTimes.clear();
}
-quint64 Utility::StopWatch::addLapTime( const QString& lapName )
+quint64 Utility::StopWatch::addLapTime(const QString &lapName)
{
- if( !_timer.isValid() ) {
+ if (!_timer.isValid()) {
start();
}
quint64 re = _timer.elapsed();
return _startTime;
}
-QDateTime Utility::StopWatch::timeOfLap( const QString& lapName ) const
+QDateTime Utility::StopWatch::timeOfLap(const QString &lapName) const
{
quint64 t = durationOfLap(lapName);
- if( t ) {
+ if (t) {
QDateTime re(_startTime);
return re.addMSecs(t);
}
return QDateTime();
}
-quint64 Utility::StopWatch::durationOfLap( const QString& lapName ) const
+quint64 Utility::StopWatch::durationOfLap(const QString &lapName) const
{
return _lapTimes.value(lapName, 0);
}
-void Utility::sortFilenames(QStringList& fileNames)
+void Utility::sortFilenames(QStringList &fileNames)
{
#if QT_VERSION >= QT_VERSION_CHECK(5, 2, 0)
QCollator collator;
}
QUrl Utility::concatUrlPath(const QUrl &url, const QString &concatPath,
- const QList< QPair<QString, QString> > &queryItems)
+ const QList<QPair<QString, QString>> &queryItems)
{
QString path = url.path();
- if (! concatPath.isEmpty()) {
+ if (!concatPath.isEmpty()) {
// avoid '//'
if (path.endsWith('/') && concatPath.startsWith('/')) {
path.chop(1);
QUrl tmpUrl = url;
tmpUrl.setPath(path);
- if( queryItems.size() > 0 ) {
+ if (queryItems.size() > 0) {
tmpUrl.setQueryItems(queryItems);
}
return tmpUrl;
Q_GLOBAL_STATIC(QString, g_configFileName)
-std::unique_ptr<QSettings> Utility::settingsWithGroup(const QString& group, QObject *parent)
+std::unique_ptr<QSettings> Utility::settingsWithGroup(const QString &group, QObject *parent)
{
if (g_configFileName()->isEmpty()) {
// cache file name
/** \addtogroup libsync
* @{
*/
-namespace Utility
-{
+namespace Utility {
OWNCLOUDSYNC_EXPORT void sleep(int sec);
OWNCLOUDSYNC_EXPORT void usleep(int usec);
- OWNCLOUDSYNC_EXPORT QString formatFingerprint( const QByteArray&, bool colonSeparated = true );
- OWNCLOUDSYNC_EXPORT void setupFavLink( const QString &folder );
- OWNCLOUDSYNC_EXPORT bool writeRandomFile( const QString& fname, int size = -1);
- OWNCLOUDSYNC_EXPORT QString octetsToString( qint64 octets );
+ OWNCLOUDSYNC_EXPORT QString formatFingerprint(const QByteArray &, bool colonSeparated = true);
+ OWNCLOUDSYNC_EXPORT void setupFavLink(const QString &folder);
+ OWNCLOUDSYNC_EXPORT bool writeRandomFile(const QString &fname, int size = -1);
+ OWNCLOUDSYNC_EXPORT QString octetsToString(qint64 octets);
OWNCLOUDSYNC_EXPORT QByteArray userAgentString();
OWNCLOUDSYNC_EXPORT bool hasLaunchOnStartup(const QString &appName);
- OWNCLOUDSYNC_EXPORT void setLaunchOnStartup(const QString &appName, const QString& guiName, bool launch);
+ OWNCLOUDSYNC_EXPORT void setLaunchOnStartup(const QString &appName, const QString &guiName, bool launch);
/**
* Return the amount of free space available.
* @param unit an optional unit that is appended if present.
* @return the formatted string.
*/
- OWNCLOUDSYNC_EXPORT QString compactFormatDouble(double value, int prec, const QString& unit = QString::null);
+ OWNCLOUDSYNC_EXPORT QString compactFormatDouble(double value, int prec, const QString &unit = QString::null);
// porting methods
- OWNCLOUDSYNC_EXPORT QString escape(const QString&);
+ OWNCLOUDSYNC_EXPORT QString escape(const QString &);
// conversion function QDateTime <-> time_t (because the ones builtin work on only unsigned 32bit)
OWNCLOUDSYNC_EXPORT QDateTime qDateTimeFromTime_t(qint64 t);
// Check if two pathes that MUST exist are equal. This function
// uses QDir::canonicalPath() to judge and cares for the systems
// case sensitivity.
- OWNCLOUDSYNC_EXPORT bool fileNamesEqual( const QString& fn1, const QString& fn2);
+ OWNCLOUDSYNC_EXPORT bool fileNamesEqual(const QString &fn1, const QString &fn2);
// Call the given command with the switch --version and rerun the first line
// of the output.
// If command is empty, the function calls the running application which, on
// Linux, might have changed while this one is running.
// For Mac and Windows, it returns QString()
- OWNCLOUDSYNC_EXPORT QByteArray versionOfInstalledBinary(const QString& command = QString() );
+ OWNCLOUDSYNC_EXPORT QByteArray versionOfInstalledBinary(const QString &command = QString());
- OWNCLOUDSYNC_EXPORT QString fileNameForGuiUse(const QString& fName);
+ OWNCLOUDSYNC_EXPORT QString fileNameForGuiUse(const QString &fName);
/**
* @brief timeAgoInWords - human readable time span
*
* If the second parameter is ommitted, the current time is used.
*/
- OWNCLOUDSYNC_EXPORT QString timeAgoInWords(const QDateTime& dt, const QDateTime& from = QDateTime() );
+ OWNCLOUDSYNC_EXPORT QString timeAgoInWords(const QDateTime &dt, const QDateTime &from = QDateTime());
- class OWNCLOUDSYNC_EXPORT StopWatch {
+ class OWNCLOUDSYNC_EXPORT StopWatch
+ {
private:
QMap<QString, quint64> _lapTimes;
QDateTime _startTime;
QElapsedTimer _timer;
+
public:
void start();
quint64 stop();
- quint64 addLapTime( const QString& lapName );
+ quint64 addLapTime(const QString &lapName);
void reset();
// out helpers, return the measured times.
QDateTime startTime() const;
- QDateTime timeOfLap( const QString& lapName ) const;
- quint64 durationOfLap( const QString& lapName ) const;
+ QDateTime timeOfLap(const QString &lapName) const;
+ quint64 durationOfLap(const QString &lapName) const;
};
/**
* @brief Sort a QStringList in a way that's appropriate for filenames
*/
- OWNCLOUDSYNC_EXPORT void sortFilenames(QStringList& fileNames);
+ OWNCLOUDSYNC_EXPORT void sortFilenames(QStringList &fileNames);
/** Appends concatPath and queryItems to the url */
OWNCLOUDSYNC_EXPORT QUrl concatUrlPath(
- const QUrl &url, const QString &concatPath,
- const QList< QPair<QString, QString> > &queryItems = (QList<QPair<QString, QString>>()));
+ const QUrl &url, const QString &concatPath,
+ const QList<QPair<QString, QString>> &queryItems = (QList<QPair<QString, QString>>()));
/** Returns a new settings pre-set in a specific group. The Settings will be created
with the given parent. If no parent is specified, the caller must destroy the settings */
- OWNCLOUDSYNC_EXPORT std::unique_ptr<QSettings> settingsWithGroup(const QString& group, QObject* parent = 0);
+ OWNCLOUDSYNC_EXPORT std::unique_ptr<QSettings> settingsWithGroup(const QString &group, QObject *parent = 0);
}
/** @} */ // \addtogroup
-
}
#endif // UTILITY_H
{
// Finder: Place under "Places"/"Favorites" on the left sidebar
CFStringRef folderCFStr = CFStringCreateWithCString(0, folder.toUtf8().data(), kCFStringEncodingUTF8);
- CFURLRef urlRef = CFURLCreateWithFileSystemPath (0, folderCFStr, kCFURLPOSIXPathStyle, true);
+ CFURLRef urlRef = CFURLCreateWithFileSystemPath(0, folderCFStr, kCFURLPOSIXPathStyle, true);
LSSharedFileListRef placesItems = LSSharedFileListCreate(0, kLSSharedFileListFavoriteItems, 0);
if (placesItems) {
//Insert an item to the list.
LSSharedFileListItemRef item = LSSharedFileListInsertItemURL(placesItems,
- kLSSharedFileListItemLast, 0, 0,
- urlRef, 0, 0);
+ kLSSharedFileListItemLast, 0, 0,
+ urlRef, 0, 0);
if (item)
CFRelease(item);
}
{
// this is quite some duplicate code with setLaunchOnStartup, at some point we should fix this FIXME.
bool returnValue = false;
- QString filePath = QDir(QCoreApplication::applicationDirPath()+QLatin1String("/../..")).absolutePath();
+ QString filePath = QDir(QCoreApplication::applicationDirPath() + QLatin1String("/../..")).absolutePath();
CFStringRef folderCFStr = CFStringCreateWithCString(0, filePath.toUtf8().data(), kCFStringEncodingUTF8);
- CFURLRef urlRef = CFURLCreateWithFileSystemPath (0, folderCFStr, kCFURLPOSIXPathStyle, true);
+ CFURLRef urlRef = CFURLCreateWithFileSystemPath(0, folderCFStr, kCFURLPOSIXPathStyle, true);
LSSharedFileListRef loginItems = LSSharedFileListCreate(0, kLSSharedFileListSessionLoginItems, 0);
if (loginItems) {
// We need to iterate over the items and check which one is "ours".
if (LSSharedFileListItemResolve(item, 0, &itemUrlRef, NULL) == noErr) {
CFStringRef itemUrlString = CFURLGetString(itemUrlRef);
- if (CFStringCompare(itemUrlString,appUrlRefString,0) == kCFCompareEqualTo) {
+ if (CFStringCompare(itemUrlString, appUrlRefString, 0) == kCFCompareEqualTo) {
returnValue = true;
}
CFRelease(itemUrlRef);
return returnValue;
}
-void setLaunchOnStartup_private(const QString &appName, const QString& guiName, bool enable)
+void setLaunchOnStartup_private(const QString &appName, const QString &guiName, bool enable)
{
Q_UNUSED(appName)
Q_UNUSED(guiName)
- QString filePath = QDir(QCoreApplication::applicationDirPath()+QLatin1String("/../..")).absolutePath();
+ QString filePath = QDir(QCoreApplication::applicationDirPath() + QLatin1String("/../..")).absolutePath();
CFStringRef folderCFStr = CFStringCreateWithCString(0, filePath.toUtf8().data(), kCFStringEncodingUTF8);
- CFURLRef urlRef = CFURLCreateWithFileSystemPath (0, folderCFStr, kCFURLPOSIXPathStyle, true);
+ CFURLRef urlRef = CFURLCreateWithFileSystemPath(0, folderCFStr, kCFURLPOSIXPathStyle, true);
LSSharedFileListRef loginItems = LSSharedFileListCreate(0, kLSSharedFileListSessionLoginItems, 0);
if (loginItems && enable) {
//Insert an item to the list.
LSSharedFileListItemRef item = LSSharedFileListInsertItemURL(loginItems,
- kLSSharedFileListItemLast, 0, 0,
- urlRef, 0, 0);
+ kLSSharedFileListItemLast, 0, 0,
+ urlRef, 0, 0);
if (item)
CFRelease(item);
CFRelease(loginItems);
- } else if (loginItems && !enable){
+ } else if (loginItems && !enable) {
// We need to iterate over the items and check which one is "ours".
UInt32 seedValue;
CFArrayRef itemsArray = LSSharedFileListCopySnapshot(loginItems, &seedValue);
if (LSSharedFileListItemResolve(item, 0, &itemUrlRef, NULL) == noErr) {
CFStringRef itemUrlString = CFURLGetString(itemUrlRef);
- if (CFStringCompare(itemUrlString,appUrlRefString,0) == kCFCompareEqualTo) {
- LSSharedFileListItemRemove(loginItems,item); // remove it!
+ if (CFStringCompare(itemUrlString, appUrlRefString, 0) == kCFCompareEqualTo) {
+ LSSharedFileListItemRemove(loginItems, item); // remove it!
}
CFRelease(itemUrlRef);
}
CFStringRef interfaceStyle = NULL;
CFStringRef darkInterfaceStyle = CFSTR("Dark");
interfaceStyle = (CFStringRef)CFPreferencesCopyAppValue(interfaceStyleKey,
- kCFPreferencesCurrentApplication);
+ kCFPreferencesCurrentApplication);
if (interfaceStyle != NULL) {
returnValue = (kCFCompareEqualTo == CFStringCompare(interfaceStyle, darkInterfaceStyle, 0));
CFRelease(interfaceStyle);
*/
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
- #include <QStandardPaths>
+#include <QStandardPaths>
#endif
namespace OCC {
-static void setupFavLink_private(const QString &folder) {
+static void setupFavLink_private(const QString &folder)
+{
// Nautilus: add to ~/.gtk-bookmarks
- QFile gtkBookmarks(QDir::homePath()+QLatin1String("/.gtk-bookmarks"));
+ QFile gtkBookmarks(QDir::homePath() + QLatin1String("/.gtk-bookmarks"));
QByteArray folderUrl = "file://" + folder.toUtf8();
if (gtkBookmarks.open(QFile::ReadWrite)) {
QByteArray places = gtkBookmarks.readAll();
QString config = QFile::decodeName(qgetenv("XDG_CONFIG_HOME"));
if (config.isEmpty()) {
- config = QDir::homePath()+QLatin1String("/.config");
+ config = QDir::homePath() + QLatin1String("/.config");
}
#endif
config += QLatin1String("/autostart/");
bool hasLaunchOnStartup_private(const QString &appName)
{
- QString desktopFileLocation = getUserAutostartDir_private()+appName+QLatin1String(".desktop");
+ QString desktopFileLocation = getUserAutostartDir_private() + appName + QLatin1String(".desktop");
return QFile::exists(desktopFileLocation);
}
-void setLaunchOnStartup_private(const QString &appName, const QString& guiName, bool enable)
+void setLaunchOnStartup_private(const QString &appName, const QString &guiName, bool enable)
{
QString userAutoStartPath = getUserAutostartDir_private();
- QString desktopFileLocation = userAutoStartPath+appName+QLatin1String(".desktop");
+ QString desktopFileLocation = userAutoStartPath + appName + QLatin1String(".desktop");
if (enable) {
if (!QDir().exists(userAutoStartPath) && !QDir().mkpath(userAutoStartPath)) {
qCWarning(lcUtility) << "Could not create autostart folder";
<< QLatin1String("Categories=") << QLatin1String("Network") << endl
<< QLatin1String("Type=") << QLatin1String("Application") << endl
<< QLatin1String("StartupNotify=") << "false" << endl
- << QLatin1String("X-GNOME-Autostart-enabled=") << "true" << endl
- ;
+ << QLatin1String("X-GNOME-Autostart-enabled=") << "true" << endl;
} else {
if (!QFile::remove(desktopFileLocation)) {
qCWarning(lcUtility) << "Could not remove autostart desktop file";
static const char runPathC[] = "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run";
namespace OCC {
-
+
static void setupFavLink_private(const QString &folder)
{
// Windows Explorer: Place under "Favorites" (Links)
-
- QString linkName;
+
+ QString linkName;
QDir folderDir(QDir::fromNativeSeparators(folder));
-
+
/* Use new WINAPI functions */
PWSTR path;
-
- if(SHGetKnownFolderPath(FOLDERID_Links, 0, NULL, &path) == S_OK) {
- QString links = QDir::fromNativeSeparators(QString::fromWCharArray(path));
+
+ if (SHGetKnownFolderPath(FOLDERID_Links, 0, NULL, &path) == S_OK) {
+ QString links = QDir::fromNativeSeparators(QString::fromWCharArray(path));
linkName = QDir(links).filePath(folderDir.dirName() + QLatin1String(".lnk"));
- CoTaskMemFree(path);
+ CoTaskMemFree(path);
}
qCDebug(lcUtility) << " creating link from " << linkName << " to " << folder;
if (!QFile::link(folder, linkName))
qCWarning(lcUtility) << "linking" << folder << "to" << linkName << "failed!";
-
}
return settings.contains(appName);
}
-void setLaunchOnStartup_private(const QString &appName, const QString& guiName, bool enable)
+void setLaunchOnStartup_private(const QString &appName, const QString &guiName, bool enable)
{
Q_UNUSED(guiName);
QString runPath = QLatin1String(runPathC);
QSettings settings(runPath, QSettings::NativeFormat);
if (enable) {
- settings.setValue(appName, QCoreApplication::applicationFilePath().replace('/','\\'));
+ settings.setValue(appName, QCoreApplication::applicationFilePath().replace('/', '\\'));
} else {
settings.remove(appName);
}