コード例 #1
0
ファイル: networkjobs.cpp プロジェクト: owncloud/client
void DetermineAuthTypeJob::start()
{
    qCInfo(lcDetermineAuthTypeJob) << "Determining auth type for" << _account->davUrl();

    QNetworkRequest req;
    // Prevent HttpCredentialsAccessManager from setting an Authorization header.
    req.setAttribute(HttpCredentials::DontAddCredentialsAttribute, true);
    // Don't reuse previous auth credentials
    req.setAttribute(QNetworkRequest::AuthenticationReuseAttribute, QNetworkRequest::Manual);
    // Don't send cookies, we can't determine the auth type if we're logged in
    req.setAttribute(QNetworkRequest::CookieLoadControlAttribute, QNetworkRequest::Manual);

    auto propfind = _account->sendRequest("PROPFIND", _account->davUrl(), req);
    propfind->setTimeout(30 * 1000);
    propfind->setIgnoreCredentialFailure(true);
    connect(propfind, &SimpleNetworkJob::finishedSignal, this, [this](QNetworkReply *reply) {
        auto authChallenge = reply->rawHeader("WWW-Authenticate").toLower();
        auto result = Basic;
        if (authChallenge.contains("bearer ")) {
            result = OAuth;
        } else if (authChallenge.isEmpty()) {
            qCWarning(lcDetermineAuthTypeJob) << "Did not receive WWW-Authenticate reply to auth-test PROPFIND";
        }
        qCInfo(lcDetermineAuthTypeJob) << "Auth type for" << _account->davUrl() << "is" << result;
        emit this->authType(result);
        this->deleteLater();
    });
}
コード例 #2
0
ファイル: extscript.cpp プロジェクト: wlemuel/awesome-widgets
void ExtScript::readJsonFilters()
{
    QString fileName = QStandardPaths::locate(
        QStandardPaths::GenericDataLocation,
        QString(
            "awesomewidgets/scripts/awesomewidgets-extscripts-filters.json"));
    qCInfo(LOG_LIB) << "Filters file" << fileName;
    QFile jsonFile(fileName);
    if (!jsonFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qCWarning(LOG_LIB) << "Could not open" << fileName;
        return;
    }
    QString jsonText = jsonFile.readAll();
    jsonFile.close();

    QJsonParseError error;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonText.toUtf8(), &error);
    if (error.error != QJsonParseError::NoError) {
        qCWarning(LOG_LIB) << "Parse error" << error.errorString();
        return;
    }
    jsonFilters = jsonDoc.toVariant().toMap();

    qCInfo(LOG_LIB) << "Filters" << jsonFilters;
}
コード例 #3
0
/**
 * @fn editOptionPrivate
 */
QueuedResult<bool> QueuedCorePrivateHelper::editOptionPrivate(const QString &_key,
                                                              const QVariant &_value)
{
    qCDebug(LOG_LIB) << "Set key" << _key << "to" << _value;

    // add to database
    long long id = advancedSettings()->id(_key);
    QVariantHash payload = {{"key", _key}, {"value", _value}};

    bool status;
    if (id == -1) {
        id = database()->add(QueuedDB::SETTINGS_TABLE, payload);
        qCInfo(LOG_LIB) << "Added new key with ID" << id;
        status = (id != -1);
    } else {
        status = database()->modify(QueuedDB::SETTINGS_TABLE, id, payload);
        qCInfo(LOG_LIB) << "Value for" << _key << "has been modified with status" << status;
    }

    // add to child object
    if (status) {
        advancedSettings()->set(_key, _value);
        // notify plugins if required
        if (plugins()) {
            auto tryPluginOption = plugins()->convertOptionName(_key);
            if ((!tryPluginOption.first.isEmpty()) && (!tryPluginOption.second.isEmpty()))
                plugins()->optionChanged(_key, _value);
            // notify plugins
            emit(plugins()->interface()->onEditOption(_key, _value));
        }
    }

    return status;
}
コード例 #4
0
ファイル: extscript.cpp プロジェクト: wlemuel/awesome-widgets
void ExtScript::updateValue()
{
    qCInfo(LOG_LIB) << "Cmd returns" << process->exitCode();
    QString qdebug = QTextCodec::codecForMib(106)
                         ->toUnicode(process->readAllStandardError())
                         .trimmed();
    qCInfo(LOG_LIB) << "Error" << qdebug;
    QString qoutput = QTextCodec::codecForMib(106)
                          ->toUnicode(process->readAllStandardOutput())
                          .trimmed();
    qCInfo(LOG_LIB) << "Output" << qoutput;
    QString strValue;

    switch (m_redirect) {
    case stdout2stderr:
        break;
    case stderr2stdout:
        strValue = QString("%1\n%2").arg(qdebug).arg(qoutput);
        break;
    case swap:
        strValue = qdebug;
        break;
    case nothing:
    default:
        strValue = qoutput;
        break;
    }

    // filters
    value[tag(QString("custom"))] = applyFilters(strValue);
}
コード例 #5
0
bool DataExporter::exportDay(const QVector<TimeLogEntry> &data)
{
    if (data.isEmpty()) {
        qCInfo(DATA_IO_CATEGORY) << QString("No data for date %1").arg(m_currentDate.toString());
        return true;
    }

    qCInfo(DATA_IO_CATEGORY) << QString("Exporting data for date %1").arg(m_currentDate.toString());

    QString fileName = QString("%1 (%2).csv").arg(m_currentDate.toString(Qt::ISODate))
                                             .arg(m_currentDate.toString("ddd"));
    QString filePath = m_dir.filePath(fileName);
    QFile file(filePath);
    if (file.exists()) {
        fail(QString("File %1 already exists").arg(filePath));
        return false;
    }

    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        fail(formatFileError("Fail to open file", file));
        return false;
    }

    QStringList strings;
    foreach (const TimeLogEntry &entry, data) {
        QStringList values;
        values << entry.startTime.toUTC().toString(Qt::ISODate);
        values << entry.category;
        values << entry.comment;
        values << entry.uuid.toString();
        strings.append(values.join(m_sep));
    }
コード例 #6
0
bool AWKeyCache::addKeyToCache(const QString type, const QString key)
{
    qCDebug(LOG_AW) << "Key" << key << "with type" << type;

    QString fileName = QString("%1/awesomewidgets.ndx")
                           .arg(QStandardPaths::writableLocation(
                               QStandardPaths::GenericCacheLocation));
    qCInfo(LOG_AW) << "Cache file" << fileName;
    QSettings cache(fileName, QSettings::IniFormat);

    cache.beginGroup(type);
    QStringList cachedValues;
    for (auto key : cache.allKeys())
        cachedValues.append(cache.value(key).toString());

    if (type == QString("hdd")) {
        QStringList allDevices
            = QDir(QString("/dev")).entryList(QDir::System, QDir::Name);
        QStringList devices
            = allDevices.filter(QRegExp(QString("^[hms]d[a-z]$")));
        for (auto dev : devices) {
            QString device = QString("/dev/%1").arg(dev);
            if (cachedValues.contains(device))
                continue;
            qCInfo(LOG_AW) << "Found new key" << device << "for type" << type;
            cache.setValue(
                QString("%1").arg(cache.allKeys().count(), 3, 10, QChar('0')),
                device);
        }
    } else if (type == QString("net")) {
        QList<QNetworkInterface> rawInterfaceList
            = QNetworkInterface::allInterfaces();
        for (auto interface : rawInterfaceList) {
            QString device = interface.name();
            if (cachedValues.contains(device))
                continue;
            qCInfo(LOG_AW) << "Found new key" << device << "for type" << type;
            cache.setValue(
                QString("%1").arg(cache.allKeys().count(), 3, 10, QChar('0')),
                device);
        }
    } else {
        if (cachedValues.contains(key))
            return false;
        qCInfo(LOG_AW) << "Found new key" << key << "for type" << type;
        cache.setValue(
            QString("%1").arg(cache.allKeys().count(), 3, 10, QChar('0')), key);
    }
    cache.endGroup();

    cache.sync();
    return true;
}
コード例 #7
0
ファイル: configfile.cpp プロジェクト: owncloud/client
void ConfigFile::setupDefaultExcludeFilePaths(ExcludedFiles &excludedFiles)
{
    ConfigFile cfg;
    QString systemList = cfg.excludeFile(ConfigFile::SystemScope);
    qCInfo(lcConfigFile) << "Adding system ignore list to csync:" << systemList;
    excludedFiles.addExcludeFilePath(systemList);

    QString userList = cfg.excludeFile(ConfigFile::UserScope);
    if (QFile::exists(userList)) {
        qCInfo(lcConfigFile) << "Adding user defined ignore list to csync:" << userList;
        excludedFiles.addExcludeFilePath(userList);
    }
}
コード例 #8
0
ファイル: InboundAudioStream.cpp プロジェクト: huffman/hifi
int InboundAudioStream::writeDroppableSilentFrames(int silentFrames) {

    // We can't guarentee that all clients have faded the stream down
    // to silence and encoded that silence before sending us a 
    // SilentAudioFrame. If the encoder has truncated the stream it will
    // leave the decoder holding some unknown loud state. To handle this 
    // case we will call the decoder's lostFrame() method, which indicates
    // that it should interpolate from its last known state down toward 
    // silence.
    if (_decoder) {
        // FIXME - We could potentially use the output from the codec, in which 
        // case we might get a cleaner fade toward silence. NOTE: The below logic 
        // attempts to catch up in the event that the jitter buffers have grown. 
        // The better long term fix is to use the output from the decode, detect
        // when it actually reaches silence, and then delete the silent portions
        // of the jitter buffers. Or petentially do a cross fade from the decode
        // output to silence.
        QByteArray decodedBuffer;
        _decoder->lostFrame(decodedBuffer);
    }

    // calculate how many silent frames we should drop.
    int silentSamples = silentFrames * _numChannels;
    int samplesPerFrame = _ringBuffer.getNumFrameSamples();
    int desiredJitterBufferFramesPlusPadding = _desiredJitterBufferFrames + DESIRED_JITTER_BUFFER_FRAMES_PADDING;
    int numSilentFramesToDrop = 0;

    if (silentSamples >= samplesPerFrame && _currentJitterBufferFrames > desiredJitterBufferFramesPlusPadding) {

        // our avg jitter buffer size exceeds its desired value, so ignore some silent
        // frames to get that size as close to desired as possible
        int numSilentFramesToDropDesired = _currentJitterBufferFrames - desiredJitterBufferFramesPlusPadding;
        int numSilentFramesReceived = silentSamples / samplesPerFrame;
        numSilentFramesToDrop = std::min(numSilentFramesToDropDesired, numSilentFramesReceived);

        // dont reset _currentJitterBufferFrames here; we want to be able to drop further silent frames
        // without waiting for _framesAvailableStat to fill up to 10s of samples.
        _currentJitterBufferFrames -= numSilentFramesToDrop;
        _silentFramesDropped += numSilentFramesToDrop;

        qCInfo(audiostream, "Dropped %d silent frames", numSilentFramesToDrop);
        qCInfo(audiostream, "Set current jitter frames to %d (dropped)", _currentJitterBufferFrames);

        _framesAvailableStat.reset();
    }

    int ret = _ringBuffer.addSilentSamples(silentSamples - numSilentFramesToDrop * samplesPerFrame);
    
    return ret;
}
コード例 #9
0
ファイル: InboundAudioStream.cpp プロジェクト: huffman/hifi
void InboundAudioStream::setToStarved() {
    if (!_isStarved) {
        qCInfo(audiostream, "Starved");
    }

    _consecutiveNotMixedCount = 0;
    _starveCount++;
    // if we have more than the desired frames when setToStarved() is called, then we'll immediately
    // be considered refilled. in that case, there's no need to set _isStarved to true.
    _isStarved = (_ringBuffer.framesAvailable() < _desiredJitterBufferFrames);

    // record the time of this starve in the starve history
    quint64 now = usecTimestampNow();
    _starveHistory.insert(now);

    if (_dynamicJitterBufferEnabled) {
        // dynamic jitter buffers are enabled. check if this starve put us over the window
        // starve threshold
        quint64 windowEnd = now - WINDOW_SECONDS_FOR_DESIRED_CALC_ON_TOO_MANY_STARVES * USECS_PER_SECOND;
        RingBufferHistory<quint64>::Iterator starvesIterator = _starveHistory.begin();
        RingBufferHistory<quint64>::Iterator end = _starveHistory.end();
        int starvesInWindow = 1;
        do {
            ++starvesIterator;
            if (*starvesIterator < windowEnd) {
                break;
            }
            starvesInWindow++;
        } while (starvesIterator != end);

        // this starve put us over the starve threshold. update _desiredJitterBufferFrames to
        // value determined by window A.
        if (starvesInWindow >= WINDOW_STARVE_THRESHOLD) {
            int calculatedJitterBufferFrames;
            // we don't know when the next packet will arrive, so it's possible the gap between the last packet and the
            // next packet will exceed the max time gap in the window.  If the time since the last packet has already exceeded
            // the window max gap, then we should use that value to calculate desired frames.
            int framesSinceLastPacket = ceilf((float)(now - _lastPacketReceivedTime)
                                              / (float)AudioConstants::NETWORK_FRAME_USECS);
            calculatedJitterBufferFrames = std::max(_calculatedJitterBufferFrames, framesSinceLastPacket);
            // make sure _desiredJitterBufferFrames does not become lower here
            if (calculatedJitterBufferFrames >= _desiredJitterBufferFrames) {
                _desiredJitterBufferFrames = calculatedJitterBufferFrames;
                qCInfo(audiostream, "Set desired jitter frames to %d (starved)", _desiredJitterBufferFrames);
            }
        }
    }
}
コード例 #10
0
void LibInputHandlerPrivate::logHandler(libinput *handle, libinput_log_priority priority,
                                        const char *format, va_list args)
{
    Q_UNUSED(handle);

    char buffer[512];
    int n = vsnprintf(buffer, sizeof(buffer), format, args);
    if (n > 0) {
        // Remove newline
        if (buffer[n - 1] == '\n')
            buffer[n - 1] = '\0';

        // Log the message prefixing "libinput" so that messages from the
        // library can be dinstinguished from ours
        switch (priority) {
        case LIBINPUT_LOG_PRIORITY_DEBUG:
            qCDebug(lcInput, "%s", buffer);
            break;
        case LIBINPUT_LOG_PRIORITY_ERROR:
            qCWarning(lcInput, "%s", buffer);
            break;
        case LIBINPUT_LOG_PRIORITY_INFO:
            qCInfo(lcInput, "%s", buffer);
            break;
        default:
            break;
        }
    }
}
コード例 #11
0
bool AbstractExtItem::tryDelete() const
{
    bool status = QFile::remove(m_fileName);
    qCInfo(LOG_LIB) << "Remove file" << m_fileName << status;

    return status;
}
コード例 #12
0
/**
 * @fn editUserPermissionPrivate
 */
QueuedResult<bool> QueuedCorePrivateHelper::editUserPermissionPrivate(
    const long long _id, const QueuedEnums::Permission &_permission, const bool _add)
{
    qCDebug(LOG_LIB) << "Edit permissions" << static_cast<int>(_permission) << "for user" << _id
                     << "add" << _add;

    auto userObj = users()->user(_id);
    if (!userObj) {
        qCWarning(LOG_LIB) << "Could not find user with ID" << _id;
        return QueuedError("User does not exist", QueuedEnums::ReturnStatus::InvalidArgument);
    }

    // edit runtime permissions to get value
    auto perms
        = _add ? userObj->addPermission(_permission) : userObj->removePermission(_permission);
    auto permissions = static_cast<uint>(perms);
    qCInfo(LOG_LIB) << "New user permissions" << perms;

    // modify in database now
    QVariantHash payload = {{"permissions", permissions}};
    bool status = database()->modify(QueuedDB::USERS_TABLE, _id, payload);
    if (!status) {
        qCWarning(LOG_LIB) << "Could not modify user record" << _id
                           << "in database, do not edit it in memory";
        // rollback in-memory values
        if (_add)
            userObj->removePermission(_permission);
        else
            userObj->addPermission(_permission);
        return QueuedError("", QueuedEnums::ReturnStatus::Error);
    }

    return true;
}
コード例 #13
0
ファイル: DateTime.cpp プロジェクト: arcan1s/quadro-plugins
void DateTime::action() const
{
    DateTimeCalendar *calendar = new DateTimeCalendar(nullptr);
    int ret = calendar->exec();
    qCInfo(LOG_PL) << "Calendar exited with code" << ret;
    delete calendar;
}
コード例 #14
0
ファイル: Konfiguration.cpp プロジェクト: QAlarm/Lib
void Konfiguration::Laden()
{
	QString Datei;
	if (K_Konfig)
		return;
	if (!K_Klientconfig)
	{
		Datei=K_Datei;
		if (!QFile::exists(K_Datei))
		{
			Q_EMIT DateiNichtGefunden();
			return;
		}
		K_Konfig=new QSettings(K_Datei,QSettings::IniFormat,this);
	}
	else
	{
		K_Konfig=new QSettings(QSettings::IniFormat,QSettings::UserScope,qApp->organizationName(),
							   qApp->applicationName(),this);
		Datei=K_Konfig->fileName();
	}
	qCInfo(qalarm_Konfiguration)<<tr("Lade Datei %1").arg(Datei);
	K_Konfig->setIniCodec("UTF-8");
	Q_EMIT Geladen();
}
コード例 #15
0
ファイル: networkjobs.cpp プロジェクト: owncloud/client
bool RequestEtagJob::finished()
{
    qCInfo(lcEtagJob) << "Request Etag of" << reply()->request().url() << "FINISHED WITH STATUS"
                      <<  replyStatusString();

    auto httpCode = reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
    if (httpCode == 207) {
        // Parse DAV response
        QXmlStreamReader reader(reply());
        reader.addExtraNamespaceDeclaration(QXmlStreamNamespaceDeclaration("d", "DAV:"));
        QString etag;
        while (!reader.atEnd()) {
            QXmlStreamReader::TokenType type = reader.readNext();
            if (type == QXmlStreamReader::StartElement && reader.namespaceUri() == QLatin1String("DAV:")) {
                QString name = reader.name().toString();
                if (name == QLatin1String("getetag")) {
                    etag += reader.readElementText();
                }
            }
        }
        emit etagRetreived(etag);
        emit finishedWithResult(etag);
    } else {
        emit finishedWithResult(HttpError{ httpCode, errorString() });
    }
    return true;
}
コード例 #16
0
ファイル: QueuedServer.cpp プロジェクト: arcan1s/queued
void QueuedServer::init()
{
    while (QueuedCoreAdaptor::getStatus().type() != Result::Content::Value) {
        qCWarning(LOG_SERV) << "Daemon seems to be unavailable wait" << WAIT_FOR_DAEMON;

        QTime timer = QTime::currentTime().addMSecs(WAIT_FOR_DAEMON);
        while (QTime::currentTime() < timer)
            QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
    }

    m_server->init(QueuedCoreAdaptor::getOption(QueuedConfig::QueuedSettings::ServerTimeout, "")
                       .get()
                       .toInt());
    QString address = QueuedCoreAdaptor::getOption(QueuedConfig::QueuedSettings::ServerAddress, "")
                          .get()
                          .toString();
    ushort port
        = QueuedCoreAdaptor::getOption(QueuedConfig::QueuedSettings::ServerPort, "").get().toUInt();
    m_server->listen(QHostAddress(address), port);
    m_server->setMaxPendingConnections(
        QueuedCoreAdaptor::getOption(QueuedConfig::QueuedSettings::ServerMaxConnections, "")
            .get()
            .toInt());

    qCInfo(LOG_SERV) << "Server listen on" << m_server->serverAddress() << m_server->serverPort();
}
コード例 #17
0
ファイル: ocupdater.cpp プロジェクト: msphn/client
void NSISUpdater::versionInfoArrived(const UpdateInfo &info)
{
    ConfigFile cfg;
    QSettings settings(cfg.configFile(), QSettings::IniFormat);
    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) {
        qCInfo(lcUpdater) << "Client is on latest version!";
        setDownloadState(UpToDate);
    } else {
        QString url = info.downloadUrl();
        qint64 autoUpdateFailedVersion =
            Helper::stringVersionToInt(settings.value(autoUpdateFailedVersionC).toString());
        if (url.isEmpty() || _showFallbackMessage || infoVersion == autoUpdateFailedVersion) {
            showDialog(info);
        }
        if (!url.isEmpty()) {
            _targetFile = cfg.configPath() + url.mid(url.lastIndexOf('/'));
            if (QFile(_targetFile).exists()) {
                setDownloadState(DownloadComplete);
            } else {
                QNetworkReply *reply = qnam()->get(QNetworkRequest(QUrl(url)));
                connect(reply, &QIODevice::readyRead, this, &NSISUpdater::slotWriteFile);
                connect(reply, &QNetworkReply::finished, this, &NSISUpdater::slotDownloadFinished);
                setDownloadState(Downloading);
                _file.reset(new QTemporaryFile);
                _file->setAutoRemove(true);
                _file->open();
            }
        }
    }
}
コード例 #18
0
ファイル: Wallet.cpp プロジェクト: howard-stearns/hifi
// for now a copy of how we sign in libraries/networking/src/DataServerAccountInfo -
// we sha256 the text, read the private key from disk (for now!), and return the signed
// sha256.  Note later with multiple keys, we may need the key parameter (or something
// similar) so I left it alone for now.  Also this will probably change when we move
// away from RSA keys anyways.  Note that since this returns a QString, we better avoid
// the horror of code pages and so on (changing the bytes) by just returning a base64
// encoded string representing the signature (suitable for http, etc...)
QString Wallet::signWithKey(const QByteArray& text, const QString& key) {
    EC_KEY* ecPrivateKey = NULL;

    auto keyFilePathString = keyFilePath().toStdString();
    if ((ecPrivateKey = readPrivateKey(keyFilePath().toStdString().c_str()))) {
        unsigned char* sig = new unsigned char[ECDSA_size(ecPrivateKey)];

        unsigned int signatureBytes = 0;

        qCInfo(commerce) << "Hashing and signing plaintext" << text << "with key at address" << ecPrivateKey;

        QByteArray hashedPlaintext = QCryptographicHash::hash(text, QCryptographicHash::Sha256);


        int retrn = ECDSA_sign(0,
            reinterpret_cast<const unsigned char*>(hashedPlaintext.constData()),
            hashedPlaintext.size(),
            sig,
            &signatureBytes, ecPrivateKey);

        EC_KEY_free(ecPrivateKey);
        QByteArray signature(reinterpret_cast<const char*>(sig), signatureBytes);
        if (retrn != -1) {
            return signature.toBase64();
        }
    }
    return QString();
}
コード例 #19
0
ファイル: Wallet.cpp プロジェクト: Atlante45/hifi
bool Wallet::generateKeyPair() {
    // FIXME: initialize OpenSSL elsewhere soon
    initialize();

    qCInfo(commerce) << "Generating keypair.";
    auto keyPair = generateECKeypair();
    if (!keyPair.first) {
        qCWarning(commerce) << "Empty keypair";
        return false;
    }

    writeBackupInstructions();

    // TODO: redo this soon -- need error checking and so on
    writeSecurityImage(_securityImage, keyFilePath());
    QString key = keyPair.first->toBase64();
    _publicKeys.push_back(key);
    qCDebug(commerce) << "public key:" << key;
    _isOverridingServer = false;

    // It's arguable whether we want to change the receiveAt every time, but:
    // 1. It's certainly needed the first time, when createIfNeeded answers true.
    // 2. It is maximally private, and we can step back from that later if desired.
    // 3. It maximally exercises all the machinery, so we are most likely to surface issues now.
    auto ledger = DependencyManager::get<Ledger>();
    return ledger->receiveAt(key, key, getWallet());
}
コード例 #20
0
ファイル: networkjobs.cpp プロジェクト: uniblockchain/client
// TODO: Instead of doing all in this slot, we should iteratively parse in readyRead(). This
// would allow us to be more asynchronous in processing while data is coming from the network,
// not all in one big blob at the end.
bool LsColJob::finished()
{
    qCInfo(lcLsColJob) << "LSCOL of" << reply()->request().url() << "FINISHED WITH STATUS"
                       << 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, &LsColXMLParser::directoryListingSubfolders,
            this, &LsColJob::directoryListingSubfolders);
        connect(&parser, &LsColXMLParser::directoryListingIterated,
            this, &LsColJob::directoryListingIterated);
        connect(&parser, &LsColXMLParser::finishedWithError,
            this, &LsColJob::finishedWithError);
        connect(&parser, &LsColXMLParser::finishedWithoutError,
            this, &LsColJob::finishedWithoutError);

        QString expectedPath = reply()->request().url().path(); // something like "/owncloud/remote.php/webdav/folder"
        if (!parser.parse(reply()->readAll(), &_sizes, expectedPath)) {
            // XML parse error
            emit finishedWithError(reply());
        }
    } else if (httpCode == 207) {
        // wrong content type
        emit finishedWithError(reply());
    } else {
        // wrong HTTP code or any other network error
        emit finishedWithError(reply());
    }

    return true;
}
コード例 #21
0
QString YahooWeatherHelper::url() const
{
    QString apiUrl
        = QString("%1").arg(YAHOO_FORECAST_URL).arg(m_city).arg(m_country);

    qCInfo(LOG_PL) << "Using url" << apiUrl;
    return apiUrl;
}
コード例 #22
0
ファイル: WebsocketServer.cpp プロジェクト: QAlarm/Server
void WebsocketServer::NeuerKlient()
{
	QWebSocket *Klient=K_Server->nextPendingConnection();
	qCInfo(qalarm_serverWebsocketServer)<<tr("Neuer Klient: IP: %1 Anschluss: %2").arg(Klient->peerAddress().toString())
																				  .arg(Klient->peerPort());
	qCDebug(qalarm_serverWebsocketServer)<<tr("Klient fordert an: %1").arg(Klient->requestUrl().toString());
	Klient->deleteLater();
}
コード例 #23
0
ファイル: WebsocketServer.cpp プロジェクト: QAlarm/Server
void WebsocketServer::starten()
{
	if (!K_Server->listen(K_IPAdresse,K_Anschluss))
		Q_EMIT Fehler(tr("Konnte den Server nicht starten. %1").arg(K_Server->errorString()));
	else
		qCInfo(qalarm_serverWebsocketServer)<<tr("Der Server lauscht auf der Adresse %1 und dem Anschluss %2").arg(K_Server->serverAddress().toString())
																											  .arg(K_Server->serverPort());
}
コード例 #24
0
ファイル: networkjobs.cpp プロジェクト: owncloud/client
bool MkColJob::finished()
{
    qCInfo(lcMkColJob) << "MKCOL of" << reply()->request().url() << "FINISHED WITH STATUS"
                       << replyStatusString();

    emit finished(reply()->error());
    return true;
}
コード例 #25
0
bool MoveJob::finished()
{
    qCInfo(lcMoveJob) << "MOVE of" << reply()->request().url() << "FINISHED WITH STATUS"
                      << replyStatusString();

    emit finishedSignal();
    return true;
}
コード例 #26
0
void PropagateUploadFileNG::slotPropfindFinished()
{
    auto job = qobject_cast<LsColJob *>(sender());
    slotJobDestroyed(job); // remove it from the _jobs list
    propagator()->_activeJobList.removeOne(this);

    _currentChunk = 0;
    _sent = 0;
    while (_serverChunks.contains(_currentChunk)) {
        _sent += _serverChunks[_currentChunk].size;
        _serverChunks.remove(_currentChunk);
        ++_currentChunk;
    }

    if (_sent > _item->_size) {
        // Normally this can't happen because the size is xor'ed with the transfer id, and it is
        // therefore impossible that there is more data on the server than on the file.
        qCCritical(lcPropagateUpload) << "Inconsistency while resuming " << _item->_file
                                      << ": 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;

    if (!_serverChunks.isEmpty()) {
        qCInfo(lcPropagateUpload) << "To Delete" << _serverChunks.keys();
        propagator()->_activeJobList.append(this);
        _removeJobError = false;

        // Make sure that if there is a "hole" and then a few more chunks, on the server
        // we should remove the later chunks. Otherwise when we do dynamic chunk sizing, we may end up
        // with corruptions if there are too many chunks, or if we abort and there are still stale chunks.
        for (auto it = _serverChunks.begin(); it != _serverChunks.end(); ++it) {
            auto job = new DeleteJob(propagator()->account(), Utility::concatUrlPath(chunkUrl(), it->originalName), this);
            QObject::connect(job, &DeleteJob::finishedSignal, this, &PropagateUploadFileNG::slotDeleteJobFinished);
            _jobs.append(job);
            job->start();
        }
        _serverChunks.clear();
        return;
    }

    startNextChunk();
}
コード例 #27
0
bool ChangeLog::checkChanges(const QString &previousVersion, const QString &currentVersion)
{
    QVersionNumber previous = QVersionNumber::fromString(previousVersion);
    QVersionNumber current = QVersionNumber::fromString(currentVersion);
    if (current <= previous) {
        qCInfo(CHANGELOG_CATEGORY) << "Current version isn't newer, than previous"
                                   << previousVersion << currentVersion;
        return false;
    }

    QFileSelector fileSelector;
    fileSelector.setExtraSelectors(QStringList() << QLocale::system().uiLanguages().constFirst().split('-').constFirst());
    const QString path = fileSelector.select(":/changelogs/changelog.json");

    QFile file(path);
    if (!file.open(QIODevice::ReadOnly)) {
        qCCritical(CHANGELOG_CATEGORY) << "Fail to open changelog file" << path << file.errorString();
        return false;
    }
    QByteArray data = file.readAll();

    QJsonParseError parseError;
    QJsonDocument document = QJsonDocument::fromJson(data, &parseError);
    if (parseError.error != QJsonParseError::NoError) {
        qCritical(CHANGELOG_CATEGORY) << "Fail to parse changelog data JSON:"
                                      << data << "error at offset"
                                      << parseError.offset
                                      << parseError.errorString() << parseError.error;
        return false;
    }
    QVariantList content = document.array().toVariantList();

    while (!content.isEmpty()) {
        if (QVersionNumber::fromString(content.constFirst().toMap().value("version").toString()) > current) {
            content.takeFirst();
        } else {
            break;
        }
    }
    QVariantList result;
    while (!content.isEmpty()) {
        if (QVersionNumber::fromString(content.constFirst().toMap().value("version").toString()) > previous) {
            result.append(content.takeFirst());
        } else {
            break;
        }
    }

    if (result.isEmpty()) {
        qCWarning(CHANGELOG_CATEGORY) << "Empty changelog" << previousVersion << currentVersion;
        return false;
    }

    emit changesAvailable(result);

    return true;
}
コード例 #28
0
ファイル: networkjobs.cpp プロジェクト: uniblockchain/client
bool MkColJob::finished()
{
    qCInfo(lcMkColJob) << "MKCOL of" << reply()->request().url() << "FINISHED WITH STATUS"
                       << reply()->error()
                       << (reply()->error() == QNetworkReply::NoError ? QLatin1String("") : errorString());

    emit finished(reply()->error());
    return true;
}
コード例 #29
0
ファイル: obUSBStrategy.cpp プロジェクト: CMon/dld
/**
 * @brief parse the data that comes from the OB nodes
 * @param data	the data that is coming from the OB
 * @return
 * 	void
 */
void OpenBeaconUSBStrategy::parseNewData (const QString & data)
{
	if (data.isEmpty ())
		return ;
	QString receivedPath = reinterpret_cast<OpenBeaconCommunication(*)> (sender ())->getDevicePath ();
	QStringList answerParts = data.split(" ", QString::SkipEmptyParts);
	if (answerParts.at(0) == "Id:")
	{
		setPath (answerParts.at(1).toInt(), receivedPath);
		DeviceInformation deviceInfo = getDeviceInformation (receivedPath);
		qCInfo(OPENBEACON_STRATEGY) << QString ("device with Id: %1 added.").arg (deviceInfo.id);
		emit newNode (deviceInfo.id, deviceInfo.x(), deviceInfo.y(), deviceInfo.z());
		return;
	}
	if (answerParts.at (0) == "FIFO" && answerParts.at (1) == "lifetime")
	{
		qCInfo(OPENBEACON_STRATEGY) << QString ("FIFO of >%1< set to %2").arg (receivedPath).arg (answerParts.at (4));
		return;
	}
	if (answerParts.at(0) == "RX:")
	{
		// if no tag is in reach
		if (answerParts.size () < 2 || answerParts.at(1).isEmpty())
			return ;

		DeviceInformation deviceInfo = getDeviceInformation (receivedPath);
		if (!deviceInfo.isValid())
		{
			qCInfo(OPENBEACON_STRATEGY) << QString ("Received information(%1) from unconfigured device: %2").arg(data).arg(receivedPath);
			return ;
		}

		//RX: 0,2213,3
		// first is the powerlevel (0, 85, 170, 255)
		// second is the tagId
		// third is the count of received packets
		// strength = (powerlevel/85)*10 + (MAXPACKETS - packets)
		// gives us a scale from 0->40
		QStringList tagInfo = answerParts.at(1).split(",", QString::SkipEmptyParts);
		int strength = ((tagInfo.at(0).toInt() / 85) * 10) + (maxPackages - tagInfo.at(2).toInt());
		emit newStrength (deviceInfo.id, tagInfo.at(1), strength);
		return;
	}
}
コード例 #30
0
ファイル: networkjobs.cpp プロジェクト: uniblockchain/client
bool CheckServerJob::finished()
{
    if (reply()->request().url().scheme() == QLatin1String("https")
        && reply()->sslConfiguration().sessionTicket().isEmpty()
        && reply()->error() == QNetworkReply::NoError) {
        qCWarning(lcCheckServerJob) << "No SSL session identifier / session ticket is used, this might impact sync performance negatively.";
    }

    mergeSslConfigurationForSslButton(reply()->sslConfiguration(), account());

    // The server installs to /owncloud. Let's try that if the file wasn't found
    // at the original location
    if ((reply()->error() == QNetworkReply::ContentNotFoundError) && (!_subdirFallback)) {
        _subdirFallback = true;
        setPath(QLatin1String(nextcloudDirC) + QLatin1String(statusphpC));
        start();
        qCInfo(lcCheckServerJob) << "Retrying with" << reply()->url();
        return false;
    }

    QByteArray body = reply()->peek(4 * 1024);
    int httpStatus = reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
    if (body.isEmpty() || httpStatus != 200) {
        qCWarning(lcCheckServerJob) << "error: status.php replied " << httpStatus << body;
        emit instanceNotFound(reply());
    } else {
        QJsonParseError error;
        auto status = QJsonDocument::fromJson(body, &error);
        // empty or invalid response
        if (error.error != QJsonParseError::NoError || status.isNull()) {
            qCWarning(lcCheckServerJob) << "status.php from server is not valid JSON!" << body << reply()->request().url() << error.errorString();
        }

        qCInfo(lcCheckServerJob) << "status.php returns: " << status << " " << reply()->error() << " Reply: " << reply();
        if (status.object().contains("installed")) {
            emit instanceFound(_serverUrl, status.object());
        } else {
            qCWarning(lcCheckServerJob) << "No proper answer on " << reply()->url();
            emit instanceNotFound(reply());
        }
    }
    return true;
}