Example #1
0
/*
 * Returns true on success, with index populated
 * index is undefined otherwise
 */
bool loadAssetsIndexJson(QString path, AssetsIndex *index)
{
	/*
	{
	  "objects": {
		"icons/icon_16x16.png": {
		  "hash": "bdf48ef6b5d0d23bbb02e17d04865216179f510a",
		  "size": 3665
		},
		...
		}
	  }
	}
	*/

	QFile file(path);

	// Try to open the file and fail if we can't.
	// TODO: We should probably report this error to the user.
	if (!file.open(QIODevice::ReadOnly))
	{
		QLOG_ERROR() << "Failed to read assets index file" << path;
		return false;
	}

	// Read the file and close it.
	QByteArray jsonData = file.readAll();
	file.close();

	QJsonParseError parseError;
	QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonData, &parseError);

	// Fail if the JSON is invalid.
	if (parseError.error != QJsonParseError::NoError)
	{
		QLOG_ERROR() << "Failed to parse assets index file:" << parseError.errorString()
					 << "at offset " << QString::number(parseError.offset);
		return false;
	}

	// Make sure the root is an object.
	if (!jsonDoc.isObject())
	{
		QLOG_ERROR() << "Invalid assets index JSON: Root should be an array.";
		return false;
	}

	QJsonObject root = jsonDoc.object();

	QJsonValue isVirtual = root.value("virtual");
	if (!isVirtual.isUndefined())
	{
		index->isVirtual = isVirtual.toBool(false);
	}

	QJsonValue objects = root.value("objects");
	QVariantMap map = objects.toVariant().toMap();

	for (QVariantMap::const_iterator iter = map.begin(); iter != map.end(); ++iter)
	{
		// QLOG_DEBUG() << iter.key();

		QVariant variant = iter.value();
		QVariantMap nested_objects = variant.toMap();

		AssetObject object;

		for (QVariantMap::const_iterator nested_iter = nested_objects.begin();
			 nested_iter != nested_objects.end(); ++nested_iter)
		{
			// QLOG_DEBUG() << nested_iter.key() << nested_iter.value().toString();
			QString key = nested_iter.key();
			QVariant value = nested_iter.value();

			if (key == "hash")
			{
				object.hash = value.toString();
			}
			else if (key == "size")
			{
				object.size = value.toDouble();
			}
		}

		index->objects.insert(iter.key(), object);
	}

	return true;
}
Example #2
0
bool KNAccount::generateAccount(const QString &userName,
                                QString password,
                                const QString &mail)
{
    //Check whether we have already register a user.
    if(m_accountDetails->isLogin())
    {
        //You cannot register a user when login.
        return false;
    }
    //Encrypt the password.
    password=accessPassword(password);
    //Construct the json struct.
    QJsonObject registerData;
    //Save the data.
    registerData.insert("username", userName);
    registerData.insert("password", password);
    registerData.insert("email", mail);
    //Generate the response cache.
    {
        QByteArray responseCache;
        //Send the JSON document to Kreogist cloud.
        if(post(generateKreogistRequest("users"),
                QJsonDocument(registerData).toJson(QJsonDocument::Compact),
                responseCache,
                false)!=201 || responseCache.isEmpty())
        {
            //Emit the register error.
            switch(QJsonDocument::fromJson(responseCache).object().value(
                       "code").toInt())
            {
            case 202:
                emit generateFailed(UserNameAlreadyTaken);
                break;
            case 203:
                emit generateFailed(EmailAlreadyTaken);
                break;
            default:
                emit generateFailed(UnknownRegisterError);
                break;
            }
            //Failed to post then failed.
            return false;
        }
        //Check the response data.
        registerData=QJsonDocument::fromJson(responseCache).object();
    }
    //Check register response data.
    if(registerData.contains("objectId"))
    {
        //Save the user name and password for auto login.
        m_accountDetails->setCacheUserName(userName);
        m_accountDetails->setCachePassword(password);
        //Save the contact information.
        m_accountDetails->setObjectId(
                    registerData.value("objectId").toString());
        m_accountDetails->setSessionToken(
                    registerData.value("sessionToken").toString());
        //Set the login.
        m_accountDetails->setIsLogin(true);
        //Update the account information.
        refreshAccountInfo();
        //Emit register success signal.
        emit generateSuccess();
        //Mission complete.
        return true;
    }
    //Emit failed for unknown reason.
    emit generateFailed(UnknownRegisterError);
    //Or else failed to login.
    return false;
}
Example #3
0
bool KNAccount::updateOnlineAccount(const QJsonObject &userInfo,
                                    bool withSignal)
{
    //Check login first.
    if(!m_accountDetails->isLogin())
    {
        //Check signal flags.
        if(withSignal)
        {
            //Failed to update user info.
            emit userInfoUpdateFailed();
        }
        //Failed to update account info.
        return false;
    }
    //Tring to update account info.
    QNetworkRequest updateRequest=generateKreogistRequest(
                "users/"+m_accountDetails->objectId());
    //Generate response data.
    QByteArray responseData;
    //PUT the json data.
    int putResult=
            accountPut(updateRequest,
                       QJsonDocument(userInfo).toJson(QJsonDocument::Compact),
                       responseData);
    //Check the Internet connection error.
    if(putResult<1)
    {
        //It caused an Internet error.
        emit updateInternetError();
        //Failed to get the result.
        return false;
    }
    //Check if update failed.
    if(putResult!=200)
    {
        //Check signal flags.
        if(withSignal)
        {
            //Failed to update user info.
            emit userInfoUpdateFailed();
        }
        //Failed to update info.
        return false;
    }
    //Successfully update user data.
    //Check whether the data contains password field.
    if(userInfo.contains("password"))
    {
        //Update the cache password.
        m_accountDetails->setCachePassword(
                    userInfo.value("password").toString());
    }
    //Get current user latest data.
    int getResult=
            get(generateKreogistRequest("users/"+m_accountDetails->objectId()),
                responseData,
                false);
    //Check Internet connection error.
    if(getResult<1)
    {
        //There's an connection error.
        emit updateInternetError();
        //Failed to get latest info.
        return false;
    }
    //Check if get the data from server.
    if(getResult!=200)
    {
        //Check signal flags.
        if(withSignal)
        {
            //Failed to update user info.
            emit userInfoUpdateFailed();
        }
        //Failed to update info.
        return false;
    }
    //Update user info.
    updateDetails(QJsonDocument::fromJson(responseData).object());
    //Check signal flags.
    if(withSignal)
    {
        //Emit success signal.
        emit userInfoUpdateSuccess();
    }
    //Mission complete.
    return true;
}
Example #4
0
void ResourceManager::displayLanguages()
      {
      tabs->setTabText(0,tr("Languages"));
      DownloadUtils *js = new DownloadUtils(this);
      js->setTarget(baseAddr + "languages/details.json");
      js->download();
      QByteArray json = js->returnData();

      QJsonParseError err;
      QJsonDocument result = QJsonDocument::fromJson(json, &err);

      if (err.error != QJsonParseError::NoError || !result.isObject()) {
            qFatal("An error occured during parsing");
            return;
            }
      int rowCount = result.object().keys().size();
      rowCount -= 2; //version and type
      qDebug() << result.object().keys().size();
      qDebug() << result.toJson();
      languagesTable->setRowCount(rowCount);

      int row = 0;
      int col = 0;
      QPushButton* updateButtons[rowCount];
      QPushButton* temp;
      languagesTable->verticalHeader()->show();

      QCryptographicHash hash(QCryptographicHash::Sha1);

      for (QString key : result.object().keys()) {
            if (!result.object().value(key).isObject())
                  continue;
            QJsonObject value = result.object().value(key).toObject();
            col = 0;
            QString test = value.value("file_name").toString();
            if(test.length() == 0)
                  continue;

            QString filename = value.value("file_name").toString();
            QString name = value.value("name").toString();
            QString fileSize = value.value("file_size").toString();
            QString hashValue = value.value("hash").toString();

            languagesTable->setItem(row,col++,new QTableWidgetItem (name));
            languagesTable->setItem(row,col++,new QTableWidgetItem (filename));
            languagesTable->setItem(row,col++,new QTableWidgetItem (tr("%1 KB").arg(fileSize)));
            updateButtons[row] = new QPushButton(tr("Update"));

            temp = updateButtons[row];
            buttonMap[temp] = "languages/" + filename;
            buttonHashMap[temp] = hashValue;
            languagesTable->setIndexWidget(languagesTable->model()->index(row,col++), temp);
            QString local = dataPath + "/locale/" + filename;

            QFileInfo fileLocal(local);
            if(!fileLocal.exists())
                  local = mscoreGlobalShare + "locale/" + filename;;

            if(verifyFile(local, hashValue)) {
                  temp->setText(tr("No update"));
                  temp->setDisabled(1);
                  }
            else {
                  connect(temp, SIGNAL(clicked()), this, SLOT(download()));
                  }
            row++;
            }
      }
Example #5
0
bool
HrvMeasureParser::serialize(QString filename, QList<HrvMeasure> &data) {

    // open file - truncate contents
    QFile file(filename);
    if (!file.open(QFile::WriteOnly)) {
        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Critical);
        msgBox.setText(QObject::tr("Problem Saving HRV Measurements"));
        msgBox.setInformativeText(QObject::tr("File: %1 cannot be opened for 'Writing'. Please check file properties.").arg(filename));
        msgBox.exec();
        return false;
    };
    file.resize(0);
    QTextStream out(&file);
    out.setCodec("UTF-8");

    HrvMeasure *m = NULL;
    QJsonArray measures;
    for (int i = 0; i < data.count(); i++) {
        m = &data[i];
        QJsonObject measure;
        measure.insert("when", m->when.toMSecsSinceEpoch()/1000);
        measure.insert("hr", m->hr);
        measure.insert("avnn", m->avnn);
        measure.insert("sdnn", m->sdnn);
        measure.insert("rmssd", m->rmssd);
        measure.insert("pnn50", m->pnn50);
        measure.insert("lf", m->lf);
        measure.insert("hf", m->hf);
        measure.insert("recovery_points", m->recovery_points);
        measure.insert("source", m->source);
        measure.insert("originalsource", m->originalSource);
        measures.append(measure);
    }

    QJsonObject jsonObject;
    // add a version in case of format changes
    jsonObject.insert("version", 1);
    jsonObject.insert("measures",  QJsonValue(measures));

    QJsonDocument json;
    json.setObject(jsonObject);

    out << json.toJson();
    out.flush();
    file.close();
    return true;

}
Example #6
0
void YoutubeSessionData::queryFinished()
{
    QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());

    if (!m_reply) {
        qDebug() << "query finished .. but no reply" << sender();
        return;
    }

    if (reply != m_reply) {
       reply->deleteLater();
       qDebug() << "Late response";
       return;
    }

    delete m_busyToken;
    m_busyToken = 0;

    if (m_context.isValid(this)) {
        QByteArray data = reply->readAll();
        QJsonParseError *error = 0;
        QJsonDocument doc = QJsonDocument::fromJson(data, error);
        //qDebug() << "We have our reply!" << reply->url();
        //qDebug() << doc.toJson();
        if (!error) {
            QJsonObject obj = doc.object();

            QVector<Sprinter::QueryMatch> matches;
            const QJsonArray entries = obj["items"].toArray();
            for (QJsonArray::const_iterator it = entries.begin(); it != entries.end(); ++it) {
                const QJsonObject entry = (*it).toObject();
                if (entry.isEmpty()) {
                    continue;
                }

                const QJsonObject media = entry["snippet"].toObject();
                const QString title = media["title"].toString();
                const QString desc = media["description"].toString();
                const QString author = media["channelTitle"].toString();
                const QString url = s_baseUrl + entry["id"].toObject()["videoId"].toString();
                const QString thumbnailUrl = media["thumbnails"].toObject()["high"].toObject()["url"].toString();

//                 qDebug() << "================================";
//                 qDebug() << title << seconds << time << desc << thumbnailUrl;
                Sprinter::QueryMatch match;
                match.setTitle(tr("%1 (%2)").arg(title, author));
                match.setText(desc);
                match.setType(Sprinter::QuerySession::VideoType);
                match.setSource(Sprinter::QuerySession::FromNetworkService);
                match.setPrecision(Sprinter::QuerySession::CloseMatch);
                match.setUserData(url);
                match.setData(url);
                match.setImage(m_icon.pixmap(m_context.imageSize()).toImage());
                matches << match;

                if (!thumbnailUrl.isEmpty()) {
                    //TODO: requesting the thumbnail EVERY SINGLE TIME is not very cool
                    //      find a way to re-use existing thumbnails
                    QNetworkRequest thumbRequest(thumbnailUrl);
                    QNetworkReply *thumbReply = m_network->get(thumbRequest);
                    connect(thumbReply, SIGNAL(finished()), this, SLOT(thumbRecv()));
                    m_thumbJobs.insert(thumbReply->url(), match);
                }
            }
//             qDebug() <<" **********" << matches.count();
            setMatches(matches, m_context);
            setCanFetchMoreMatches(true, m_context);
        }
    }

    reply->deleteLater();
    m_reply = 0;
}
QJsonObject DomainServerSettingsManager::responseObjectForType(const QString& typeValue, bool isAuthenticated) {
    QJsonObject responseObject;
    
    if (!typeValue.isEmpty() || isAuthenticated) {
        // convert the string type value to a QJsonValue
        QJsonValue queryType = typeValue.isEmpty() ? QJsonValue() : QJsonValue(typeValue.toInt());
        
        const QString AFFECTED_TYPES_JSON_KEY = "assignment-types";
        
        // enumerate the groups in the description object to find which settings to pass
        foreach(const QJsonValue& groupValue, _descriptionArray) {
            QJsonObject groupObject = groupValue.toObject();
            QString groupKey = groupObject[DESCRIPTION_NAME_KEY].toString();
            QJsonArray groupSettingsArray = groupObject[DESCRIPTION_SETTINGS_KEY].toArray();
            
            QJsonObject groupResponseObject;
            
            foreach(const QJsonValue& settingValue, groupSettingsArray) {
                const QString VALUE_HIDDEN_FLAG_KEY = "value-hidden";
                
                QJsonObject settingObject = settingValue.toObject();
                
                if (!settingObject[VALUE_HIDDEN_FLAG_KEY].toBool()) {
                    QJsonArray affectedTypesArray = settingObject[AFFECTED_TYPES_JSON_KEY].toArray();
                    if (affectedTypesArray.isEmpty()) {
                        affectedTypesArray = groupObject[AFFECTED_TYPES_JSON_KEY].toArray();
                    }
                    
                    if (affectedTypesArray.contains(queryType) ||
                        (queryType.isNull() && isAuthenticated)) {
                        // this is a setting we should include in the responseObject
                        
                        QString settingName = settingObject[DESCRIPTION_NAME_KEY].toString();
                        
                        // we need to check if the settings map has a value for this setting
                        QVariant variantValue;
                        QVariant settingsMapGroupValue = _settingsMap.value(groupObject[DESCRIPTION_NAME_KEY].toString());
                        
                        if (!settingsMapGroupValue.isNull()) {
                            variantValue = settingsMapGroupValue.toMap().value(settingName);
                        }
                        
                        if (variantValue.isNull()) {
                            // no value for this setting, pass the default
                            if (settingObject.contains(SETTING_DEFAULT_KEY)) {
                                groupResponseObject[settingName] = settingObject[SETTING_DEFAULT_KEY];
                            } else {
                                // users are allowed not to provide a default for string values
                                // if so we set to the empty string
                                groupResponseObject[settingName] = QString("");
                            }
                            
                        } else {
                            groupResponseObject[settingName] = QJsonValue::fromVariant(variantValue);
                        }
                    }
                }
            }
            
            if (!groupResponseObject.isEmpty()) {
                // set this group's object to the constructed object
                responseObject[groupKey] = groupResponseObject;
            }
        }
Example #8
0
void AudioMixer::parseSettingsObject(const QJsonObject &settingsObject) {
    if (settingsObject.contains(AUDIO_BUFFER_GROUP_KEY)) {
        QJsonObject audioBufferGroupObject = settingsObject[AUDIO_BUFFER_GROUP_KEY].toObject();

        // check the payload to see if we have asked for dynamicJitterBuffer support
        const QString DYNAMIC_JITTER_BUFFER_JSON_KEY = "dynamic_jitter_buffer";
        _streamSettings._dynamicJitterBuffers = audioBufferGroupObject[DYNAMIC_JITTER_BUFFER_JSON_KEY].toBool();
        if (_streamSettings._dynamicJitterBuffers) {
            qDebug() << "Enable dynamic jitter buffers.";
        } else {
            qDebug() << "Dynamic jitter buffers disabled.";
        }

        bool ok;
        const QString DESIRED_JITTER_BUFFER_FRAMES_KEY = "static_desired_jitter_buffer_frames";
        _streamSettings._staticDesiredJitterBufferFrames = audioBufferGroupObject[DESIRED_JITTER_BUFFER_FRAMES_KEY].toString().toInt(&ok);
        if (!ok) {
            _streamSettings._staticDesiredJitterBufferFrames = DEFAULT_STATIC_DESIRED_JITTER_BUFFER_FRAMES;
        }
        qDebug() << "Static desired jitter buffer frames:" << _streamSettings._staticDesiredJitterBufferFrames;

        const QString MAX_FRAMES_OVER_DESIRED_JSON_KEY = "max_frames_over_desired";
        _streamSettings._maxFramesOverDesired = audioBufferGroupObject[MAX_FRAMES_OVER_DESIRED_JSON_KEY].toString().toInt(&ok);
        if (!ok) {
            _streamSettings._maxFramesOverDesired = DEFAULT_MAX_FRAMES_OVER_DESIRED;
        }
        qDebug() << "Max frames over desired:" << _streamSettings._maxFramesOverDesired;

        const QString USE_STDEV_FOR_DESIRED_CALC_JSON_KEY = "use_stdev_for_desired_calc";
        _streamSettings._useStDevForJitterCalc = audioBufferGroupObject[USE_STDEV_FOR_DESIRED_CALC_JSON_KEY].toBool();
        if (_streamSettings._useStDevForJitterCalc) {
            qDebug() << "Using stdev method for jitter calc if dynamic jitter buffers enabled";
        } else {
            qDebug() << "Using max-gap method for jitter calc if dynamic jitter buffers enabled";
        }

        const QString WINDOW_STARVE_THRESHOLD_JSON_KEY = "window_starve_threshold";
        _streamSettings._windowStarveThreshold = audioBufferGroupObject[WINDOW_STARVE_THRESHOLD_JSON_KEY].toString().toInt(&ok);
        if (!ok) {
            _streamSettings._windowStarveThreshold = DEFAULT_WINDOW_STARVE_THRESHOLD;
        }
        qDebug() << "Window A starve threshold:" << _streamSettings._windowStarveThreshold;

        const QString WINDOW_SECONDS_FOR_DESIRED_CALC_ON_TOO_MANY_STARVES_JSON_KEY = "window_seconds_for_desired_calc_on_too_many_starves";
        _streamSettings._windowSecondsForDesiredCalcOnTooManyStarves = audioBufferGroupObject[WINDOW_SECONDS_FOR_DESIRED_CALC_ON_TOO_MANY_STARVES_JSON_KEY].toString().toInt(&ok);
        if (!ok) {
            _streamSettings._windowSecondsForDesiredCalcOnTooManyStarves = DEFAULT_WINDOW_SECONDS_FOR_DESIRED_CALC_ON_TOO_MANY_STARVES;
        }
        qDebug() << "Window A length:" << _streamSettings._windowSecondsForDesiredCalcOnTooManyStarves << "seconds";

        const QString WINDOW_SECONDS_FOR_DESIRED_REDUCTION_JSON_KEY = "window_seconds_for_desired_reduction";
        _streamSettings._windowSecondsForDesiredReduction = audioBufferGroupObject[WINDOW_SECONDS_FOR_DESIRED_REDUCTION_JSON_KEY].toString().toInt(&ok);
        if (!ok) {
            _streamSettings._windowSecondsForDesiredReduction = DEFAULT_WINDOW_SECONDS_FOR_DESIRED_REDUCTION;
        }
        qDebug() << "Window B length:" << _streamSettings._windowSecondsForDesiredReduction << "seconds";

        const QString REPETITION_WITH_FADE_JSON_KEY = "repetition_with_fade";
        _streamSettings._repetitionWithFade = audioBufferGroupObject[REPETITION_WITH_FADE_JSON_KEY].toBool();
        if (_streamSettings._repetitionWithFade) {
            qDebug() << "Repetition with fade enabled";
        } else {
            qDebug() << "Repetition with fade disabled";
        }

        const QString PRINT_STREAM_STATS_JSON_KEY = "print_stream_stats";
        _printStreamStats = audioBufferGroupObject[PRINT_STREAM_STATS_JSON_KEY].toBool();
        if (_printStreamStats) {
            qDebug() << "Stream stats will be printed to stdout";
        }
    }

    if (settingsObject.contains(AUDIO_ENV_GROUP_KEY)) {
        QJsonObject audioEnvGroupObject = settingsObject[AUDIO_ENV_GROUP_KEY].toObject();

        const QString ATTENATION_PER_DOULING_IN_DISTANCE = "attenuation_per_doubling_in_distance";
        if (audioEnvGroupObject[ATTENATION_PER_DOULING_IN_DISTANCE].isString()) {
            bool ok = false;
            float attenuation = audioEnvGroupObject[ATTENATION_PER_DOULING_IN_DISTANCE].toString().toFloat(&ok);
            if (ok) {
                _attenuationPerDoublingInDistance = attenuation;
                qDebug() << "Attenuation per doubling in distance changed to" << _attenuationPerDoublingInDistance;
            }
        }

        const QString NOISE_MUTING_THRESHOLD = "noise_muting_threshold";
        if (audioEnvGroupObject[NOISE_MUTING_THRESHOLD].isString()) {
            bool ok = false;
            float noiseMutingThreshold = audioEnvGroupObject[NOISE_MUTING_THRESHOLD].toString().toFloat(&ok);
            if (ok) {
                _noiseMutingThreshold = noiseMutingThreshold;
                qDebug() << "Noise muting threshold changed to" << _noiseMutingThreshold;
            }
        }

        const QString FILTER_KEY = "enable_filter";
        if (audioEnvGroupObject[FILTER_KEY].isBool()) {
            _enableFilter = audioEnvGroupObject[FILTER_KEY].toBool();
        }
        if (_enableFilter) {
            qDebug() << "Filter enabled";
        }

        const QString AUDIO_ZONES = "zones";
        if (audioEnvGroupObject[AUDIO_ZONES].isObject()) {
            const QJsonObject& zones = audioEnvGroupObject[AUDIO_ZONES].toObject();

            const QString X_RANGE = "x_range";
            const QString Y_RANGE = "y_range";
            const QString Z_RANGE = "z_range";
            foreach (const QString& zone, zones.keys()) {
                QJsonObject zoneObject = zones[zone].toObject();

                if (zoneObject.contains(X_RANGE) && zoneObject.contains(Y_RANGE) && zoneObject.contains(Z_RANGE)) {
                    QStringList xRange = zoneObject.value(X_RANGE).toString().split("-", QString::SkipEmptyParts);
                    QStringList yRange = zoneObject.value(Y_RANGE).toString().split("-", QString::SkipEmptyParts);
                    QStringList zRange = zoneObject.value(Z_RANGE).toString().split("-", QString::SkipEmptyParts);

                    if (xRange.size() == 2 && yRange.size() == 2 && zRange.size() == 2) {
                        float xMin, xMax, yMin, yMax, zMin, zMax;
                        bool ok, allOk = true;
                        xMin = xRange[0].toFloat(&ok);
                        allOk &= ok;
                        xMax = xRange[1].toFloat(&ok);
                        allOk &= ok;
                        yMin = yRange[0].toFloat(&ok);
                        allOk &= ok;
                        yMax = yRange[1].toFloat(&ok);
                        allOk &= ok;
                        zMin = zRange[0].toFloat(&ok);
                        allOk &= ok;
                        zMax = zRange[1].toFloat(&ok);
                        allOk &= ok;

                        if (allOk) {
                            glm::vec3 corner(xMin, yMin, zMin);
                            glm::vec3 dimensions(xMax - xMin, yMax - yMin, zMax - zMin);
                            AABox zoneAABox(corner, dimensions);
                            _audioZones.insert(zone, zoneAABox);
                            qDebug() << "Added zone:" << zone << "(corner:" << corner
                                     << ", dimensions:" << dimensions << ")";
                        }
                    }
                }
            }
        }

        const QString ATTENUATION_COEFFICIENTS = "attenuation_coefficients";
        if (audioEnvGroupObject[ATTENUATION_COEFFICIENTS].isArray()) {
            const QJsonArray& coefficients = audioEnvGroupObject[ATTENUATION_COEFFICIENTS].toArray();

            const QString SOURCE = "source";
            const QString LISTENER = "listener";
            const QString COEFFICIENT = "coefficient";
            for (int i = 0; i < coefficients.count(); ++i) {
                QJsonObject coefficientObject = coefficients[i].toObject();

                if (coefficientObject.contains(SOURCE) &&
                    coefficientObject.contains(LISTENER) &&
                    coefficientObject.contains(COEFFICIENT)) {

                    ZonesSettings settings;

                    bool ok;
                    settings.source = coefficientObject.value(SOURCE).toString();
                    settings.listener = coefficientObject.value(LISTENER).toString();
                    settings.coefficient = coefficientObject.value(COEFFICIENT).toString().toFloat(&ok);

                    if (ok && settings.coefficient >= 0.0f && settings.coefficient <= 1.0f &&
                        _audioZones.contains(settings.source) && _audioZones.contains(settings.listener)) {

                        _zonesSettings.push_back(settings);
                        qDebug() << "Added Coefficient:" << settings.source << settings.listener << settings.coefficient;
                    }
                }
            }
        }

        const QString REVERB = "reverb";
        if (audioEnvGroupObject[REVERB].isArray()) {
            const QJsonArray& reverb = audioEnvGroupObject[REVERB].toArray();

            const QString ZONE = "zone";
            const QString REVERB_TIME = "reverb_time";
            const QString WET_LEVEL = "wet_level";
            for (int i = 0; i < reverb.count(); ++i) {
                QJsonObject reverbObject = reverb[i].toObject();

                if (reverbObject.contains(ZONE) &&
                    reverbObject.contains(REVERB_TIME) &&
                    reverbObject.contains(WET_LEVEL)) {

                    bool okReverbTime, okWetLevel;
                    QString zone = reverbObject.value(ZONE).toString();
                    float reverbTime = reverbObject.value(REVERB_TIME).toString().toFloat(&okReverbTime);
                    float wetLevel = reverbObject.value(WET_LEVEL).toString().toFloat(&okWetLevel);

                    if (okReverbTime && okWetLevel && _audioZones.contains(zone)) {
                        ReverbSettings settings;
                        settings.zone = zone;
                        settings.reverbTime = reverbTime;
                        settings.wetLevel = wetLevel;

                        _zoneReverbSettings.push_back(settings);
                        qDebug() << "Added Reverb:" << zone << reverbTime << wetLevel;
                    }
                }
            }
        }
    }
Example #9
0
/** ***************************************************************************/
void ChromeBookmarks::Indexer::run() {

    // Notification
    QString msg("Indexing bookmarks ...");
    emit statusInfo(msg);
    qDebug() << "[ChromeBookmarks]" << msg;

    // Build a new index
    vector<shared_ptr<Bookmark>> newIndex;

    // Define a recursive bookmark indexing lambda
    std::function<void(const QJsonObject &json)> rec_bmsearch =
            [&rec_bmsearch, &newIndex](const QJsonObject &json) {
        QJsonValue type = json["type"];
        if (type == QJsonValue::Undefined)
            return;
        if (type.toString() == "folder"){
            QJsonArray jarr = json["children"].toArray();
            for (const QJsonValue &i : jarr)
                rec_bmsearch(i.toObject());
        }
        if (type.toString() == "url") {
            // TODO ADD THE FOLDERS to the aliases
            newIndex.push_back(std::make_shared<Bookmark>(
                                 json["name"].toString(), json["url"].toString(), 0));
        }
    };

    QFile f(_extension->_bookmarksFile);
    if (!f.open(QIODevice::ReadOnly)) {
        qWarning() << "Could not open " << _extension->_bookmarksFile;
        return;
    }

    QJsonObject json = QJsonDocument::fromJson(f.readAll()).object();
    QJsonObject roots = json.value("roots").toObject();
    for (const QJsonValue &i : roots)
        if (i.isObject())
            rec_bmsearch(i.toObject());

    f.close();


    // Sort the new index for linear usage copy [O(n*log(n))]
    emit statusInfo("Sorting ... ");
    std::sort(newIndex.begin(), newIndex.end(),
              [&](const shared_ptr<Bookmark> lhs, const shared_ptr<Bookmark> rhs) {
                  return QString::compare(lhs->url(), rhs->url(), Qt::CaseInsensitive) < 0;
              });


    // Copy the usagecounters  [O(n)]
    emit statusInfo("Copy usage statistics ... ");
    size_t i=0, j=0;
    while (i < _extension->_index.size() && j < newIndex.size()) {
        if (_extension->_index[i]->url_ == newIndex[j]->url_) {
            newIndex[j]->usage_ = _extension->_index[i]->usage_;
            ++i;++j;
        } else if (_extension->_index[i]->url_ < newIndex[j]->url_ ) {
            ++i;
        } else {// if ((*_fileIndex)[i]->path > (*newIndex)[j]->path) {
            ++j;
        }
    }

    /*
     *  ▼ CRITICAL ▼
     */

    // Lock the access
    _extension->_indexAccess.lock();

    // Set the new index
    _extension->_index = std::move(newIndex);

    // Reset the offline index
    emit statusInfo("Build offline index... ");
    _extension->_searchIndex.clear();

    // Build the new offline index
    for (shared_ptr<IIndexable> i : _extension->_index)
        _extension->_searchIndex.add(i);

    // Unlock the accress
    _extension->_indexAccess.unlock();

    // Finally update the watches (maybe folders changed)
    _extension->_watcher.removePaths(_extension->_watcher.files());
    if(!_extension->_watcher.addPath(_extension->_bookmarksFile)) // No clue why this should happen
        qCritical() << _extension->_bookmarksFile
                    <<  "could not be watched. Changes in this path will not be noticed.";
    /*
     *  ▲ CRITICAL ▲
     */

    // Notification
    msg = QString("Indexed %1 bookmarks.").arg(_extension->_index.size());
    emit statusInfo(msg);
    qDebug() << "[ChromeBookmarks]" << msg;
}
Example #10
0
QJsonObject MojangAccount::saveToJson() const
{
	QJsonObject json;
	json.insert("username", m_username);
	json.insert("clientToken", m_clientToken);
	json.insert("accessToken", m_accessToken);

	QJsonArray profileArray;
	for (AccountProfile profile : m_profiles)
	{
		QJsonObject profileObj;
		profileObj.insert("id", profile.id);
		profileObj.insert("name", profile.name);
		profileObj.insert("legacy", profile.legacy);
		profileArray.append(profileObj);
	}
	json.insert("profiles", profileArray);

	QJsonObject userStructure;
	{
		userStructure.insert("id", m_user.id);
		/*
		QJsonObject userAttrs;
		for(auto key: m_user.properties.keys())
		{
			auto array = QJsonArray::fromStringList(m_user.properties.values(key));
			userAttrs.insert(key, array);
		}
		userStructure.insert("properties", userAttrs);
		*/
	}
	json.insert("user", userStructure);

	if (m_currentProfile != -1)
		json.insert("activeProfile", currentProfile()->id);

	return json;
}
Example #11
0
MojangAccountPtr MojangAccount::loadFromJson(const QJsonObject &object)
{
	// The JSON object must at least have a username for it to be valid.
	if (!object.value("username").isString())
	{
		QLOG_ERROR() << "Can't load Mojang account info from JSON object. Username field is "
						"missing or of the wrong type.";
		return nullptr;
	}

	QString username = object.value("username").toString("");
	QString clientToken = object.value("clientToken").toString("");
	QString accessToken = object.value("accessToken").toString("");

	QJsonArray profileArray = object.value("profiles").toArray();
	if (profileArray.size() < 1)
	{
		QLOG_ERROR() << "Can't load Mojang account with username \"" << username
					 << "\". No profiles found.";
		return nullptr;
	}

	QList<AccountProfile> profiles;
	for (QJsonValue profileVal : profileArray)
	{
		QJsonObject profileObject = profileVal.toObject();
		QString id = profileObject.value("id").toString("");
		QString name = profileObject.value("name").toString("");
		bool legacy = profileObject.value("legacy").toBool(false);
		if (id.isEmpty() || name.isEmpty())
		{
			QLOG_WARN() << "Unable to load a profile because it was missing an ID or a name.";
			continue;
		}
		profiles.append({id, name, legacy});
	}

	MojangAccountPtr account(new MojangAccount());
	if (object.value("user").isObject())
	{
		User u;
		QJsonObject userStructure = object.value("user").toObject();
		u.id = userStructure.value("id").toString();
		/*
		QJsonObject propMap = userStructure.value("properties").toObject();
		for(auto key: propMap.keys())
		{
			auto values = propMap.operator[](key).toArray();
			for(auto value: values)
				u.properties.insert(key, value.toString());
		}
		*/
		account->m_user = u;
	}
	account->m_username = username;
	account->m_clientToken = clientToken;
	account->m_accessToken = accessToken;
	account->m_profiles = profiles;

	// Get the currently selected profile.
	QString currentProfile = object.value("activeProfile").toString("");
	if (!currentProfile.isEmpty())
		account->setCurrentProfile(currentProfile);

	return account;
}
Example #12
0
void Authorization::loadFromJson(const QJsonObject &json)
{
    if (json.isEmpty()) {
        return;
    }

    Q_D(Authorization);

    QScopedPointer<const PPEnumsMap> em(new PPEnumsMap);

    d->setId(json.value(QStringLiteral("id")).toString());

    const QJsonObject ao = json.value(QStringLiteral("amount")).toObject();
    PaymentAmount *oldAo = amount();
    if (!ao.isEmpty()) {
        if (oldAo) {
            oldAo->loadFromJson(ao);
        } else {
            setAmount(new PaymentAmount(ao, this));
        }
    } else {
        setAmount(nullptr);
        delete oldAo;
    }


    d->setPaymentMode(em->paymentModeTypeTokenToEnum(json.value(QStringLiteral("payment_mode")).toString()));

    d->setState(em->stateTypeTokenToEnum(json.value(QStringLiteral("state")).toString()));

    d->setReasonCode(em->reasonCodeTokenToEnum(json.value(QStringLiteral("reason_code")).toString()));

    d->setProtectionEligibility(em->protectionEligibilityTokenToEnum(json.value(QStringLiteral("protection_eligibility")).toString()));

    const QString pets = json.value(QStringLiteral("protection_eligibility_type")).toString();
    if (!pets.isEmpty()) {
        QList<Geltan::PP::PayPal::ProtectionEligibilityType> petList;
        const QStringList petsList = pets.split(QChar(','));
        petList.reserve(petsList.size());
        for (const QString &pet : petsList) {
            petList.append(em->protectionEligibilityTypeTokenToEnum(pet));
        }
        d->setProtectionEligibilityType(petList);
    } else {
        d->setProtectionEligibilityType(QList<Geltan::PP::PayPal::ProtectionEligibilityType>());
    }

    const QJsonObject fmfo = json.value(QStringLiteral("fmf_details")).toObject();
    FMFDetails *oldFmf = fmfDetails();
    if (!fmfo.isEmpty()) {
        if (oldFmf) {
            oldFmf->loadFromJson(fmfo);
        } else {
            d->setFmfDetails(new FMFDetails(fmfo, this));
        }
    } else {
        d->setFmfDetails(nullptr);
        delete oldFmf;
    }

    d->setParentPayment(json.value(QStringLiteral("parent_payment")).toString());

    const QString vu = json.value(QStringLiteral("valid_until")).toString();
    if (!vu.isEmpty()) {
        d->setValidUntil(QDateTime::fromString(vu, Qt::ISODate));
    } else {
        d->setValidUntil(QDateTime());
    }

    const QString ct = json.value(QStringLiteral("create_time")).toString();
    if (!ct.isEmpty()) {
        d->setCreateTime(QDateTime::fromString(ct, Qt::ISODate));
    } else {
        d->setCreateTime(QDateTime());
    }

    const QString ut = json.value(QStringLiteral("update_time")).toString();
    if (!ut.isEmpty()) {
        d->setUpdateTime(QDateTime::fromString(ut, Qt::ISODate));
    } else {
        d->setUpdateTime(QDateTime());
    }

    d->setReferenceId(json.value(QStringLiteral("reference_id")).toString());

    d->setReceiptId(json.value(QStringLiteral("receipt_id")).toString());

    const QJsonArray la = json.value(QStringLiteral("links")).toArray();
    d->clearLinks();
    Q_EMIT linksChanged(links());
    if (!la.isEmpty()) {
        QList<Link*> linksToAdd;
        QJsonArray::const_iterator i = la.constBegin();
        while (i != la.constEnd()) {
            linksToAdd.append(new Link(i->toObject()));
            ++i;
        }
        d->setLinks(linksToAdd);
    }
}
Example #13
0
void WebSocket::EvaluateRequest(const RestInputStruct &REQ){
  RestOutputStruct out;
    out.in_struct = REQ;
  QHostAddress host;
    if(SOCKET!=0){ host = SOCKET->peerAddress(); }
    else if(TSOCKET!=0){ host = TSOCKET->peerAddress(); }
  if(!REQ.VERB.isEmpty() && REQ.VERB != "GET" && REQ.VERB!="POST" && REQ.VERB!="PUT"){
    //Non-supported request (at the moment) - return an error message
    out.CODE = RestOutputStruct::BADREQUEST;
  }else if(out.in_struct.name.isEmpty() || out.in_struct.namesp.isEmpty() ){
    //Invalid JSON structure validity
    //Note: id and args are optional at this stage - let the subsystems handle those inputs
    out.CODE = RestOutputStruct::BADREQUEST;
  }else{
    //First check for a REST authorization (not stand-alone request)
    if(!out.in_struct.auth.isEmpty()){
      AUTHSYSTEM->clearAuth(SockAuthToken); //new auth requested - clear any old token
      SockAuthToken = AUTHSYSTEM->LoginUP(host, out.in_struct.auth.section(":",0,0), out.in_struct.auth.section(":",1,1));
    }
	  
    //Now check the body of the message and do what it needs
      if(out.in_struct.namesp.toLower() == "rpc"){
	if(out.in_struct.name.startsWith("auth")){
	  //Now perform authentication based on type of auth given
	  //Note: This sets/changes the current SockAuthToken
	  AUTHSYSTEM->clearAuth(SockAuthToken); //new auth requested - clear any old token
	  if(DEBUG){ qDebug() << "Authenticate Peer:" << SOCKET->peerAddress().toString(); }
	  //Now do the auth
	  if(out.in_struct.name=="auth" && out.in_struct.args.isObject() ){
	    //username/[password/cert] authentication
	    QString user, pass;
	    if(out.in_struct.args.toObject().contains("username")){ user = JsonValueToString(out.in_struct.args.toObject().value("username"));  }
	    if(out.in_struct.args.toObject().contains("password")){ pass = JsonValueToString(out.in_struct.args.toObject().value("password"));  }
	    if(!pass.isEmpty()){
	      //Use the given password
	      SockAuthToken = AUTHSYSTEM->LoginUP(host, user, pass);
	    }else{
	      //No password - use the current SSL certificates instead
	      QList<QSslCertificate> certs;
	      if(SOCKET!=0){ certs = SOCKET->sslConfiguration().peerCertificateChain(); }
	      else if(TSOCKET!=0){ certs = TSOCKET->peerCertificateChain(); }
	      SockAuthToken = AUTHSYSTEM->LoginUC(host, user, certs);
	    }
	  }else if(out.in_struct.name == "auth_token" && out.in_struct.args.isObject()){
	    SockAuthToken = JsonValueToString(out.in_struct.args.toObject().value("token"));
	  }else if(out.in_struct.name == "auth_clear"){
	    return; //don't send a return message after clearing an auth (already done)
	  }
	  
	  //Now check the auth and respond appropriately
	  if(AUTHSYSTEM->checkAuth(SockAuthToken)){
	    //Good Authentication - return the new token 
	    QJsonArray array;
	      array.append(SockAuthToken);
	      array.append(AUTHSYSTEM->checkAuthTimeoutSecs(SockAuthToken));
	    out.out_args = array;
	    out.CODE = RestOutputStruct::OK;
	  }else{
	    if(SockAuthToken=="REFUSED"){
	      out.CODE = RestOutputStruct::FORBIDDEN;
	    }
	    SockAuthToken.clear(); //invalid token
	    //Bad Authentication - return error
	      out.CODE = RestOutputStruct::UNAUTHORIZED;
	  }
		
	}else if( AUTHSYSTEM->checkAuth(SockAuthToken) ){ //validate current Authentication token	 
	  //Now provide access to the various subsystems
	  // First get/set the permissions flag into the input structure
	    out.in_struct.fullaccess = AUTHSYSTEM->hasFullAccess(SockAuthToken);
	  //Pre-set any output fields
          QJsonObject outargs;	
	    out.CODE = EvaluateBackendRequest(out.in_struct, &outargs);
            out.out_args = outargs;	  
        }else{
	  //Bad/No authentication
	  out.CODE = RestOutputStruct::UNAUTHORIZED;
	}
	    	
      }else if(out.in_struct.namesp.toLower() == "events"){
          if( AUTHSYSTEM->checkAuth(SockAuthToken) ){ //validate current Authentication token	 
	    //Pre-set any output fields
            QJsonObject outargs;	
	    //Assemble the list of input events
	    QStringList evlist;
	    if(out.in_struct.args.isObject()){ evlist << JsonValueToString(out.in_struct.args); }
	    else if(out.in_struct.args.isArray()){ evlist = JsonArrayToStringList(out.in_struct.args.toArray()); }
	    //Now subscribe/unsubscribe to these events
	    int sub = -1; //bad input
	    if(out.in_struct.name=="subscribe"){ sub = 1; }
	    else if(out.in_struct.name=="unsubscribe"){ sub = 0; }
	    //qDebug() << "Got Client Event Modification:" << sub << evlist;
	    if(sub>=0 && !evlist.isEmpty() ){
	      for(int i=0; i<evlist.length(); i++){
	        EventWatcher::EVENT_TYPE type = EventWatcher::typeFromString(evlist[i]);
		if(type==EventWatcher::BADEVENT){ continue; }
		outargs.insert(out.in_struct.name,QJsonValue(evlist[i]));
		if(sub==1){ 
		  ForwardEvents << type; 
		  EventUpdate(type);
		}else{
		  ForwardEvents.removeAll(type);
		}
	      }
	      out.out_args = outargs;
	      out.CODE = RestOutputStruct::OK;
	    }else{
	      //Bad/No authentication
	      out.CODE = RestOutputStruct::BADREQUEST;		    
	    }
          }else{
	    //Bad/No authentication
	    out.CODE = RestOutputStruct::UNAUTHORIZED;
	  }
	//Other namespace - check whether auth has already been established before continuing
	}else if( AUTHSYSTEM->checkAuth(SockAuthToken) ){ //validate current Authentication token	 
	  //Now provide access to the various subsystems
	  // First get/set the permissions flag into the input structure
	  out.in_struct.fullaccess = AUTHSYSTEM->hasFullAccess(SockAuthToken);
	  //Pre-set any output fields
          QJsonObject outargs;	
	    out.CODE = EvaluateBackendRequest(out.in_struct, &outargs);
            out.out_args = outargs;
	}else{
	  //Error in inputs - assemble the return error message
	  out.CODE = RestOutputStruct::UNAUTHORIZED;
	}
    //If this is a REST input - go ahead and format the output header
    if(out.CODE == RestOutputStruct::OK){
      out.Header << "Content-Type: text/json; charset=utf-8";
    }
  }
  //Return any information
  this->sendReply(out.assembleMessage());
  if(out.CODE == RestOutputStruct::FORBIDDEN && SOCKET!=0){
    SOCKET->close(QWebSocketProtocol::CloseCodeNormal, "Too Many Authorization Failures - Try again later");
  }
}
Example #14
0
void SpectrumSettings::fromJson(const QJsonObject & settings) {
    _custom_color_spectrum = settings.value(SETTINGS_CUSTOM_COLOR_SPECTRUM_KEY).toBool(true);

    _auto_bars_amount = settings.value(SETTINGS_AUTO_BARS_AMOUNT_KEY).toBool(true);

    QVariant color_var = settings.value(SETTINGS_SPECTRUM_COLOR1_KEY).toVariant();
    _spectrum_color = color_var.isValid() ? color_var.value<QColor>() : QColor(0, 0, 0);

    color_var = settings.value(SETTINGS_SPECTRUM_COLOR2_KEY).toVariant();
    _spectrum_color2 = color_var.isValid() ? color_var.value<QColor>() : QColor(128, 128, 128);

    color_var = settings.value(SETTINGS_SPECTRUM_COLOR3_KEY).toVariant();
    _spectrum_color3 = color_var.isValid() ? color_var.value<QColor>() : QColor(255, 255, 255);


    _spectrum_freq_rate = settings.value(SETTINGS_SPECTRUM_RATE_KEY).toInt(15);
    _spectrum_bars_count = settings.value(SETTINGS_SPECTRUM_BARS_COUNT_KEY).toInt(30);

    _spectrum_height = settings.value(SETTINGS_SPECTRUM_HEIGHT_KEY).toInt(60);
    _spectrum_type = (SpectrumType)settings.value(SETTINGS_SPECTRUM_TYPE_KEY).toInt(1);

    _spectrum_multiplier = settings.value(SETTINGS_SPECTRUM_MULTIPLIER_KEY).toInt(3);

    _auto_bar_width = settings.value(SETTINGS_AUTO_BARS_WIDTH_KEY).toInt(10);
}
Example #15
0
void JsonProcessor::handleServerInfoCommand(const QJsonObject&, const QString& command, const int tan)
{
	// create result
	QJsonObject result;
	result["success"] = true;
	result["command"] = command;
	result["tan"] = tan;

	QJsonObject info;

	// collect priority information
	QJsonArray priorities;
	uint64_t now = QDateTime::currentMSecsSinceEpoch();
	QList<int> activePriorities = _hyperion->getActivePriorities();
	Hyperion::PriorityRegister priorityRegister = _hyperion->getPriorityRegister();
	int currentPriority = _hyperion->getCurrentPriority();

	foreach (int priority, activePriorities) {
		const Hyperion::InputInfo & priorityInfo = _hyperion->getPriorityInfo(priority);
		QJsonObject item;
		item["priority"] = priority;
		if (priorityInfo.timeoutTime_ms != -1 )
		{
			item["duration_ms"] = int(priorityInfo.timeoutTime_ms - now);
		}

		item["owner"]       = QString(hyperion::componentToIdString(priorityInfo.componentId));
		item["componentId"] = QString(hyperion::componentToIdString(priorityInfo.componentId));
		item["origin"] = priorityInfo.origin;
		item["active"] = true;
		item["visible"] = (priority == currentPriority);

		// remove item from prio register, because we have more valuable information via active priority
		QList<QString> prios = priorityRegister.keys(priority);
		if (! prios.empty())
		{
			item["owner"] = prios[0];
			priorityRegister.remove(prios[0]);
		}

		if(priorityInfo.componentId == hyperion::COMP_COLOR)
		{
			QJsonObject LEDcolor;

			// add RGB Value to Array
			QJsonArray RGBValue;
			RGBValue.append(priorityInfo.ledColors.begin()->red);
			RGBValue.append(priorityInfo.ledColors.begin()->green);
			RGBValue.append(priorityInfo.ledColors.begin()->blue);
			LEDcolor.insert("RGB", RGBValue);

			uint16_t Hue;
			float Saturation, Luminace;

			// add HSL Value to Array
			QJsonArray HSLValue;
			ColorSys::rgb2hsl(priorityInfo.ledColors.begin()->red,
					priorityInfo.ledColors.begin()->green,
					priorityInfo.ledColors.begin()->blue,
					Hue, Saturation, Luminace);

			HSLValue.append(Hue);
			HSLValue.append(Saturation);
			HSLValue.append(Luminace);
			LEDcolor.insert("HSL", HSLValue);

			// add HEX Value to Array ["HEX Value"]
			QJsonArray HEXValue;
			std::stringstream hex;
				hex << "0x"
				<< std::uppercase << std::setw(2) << std::setfill('0')
				<< std::hex << unsigned(priorityInfo.ledColors.begin()->red)
				<< std::uppercase << std::setw(2) << std::setfill('0')
				<< std::hex << unsigned(priorityInfo.ledColors.begin()->green)
				<< std::uppercase << std::setw(2) << std::setfill('0')
				<< std::hex << unsigned(priorityInfo.ledColors.begin()->blue);

			HEXValue.append(QString::fromStdString(hex.str()));
			LEDcolor.insert("HEX", HEXValue);

			item["value"] = LEDcolor;
		}
		// priorities[priorities.size()] = item;
		priorities.append(item);
	}

	// append left over priorities
	for(auto key : priorityRegister.keys())
	{
		QJsonObject item;
		item["priority"] = priorityRegister[key];
		item["active"]   = false;
		item["visible"]  = false;
		item["owner"]    = key;
		priorities.append(item);
	}

	info["priorities"] = priorities;
	info["priorities_autoselect"] = _hyperion->sourceAutoSelectEnabled();

	// collect adjustment information
	QJsonArray adjustmentArray;
	for (const QString& adjustmentId : _hyperion->getAdjustmentIds())
	{
		const ColorAdjustment * colorAdjustment = _hyperion->getAdjustment(adjustmentId);
		if (colorAdjustment == nullptr)
		{
			Error(_log, "Incorrect color adjustment id: %s", QSTRING_CSTR(adjustmentId));
			continue;
		}

		QJsonObject adjustment;
		adjustment["id"] = adjustmentId;

		QJsonArray blackAdjust;
		blackAdjust.append(colorAdjustment->_rgbBlackAdjustment.getAdjustmentR());
		blackAdjust.append(colorAdjustment->_rgbBlackAdjustment.getAdjustmentG());
		blackAdjust.append(colorAdjustment->_rgbBlackAdjustment.getAdjustmentB());
		adjustment.insert("black", blackAdjust);

		QJsonArray whiteAdjust;
		whiteAdjust.append(colorAdjustment->_rgbWhiteAdjustment.getAdjustmentR());
		whiteAdjust.append(colorAdjustment->_rgbWhiteAdjustment.getAdjustmentG());
		whiteAdjust.append(colorAdjustment->_rgbWhiteAdjustment.getAdjustmentB());
		adjustment.insert("white", whiteAdjust);

		QJsonArray redAdjust;
		redAdjust.append(colorAdjustment->_rgbRedAdjustment.getAdjustmentR());
		redAdjust.append(colorAdjustment->_rgbRedAdjustment.getAdjustmentG());
		redAdjust.append(colorAdjustment->_rgbRedAdjustment.getAdjustmentB());
		adjustment.insert("red", redAdjust);

		QJsonArray greenAdjust;
		greenAdjust.append(colorAdjustment->_rgbGreenAdjustment.getAdjustmentR());
		greenAdjust.append(colorAdjustment->_rgbGreenAdjustment.getAdjustmentG());
		greenAdjust.append(colorAdjustment->_rgbGreenAdjustment.getAdjustmentB());
		adjustment.insert("green", greenAdjust);

		QJsonArray blueAdjust;
		blueAdjust.append(colorAdjustment->_rgbBlueAdjustment.getAdjustmentR());
		blueAdjust.append(colorAdjustment->_rgbBlueAdjustment.getAdjustmentG());
		blueAdjust.append(colorAdjustment->_rgbBlueAdjustment.getAdjustmentB());
		adjustment.insert("blue", blueAdjust);

		QJsonArray cyanAdjust;
		cyanAdjust.append(colorAdjustment->_rgbCyanAdjustment.getAdjustmentR());
		cyanAdjust.append(colorAdjustment->_rgbCyanAdjustment.getAdjustmentG());
		cyanAdjust.append(colorAdjustment->_rgbCyanAdjustment.getAdjustmentB());
		adjustment.insert("cyan", cyanAdjust);

		QJsonArray magentaAdjust;
		magentaAdjust.append(colorAdjustment->_rgbMagentaAdjustment.getAdjustmentR());
		magentaAdjust.append(colorAdjustment->_rgbMagentaAdjustment.getAdjustmentG());
		magentaAdjust.append(colorAdjustment->_rgbMagentaAdjustment.getAdjustmentB());
		adjustment.insert("magenta", magentaAdjust);

		QJsonArray yellowAdjust;
		yellowAdjust.append(colorAdjustment->_rgbYellowAdjustment.getAdjustmentR());
		yellowAdjust.append(colorAdjustment->_rgbYellowAdjustment.getAdjustmentG());
		yellowAdjust.append(colorAdjustment->_rgbYellowAdjustment.getAdjustmentB());
		adjustment.insert("yellow", yellowAdjust);

		adjustment["backlightThreshold"] = colorAdjustment->_rgbTransform.getBacklightThreshold();
		adjustment["backlightColored"]   = colorAdjustment->_rgbTransform.getBacklightColored();
		adjustment["brightness"] = colorAdjustment->_rgbTransform.getBrightness();
		adjustment["brightnessCompensation"] = colorAdjustment->_rgbTransform.getBrightnessCompensation();
		adjustment["gammaRed"]   = colorAdjustment->_rgbTransform.getGammaR();
		adjustment["gammaGreen"] = colorAdjustment->_rgbTransform.getGammaG();
		adjustment["gammaBlue"]  = colorAdjustment->_rgbTransform.getGammaB();

		adjustmentArray.append(adjustment);
	}

	info["adjustment"] = adjustmentArray;

	// collect effect info
	QJsonArray effects;
	const std::list<EffectDefinition> & effectsDefinitions = _hyperion->getEffects();
	for (const EffectDefinition & effectDefinition : effectsDefinitions)
	{
		QJsonObject effect;
		effect["name"] = effectDefinition.name;
		effect["file"] = effectDefinition.file;
		effect["script"] = effectDefinition.script;
		effect["args"] = effectDefinition.args;
		effects.append(effect);
	}

	info["effects"] = effects;

	// get available led devices
	QJsonObject ledDevices;
	ledDevices["active"] = LedDevice::activeDevice();
	QJsonArray availableLedDevices;
	for (auto dev: LedDevice::getDeviceMap())
	{
		availableLedDevices.append(dev.first);
	}

	ledDevices["available"] = availableLedDevices;
	info["ledDevices"] = ledDevices;

	QJsonObject grabbers;
	QJsonArray availableGrabbers;
#if defined(ENABLE_DISPMANX) || defined(ENABLE_V4L2) || defined(ENABLE_FB) || defined(ENABLE_AMLOGIC) || defined(ENABLE_OSX) || defined(ENABLE_X11)
	// get available grabbers
	//grabbers["active"] = ????;
	for (auto grabber: GrabberWrapper::availableGrabbers())
	{
		availableGrabbers.append(grabber);
	}
#endif
	grabbers["available"] = availableGrabbers;
	grabbers["videomode"] = QString(videoMode2String(_hyperion->getCurrentVideoMode()));
	info["grabbers"]      = grabbers;

	// get available components
	QJsonArray component;
	std::map<hyperion::Components, bool> components = _hyperion->getComponentRegister().getRegister();
	for(auto comp : components)
	{
		QJsonObject item;
		item["name"] = QString::fromStdString(hyperion::componentToIdString(comp.first));
		item["enabled"] = comp.second;

		component.append(item);
	}

	info["components"] = component;
	info["ledMAppingType"] = ImageProcessor::mappingTypeToStr(_hyperion->getLedMappingType());

	// Add Hyperion
	QJsonObject hyperion;
	hyperion["config_modified" ] = _hyperion->configModified();
	hyperion["config_writeable"] = _hyperion->configWriteable();
	hyperion["off"] = hyperionIsActive()? false : true;

	// sessions
	QJsonArray sessions;
	for (auto session: _hyperion->getHyperionSessions())
	{
		if (session.port<0) continue;
		QJsonObject item;
		item["name"]   = session.serviceName;
		item["type"]   = session.registeredType;
		item["domain"] = session.replyDomain;
		item["host"]   = session.hostName;
		item["address"]= session.address;
		item["port"]   = session.port;
		sessions.append(item);
	}
	hyperion["sessions"] = sessions;

	info["hyperion"] = hyperion;

	// send the result
	result["info"] = info;
	emit callbackMessage(result);
}
Example #16
0
void NodeAsset::addPixmapEntry(const QJsonObject& entry) {
    for (const QString &key : entry.keys()) {
        QJsonArray qualityArray = entry.value(key).toArray();
        for (const QJsonValue &val : qualityArray) {
            const QJsonObject qualityObject = val.toObject();
            const QString file = qualityObject.value("filename").toString();

            if (!_nodeAssetPixmapHash.contains(file)) {
                QPixmap pixmap(":/assets/" + file);
                _nodeAssetPixmapHash.insert(file, pixmap);
            }

            QJsonObject coords = qualityObject.value("coords").toObject();
            for (const QString &fileEntryKey : coords.keys()) {
                const QJsonObject fileEntryObject = coords.value(fileEntryKey).toObject();

                NodeAsset* asset = _nodeAssetHash.value(fileEntryKey, nullptr);
                if (asset == nullptr) {
                    asset = new NodeAsset;
                    asset->_file = file;
                    _nodeAssetHash.insert(fileEntryKey, asset);
                }

                QPair<QString, QRect> data;
                data.first = file;
                data.second = QRect(fileEntryObject.value("x").toInt(),
                             fileEntryObject.value("y").toInt(),
                             fileEntryObject.value("w").toInt(),
                             fileEntryObject.value("h").toInt());
                asset->_coords.insert(key, data);
            }
        }
    }
}
Example #17
0
void JsonProcessor::handleSchemaGetCommand(const QJsonObject& message, const QString& command, const int tan)
{
	// create result
	QJsonObject result, schemaJson, alldevices, properties;
	result["success"] = true;
	result["command"] = command;
	result["tan"] = tan;

	// make sure the resources are loaded (they may be left out after static linking)
	Q_INIT_RESOURCE(resource);

	// read the hyperion json schema from the resource
	QString schemaFile = ":/hyperion-schema";

	try
	{
		schemaJson = QJsonFactory::readSchema(schemaFile);
	}
	catch(const std::runtime_error& error)
	{
		throw std::runtime_error(error.what());
	}

	// collect all LED Devices
	properties = schemaJson["properties"].toObject();
	alldevices = LedDevice::getLedDeviceSchemas();
	properties.insert("alldevices", alldevices);

	// collect all available effect schemas
	QJsonObject pyEffectSchemas, pyEffectSchema;
	QJsonArray in, ex;
	const std::list<EffectSchema> & effectsSchemas = _hyperion->getEffectSchemas();
	for (const EffectSchema & effectSchema : effectsSchemas)
	{
		if (effectSchema.pyFile.mid(0, 1)  == ":")
		{
			QJsonObject internal;
			internal.insert("script", effectSchema.pyFile);
			internal.insert("schemaLocation", effectSchema.schemaFile);
			internal.insert("schemaContent", effectSchema.pySchema);
			in.append(internal);
		}
		else
		{
			QJsonObject external;
			external.insert("script", effectSchema.pyFile);
			external.insert("schemaLocation", effectSchema.schemaFile);
			external.insert("schemaContent", effectSchema.pySchema);
			ex.append(external);
		}
	}

	if (!in.empty())
		pyEffectSchema.insert("internal", in);
	if (!ex.empty())
		pyEffectSchema.insert("external", ex);

	pyEffectSchemas = pyEffectSchema;
	properties.insert("effectSchemas", pyEffectSchemas);

	schemaJson.insert("properties", properties);

	result["result"] = schemaJson;

	// send the result
	emit callbackMessage(result);
}
Example #18
0
Node::Node(const QJsonObject& source, bool root)
    : _flags(root ? Root : None)
    , _active(false) {
    _id         = source.value("id").toInt();
    _group      = source.value("g").toInt();
    _orbit      = source.value("o").toInt();
    _orbitIndex = source.value("oidx").toInt();

    if (source.value("not").toBool())
        _flags = _flags | Notable;

    if (source.value("ks").toBool())
        _flags = _flags | KeyStone;

    if (source.value("m").toBool())
        _flags = _flags | Mastery;

    if (source.value("isJewelSocket").toBool())
        _flags = _flags | JewelSocket;

    if (source.value("isAscendancyStart").toBool())
        _flags = _flags | AscendancyRoot;

    if (source.value("isMultipleChoice").toBool())
        _flags = _flags | MultiChoiceRoot;

    if (source.value("isMultipleChoiceOption").toBool())
        _flags = _flags | MultiChoiceOption;

    _name       = source.value("dn").toString();
    _icon       = source.value("icon").toString();
    _ascendancy = source.value("ascendancyName").toString();
    _detail     = source.value("sd").toVariant().toStringList();

    _grantedPassivePoints   = source.value("passivePointsGranted").toInt();
    _grantedStrength        = source.value("sa").toInt();
    _grantedIntelligence    = source.value("ia").toInt();
    _grantedDexterity       = source.value("da").toInt();

    auto outNodesArray = source.value("out").toArray();
    for (const QJsonValue &val : outNodesArray) {
        _outNodes << val.toInt();
    }

    if (hasNodeFlag(AscendancyRoot)) {
        setZValue(1.0f);
        _pixmap = QPixmap(":/static/PassiveSkillScreenAscendancyMiddle.png");
    }
    else {
        setZValue(2.0f);

        NodeAsset* asset = NodeAsset::getAsset(_icon);
        if (asset) {
            _pixmap = asset->getPixmap(this);

            if (!hasNodeFlag(Mastery)) {
                QPixmap frame;
                if (hasNodeFlag(Notable)) {
                    frame = QPixmap(_ascendancy.isEmpty() ? ":/static/NotableFrameUnallocated.png" : ":/static/PassiveSkillScreenAscendancyFrameLargeNormal.png");
                }
                else if (hasNodeFlag(KeyStone)) {
                    frame = QPixmap(":/static/KeystoneFrameUnallocated.png");
                }
                else if (hasNodeFlag(JewelSocket)) {
                    frame = QPixmap(":/static/JewelFrameUnallocated.png");
                }
                else {
                    frame = QPixmap(_ascendancy.isEmpty() ? ":/static/Skill_Frame_Unallocated.png" : ":/static/PassiveSkillScreenAscendancyFrameSmallNormal.png");
                }
                QPixmap result(frame.width(), frame.height());
                result.fill(Qt::transparent);
                QPainter painter(&result);
                painter.drawPixmap((frame.width() / 2) - (_pixmap.width() / 2),
                                   (frame.height() / 2) - (_pixmap.height() / 2),
                                   _pixmap);
                painter.drawPixmap(frame.rect(), frame);
                _pixmap = result;
            }
        }
        else {
            qDebug() << "Failed to find asset for " << _icon;
        }
    }
}
Example #19
0
/**
 * @return name of the associated service
 */
QString KoDocumentEntry::name() const {
    QJsonObject json = metaData();
    json = json.value("KPlugin").toObject();
    return json.value("Name").toString();
}
QJsonObject*
SWGLimeSdrOutputReport::asJsonObject() {
    QJsonObject* obj = new QJsonObject();
    if(m_success_isSet){
        obj->insert("success", QJsonValue(success));
    }
    if(m_stream_active_isSet){
        obj->insert("streamActive", QJsonValue(stream_active));
    }
    if(m_fifo_size_isSet){
        obj->insert("fifoSize", QJsonValue(fifo_size));
    }
    if(m_fifo_fill_isSet){
        obj->insert("fifoFill", QJsonValue(fifo_fill));
    }
    if(m_underrun_count_isSet){
        obj->insert("underrunCount", QJsonValue(underrun_count));
    }
    if(m_overrun_count_isSet){
        obj->insert("overrunCount", QJsonValue(overrun_count));
    }
    if(m_dropped_packets_count_isSet){
        obj->insert("droppedPacketsCount", QJsonValue(dropped_packets_count));
    }
    if(m_link_rate_isSet){
        obj->insert("linkRate", QJsonValue(link_rate));
    }
    if(m_hw_timestamp_isSet){
        obj->insert("hwTimestamp", QJsonValue(hw_timestamp));
    }
    if(m_temperature_isSet){
        obj->insert("temperature", QJsonValue(temperature));
    }
    if(m_gpio_dir_isSet){
        obj->insert("gpioDir", QJsonValue(gpio_dir));
    }
    if(m_gpio_pins_isSet){
        obj->insert("gpioPins", QJsonValue(gpio_pins));
    }

    return obj;
}
Example #21
0
bool MedNUSStoryManager::loadStoryFile(QString storyFile)
{
    QString dir = QDir::homePath();
    dir.append(storyFile);

    QFile file(dir);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qWarning() << "Unable to open file.";
        return false;
    }

    QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
    QJsonObject obj = doc.object();
    QJsonValue jsonValue = obj.value(QString("videoFile"));
    videoFileName = jsonValue.toString();

    jsonValue = obj.value(QString("3DFile"));
    modelFileName = jsonValue.toString();

    jsonValue = obj.value(QString("PDFFile"));
    pdfFileName = jsonValue.toString();

    jsonValue = obj.value(QString("timeline"));
    QJsonArray timelineDetails = jsonValue.toArray();

    for(int i = 0; i < timelineDetails.size(); i++)
    {
        obj = timelineDetails[i].toObject();

        StoryPoint temp;
        temp.timestamp = qint64(obj.value(QString("timestamp")).toString().toLongLong());
        temp.slideNum = obj.value(QString("slide")).toInt();

        QJsonArray posArray = obj.value(QString("cameraPosition")).toArray();
        QJsonArray focArray = obj.value(QString("cameraFocalPoint")).toArray();
        QJsonArray vupArray = obj.value(QString("cameraViewUp")).toArray();
        for(int i = 0; i<3; i++)
        {
            temp.cameraPosition[i] =  posArray[i].toDouble();
            temp.cameraFocalPoint[i] = focArray[i].toDouble();
            temp.cameraViewUp[i] = vupArray[i].toDouble();
        }

        temp.cameraViewAngle = obj.value(QString("cameraViewAngle")).toInt();
        storyPointList->push_back(temp);
    }

    return true;
}
Example #22
0
void MainWindow::LoadJSON(QString fileName)
{
    QFile jsonFile(fileName);

    if(!jsonFile.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        ui->statusBar->showMessage("Could not open file: " + fileName);
        return;
    }

    QByteArray rawJson = jsonFile.readAll();

    ui->textEdit->setText(QString(rawJson));

    QJsonParseError error;

    doc = new QJsonDocument(QJsonDocument::fromJson(rawJson, &error));

    if(error.error != QJsonParseError::NoError)
    {
        ui->statusBar->showMessage("Failed to parse file: " + error.errorString());
        delete doc;
        doc = NULL;
        return;
    }

    /*
    QJsonObject root = doc->object();
    for(QJsonObject::ConstIterator i = root.begin(); i != root.end(); ++i)
    {
        QTreeWidgetItem *toAdd = new QTreeWidgetItem();
        toAdd->setText(0, i.key());
        ui->treeWidget->addTopLevelItem(toAdd);
    }
    */

    QTreeWidgetItem *root = new QTreeWidgetItem();
    QString rootId = "root";
    QJsonValue rootVal;

    if(doc->isArray())
    {
        QJsonArray array = doc->array();
        rootVal = QJsonValue(array);
        int count = array.count();
        rootId += "["+QString::number(count)+"]";

        for(int i = 0; i < count; ++i)
        {
            QJsonValue val = array.at(i);
            buildJsonTree(root, val, QString::number(i)+" : ");
        }
    }
    else if(doc->isObject())
    {
        QJsonObject object = doc->object();
        rootVal = QJsonValue(object);
        rootId += "{"+QString::number(object.count())+"}";

        for(QJsonObject::ConstIterator i = object.begin(); i != object.end(); ++i)
        {
            QJsonValue val = i.value();
            buildJsonTree(root, val, i.key()+" : ");
        }
    }
    else
    {
        rootId = "Null or Undefined root object";
        return;
    }

    root->setText(0, rootId);
    root->setData(0, Qt::UserRole, QVariant(rootVal));
    ui->treeWidget->addTopLevelItem(root);
    ui->treeWidget->setCurrentItem(root);
}
Example #23
0
void ServiceClient::cLstReplRead(QNetworkReply* repl) {
    QJsonDocument json = QJsonDocument::fromJson(repl->readAll());
    repl->deleteLater();
    sender()->deleteLater();

    Response r;
    CourseSummaryList* summaries = new CourseSummaryList();
    if(!json.isArray()) {
        r.Status = 500;
        emit GetCourseListFinished(summaries, r);
        return;
    }
    QJsonArray jArrCLst = json.array();
    QJsonValue val, field;
    QJsonObject obj;
    for(int i=0; i < jArrCLst.size(); i++) {
        val = jArrCLst[i];
        if(!val.isObject()) {
            continue;
        }
        obj = val.toObject();
        CourseSummary summary;
        field = obj.value("course_id");
        if(!field.isUndefined()) {
            summary.course_id = field.toString();
        }

        field = obj.value("credits");
        if(!field.isUndefined()) {
            summary.credits = field.toString();
        }

        field = obj.value("description");
        if(!field.isUndefined()) {
            summary.description = field.toString();
        }

        field = obj.value("percent");
        if(!field.isUndefined()) {
            summary.percent = field.toString();
        }

        field = obj.value("subject");
        if(!field.isUndefined()) {
            summary.subject = field.toString();
        }

        field = obj.value("term");
        if(!field.isUndefined()) {
            summary.term = field.toString();
        }

        field = obj.value("year");
        if(!field.isUndefined()) {
            summary.year = field.toString();
        }

        field = obj.value("lecturer");
        if(!field.isUndefined()) {
            summary.lecturer = field.toString();
        }
        summaries->append(summary);
    }


//    for(int i=0; i<30;i++){
//        CourseSummary summary;
//        summary.course_id = "1231231231";
//        summary.credits = "2";
//        summary.description = "qwejkwhqe 12312";
//        summary.percent = "20";
//        summary.subject = "tin hoc dai cuong";
//        summary.term = "2";
//        summary.year = "2013";
//        summary.lecturer ="ng v a";
//        summaries->append(summary);
//    }

    emit GetCourseListFinished(summaries, r);
}
Example #24
0
WorldInfo::WallInfo::WallInfo(quint16 id, const QJsonObject &json) {
  name = json["name"].toString();
  color = json.contains("color") ? readColor(json["color"].toString()) : 0;
  blend = json["blend"].toInt(id);
}
Example #25
0
bool TMailAgent::getMailContact()
{

   if (!authIndicator)
   {
    if (!authenAgent())
        FUNC_ABORT ("Authentification not sucuess");

   }

   url = "https://e.mail.ru/addressbook";
    request.setUrl(url);
    request.setRawHeader("User-Agent","Mozilla/5.0 (Windows NT 5.1) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.46 Safari/536.5");
    startRequest(getRequest, requestString );

   QRegExp regexjsonContact("\\{\"body\"\\:\\{\"contacts\"\\:(.)+\"status\"\\:\\d+\\}");

   QString jsonParseString;
   QStringList listEmailContacts;
   QStringList listNick;
   QStringList listDisplayName;
   QStringList listId;
   QStringList listPhones;
   QStringList listFio;

    if (regexjsonContact.indexIn(lastResponsAgentRequest) == -1)
          FUNC_ABORT("regex for contact not work");

    jsonParseString = regexjsonContact.cap(0);
    QJsonDocument jsonResponse = QJsonDocument::fromJson(jsonParseString.toUtf8());
    QJsonObject jsonObject = jsonResponse.object();
    QJsonObject jsonObjectContacts = jsonObject["body"].toObject();

    QJsonArray jsonArray = jsonObjectContacts["contacts"].toArray();
    qDebug() << jsonArray;

    foreach (const QJsonValue & value, jsonArray)
            {
                QJsonObject obj = value.toObject();

                //---------получение данных поля emails---------------------------------//
                QJsonArray jsonArrayEmail = obj["emails"].toArray();
                QString emails;
                    foreach (const QJsonValue & valueEmail, jsonArrayEmail)
                            emails.append(valueEmail.toString() + " ; ");
                listEmailContacts << emails;

                //---------получение данных поля name---------------------------------------//
               QString fio;
                QJsonObject jsonObjName = obj["name"].toObject();
               fio.append(jsonObjName.value("first").toString() + " ");
                fio.append(jsonObjName.value("last").toString());
                listFio << fio;


                //---------получение данных поля phone---------------------------------------//
                QString phone;
                QJsonArray jsonArrayPhones = obj["phones"].toArray();
                 foreach (const QJsonValue & valuePhone,  jsonArrayPhones)
                 {
                     QJsonObject obj = valuePhone.toObject();
                      phone.append(obj.value("phone").toString() + " ; ");

                 }
void MusicRadioSongsThread::downLoadFinished()
{
    if(m_reply == nullptr)
    {
        deleteAll();
        return;
    }

    if(m_reply->error() == QNetworkReply::NoError)
    {
        QByteArray bytes = m_reply->readAll();
#ifdef MUSIC_QT_5
        QJsonParseError jsonError;
        QJsonDocument parseDoucment = QJsonDocument::fromJson(bytes, &jsonError);
        ///Put the data into Json
        if(jsonError.error != QJsonParseError::NoError ||
           !parseDoucment.isObject())
        {
            deleteAll();
            return ;
        }

        QJsonObject jsonObject = parseDoucment.object();
        if(jsonObject.contains("data"))
        {
            jsonObject = jsonObject.value("data").toObject();
            if(jsonObject.contains("songList"))
            {
                QJsonArray array = jsonObject.value("songList").toArray();
                foreach(QJsonValue value, array)
                {
                    if(!value.isObject())
                    {
                       continue;
                    }
                    QJsonObject object = value.toObject();

                    m_songInfo.m_songUrl = object.value("songLink").toString();
                    m_songInfo.m_songName = object.value("songName").toString();
                    m_songInfo.m_artistName = object.value("artistName").toString();
                    m_songInfo.m_songPicUrl = object.value("songPicRadio").toString();
                    m_songInfo.m_albumName = object.value("albumName").toString();
                    QString lrcLink = object.value("lrcLink").toString();
                    if(!lrcLink.contains( LRC_PREFIX ))
                    {
                        lrcLink = LRC_PREFIX + lrcLink;
                    }
                    m_songInfo.m_lrcUrl = lrcLink;
                }
            }
Example #27
0
bool KNAccount::setAvatar(const QPixmap &avatarImage)
{
    //Check out the avatar image size.
    if(avatarImage.width()>100 || avatarImage.height()>100 ||
            (!m_accountDetails->isLogin()))
    {
        //Failed to update the avatar.
        emit avatarUpdatedFailed();
        //Rescaled the image before uploading.
        return false;
    }
    //Check whether it contains image before.
    if(!m_accountDetails->avatarPath().isEmpty())
    {
        //Generate the result.
        QNetworkRequest request=generateKreogistRequest(
                                    "files/"+m_accountDetails->avatarPath());
        //Check the avatar path, if it's starts with http, then we will use the
        //new API to remove the previous image.
        if(m_accountDetails->avatarPath().startsWith("http"))
        {
            //Save the avatar data.
            const QJsonObject &avatarData=m_accountDetails->avatarData();
            //Combine the remove URL.
            QString fileUrl=avatarData.value("url").toString();
            //Reset the url.
            request.setUrl("https://api.bmob.cn/2/files/" +
                           avatarData.value("cdn").toString() +
                           fileUrl.mid(fileUrl.indexOf('/', 8)));
        }
        //Delete the resource.
        int removeResult=deleteResource(request, false);
        //If the avatar is already deleted(404), nor remove it successfully
        //(200) there should be an Ineternet connection error.
        if(removeResult!=200 && removeResult!=404)
        {
            //Emit the failed connection signal.
            emit updateInternetError();
            //Failed to upload the image.
            return false;
        }
    }
    //Generate image cache.
    QByteArray imageBytes, responseBytes;
    {
        //Generate the buffer.
        QBuffer imageBuffer(&imageBytes);
        //Open the buffer.
        if(!imageBuffer.open(QIODevice::WriteOnly))
        {
            //Failed to update the avatar.
            emit avatarUpdatedFailed();
            //Failed to save image.
            return false;
        }
        //Save the pixamp.
        avatarImage.save(&imageBuffer, "JPG");
        //Close buffer.
        imageBuffer.close();
    }
    //Upload the account data.
    QNetworkRequest avatarRequest=generateKreogistRequest("");
    //Set the url.
    avatarRequest.setUrl("https://api.bmob.cn/2/files/" +
                         m_accountDetails->objectId() + "/avatar.jpg");
    //Configure the image.
    avatarRequest.setHeader(QNetworkRequest::ContentTypeHeader, "image/jpeg");
    //Post the request.
    int postResult=post(avatarRequest, imageBytes, responseBytes, false);
    //Check Internet connection first.
    if(postResult<0)
    {
        //Emit the failed connection signal.
        emit updateInternetError();
        //Failed to upload the image.
        return false;
    }
    //Check post result.
    else if(postResult!=200)
    {
        //Failed to update the avatar.
        emit avatarUpdatedFailed();
        //Failed to upload the image.
        return false;
    }
    //Check the response data.
    QJsonObject updateObject;
    //Update account details.
    updateObject.insert("avatarPath", QString(responseBytes));
    //Send update request.
    if(updateOnlineAccount(updateObject, false))
    {
        //Update the avatar successfully.
        emit avatarUpdatedSuccess();
        //Set the data to detail info.
        m_accountDetails->setAvatarPath(responseBytes);
        return true;
    }
    //Else is failed.
    emit avatarUpdatedFailed();
    //Mission failed.
    return false;
}
Example #28
0
void JsonProcessor::handleCreateEffectCommand(const QJsonObject& message, const QString &command, const int tan)
{
	if(message.size() > 0)
	{
		if (!message["args"].toObject().isEmpty())
		{
			QString scriptName;
			(message["script"].toString().mid(0, 1)  == ":" )
				? scriptName = ":/effects//" + message["script"].toString().mid(1)
				: scriptName = message["script"].toString();

			std::list<EffectSchema> effectsSchemas = _hyperion->getEffectSchemas();
			std::list<EffectSchema>::iterator it = std::find_if(effectsSchemas.begin(), effectsSchemas.end(), find_schema(scriptName));

			if (it != effectsSchemas.end())
			{
				QString errors;

				if (!checkJson(message["args"].toObject(), it->schemaFile, errors))
				{
					sendErrorReply("Error while validating json: " + errors, command, tan);
					return;
				}

				QJsonObject effectJson;
				QJsonArray effectArray;
				effectArray = _hyperion->getQJsonConfig()["effects"].toObject()["paths"].toArray();

				if (effectArray.size() > 0)
				{
					if (message["name"].toString().trimmed().isEmpty() || message["name"].toString().trimmed().startsWith("."))
					{
						sendErrorReply("Can't save new effect. Effect name is empty or begins with a dot.", command, tan);
						return;
					}

					effectJson["name"] = message["name"].toString();
					effectJson["script"] = message["script"].toString();
					effectJson["args"] = message["args"].toObject();

					std::list<EffectDefinition> availableEffects = _hyperion->getEffects();
					std::list<EffectDefinition>::iterator iter = std::find_if(availableEffects.begin(), availableEffects.end(), find_effect(message["name"].toString()));

					QFileInfo newFileName;
					if (iter != availableEffects.end())
					{
						newFileName.setFile(iter->file);
						if (newFileName.absoluteFilePath().mid(0, 1)  == ":")
						{
							sendErrorReply("The effect name '" + message["name"].toString() + "' is assigned to an internal effect. Please rename your effekt.", command, tan);
							return;
						}
					} else
					{
						newFileName.setFile(effectArray[0].toString() + QDir::separator() + message["name"].toString().replace(QString(" "), QString("")) + QString(".json"));

						while(newFileName.exists())
						{
							newFileName.setFile(effectArray[0].toString() + QDir::separator() + newFileName.baseName() + QString::number(qrand() % ((10) - 0) + 0) + QString(".json"));
						}
					}

					QJsonFactory::writeJson(newFileName.absoluteFilePath(), effectJson);
					Info(_log, "Reload effect list");
					_hyperion->reloadEffects();
					sendSuccessReply(command, tan);
				} else
				{
					sendErrorReply("Can't save new effect. Effect path empty", command, tan);
					return;
				}
			} else
				sendErrorReply("Missing schema file for Python script " + message["script"].toString(), command, tan);
		} else
			sendErrorReply("Missing or empty Object 'args'", command, tan);
	} else
		sendErrorReply("Error while parsing json: Message size " + QString(message.size()), command, tan);
}
Example #29
0
void BSClient::replySeriesFinished()
{
    qDebug() << "BSClient::replySeriesFinished()";

    QByteArray byteArray = m_reply->readAll();

    if(isCaptcha(byteArray))
    {
        loadSeries();
        return;
    }

    QJsonDocument document = QJsonDocument::fromJson(byteArray);

    if(!document.isArray())
    {
        Q_EMIT error(tr("JSON-Parse-Fehler: 0x0001"));
        return;
    }

    QList<QPair<QString, QString> > series;

    QJsonArray array = document.array();

    Q_FOREACH(const QJsonValue &value, array)
    {
        if(!value.isObject())
        {
            Q_EMIT error(tr("JSON-Parse-Fehler: 0x0002"));
            return;
        }

        QJsonObject object = value.toObject();

        if(!object.contains("id"))
        {
            Q_EMIT error(tr("JSON-Parse-Fehler: 0x0003"));
            return;
        }

        QJsonValue idValue = object.value("id");

        if(!idValue.isString())
        {
            Q_EMIT error(tr("JSON-Parse-Fehler: 0x0004"));
            return;
        }

        if(!object.contains("series"))
        {
            Q_EMIT error(tr("JSON-Parse-Fehler: 0x0005"));
            return;
        }

        QJsonValue seriesValue = object.value("series");

        if(!seriesValue.isString())
        {
            Q_EMIT error(tr("JSON-Parse-Fehler: 0x0006"));
            return;
        }

        series << qMakePair(idValue.toString(), seriesValue.toString());
    }

    Q_EMIT loadSeriesFinished(series);
}
void UpdateChecker::readUpdateData(const QByteArray &data)
{
	const QStringList activeChannels = SettingsManager::getValue(QLatin1String("Updates/ActiveChannels")).toStringList();
	const QJsonObject updateData = QJsonDocument::fromJson(data).object();
	const QJsonArray channels = updateData.value(QLatin1String("channels")).toArray();
	int mainVersion = QCoreApplication::applicationVersion().remove(QChar('.')).toInt();
	int subVersion = QString(OTTER_VERSION_WEEKLY).toInt();
	QString availableVersion;
	QString availableChannel;

	for (int i = 0; i < channels.count(); ++i)
	{
		if (channels.at(i).isObject())
		{
			const QJsonObject object = channels.at(i).toObject();
			const QString identifier = object["identifier"].toString();
			const QString channelVersion = object["version"].toString();

			if (activeChannels.contains(identifier, Qt::CaseInsensitive))
			{
				const int channelMainVersion = channelVersion.trimmed().remove(QChar('.')).toInt();

				if (channelMainVersion == 0)
				{
					Console::addMessage(QCoreApplication::translate("main", "Unable to parse version number: %1").arg(channelVersion), OtherMessageCategory, ErrorMessageLevel);

					continue;
				}

				const int channelSubVersion = object["subVersion"].toString().toInt();

				if ((mainVersion < channelMainVersion) || (channelSubVersion > 0 && subVersion < channelSubVersion))
				{
					mainVersion = channelMainVersion;
					subVersion = channelSubVersion;
					availableVersion = channelVersion;
					availableChannel = identifier;
					m_detailsUrl = object["detailsUrl"].toString();
				}
			}
		}
	}

	SettingsManager::setValue(QLatin1String("Updates/LastCheck"), QDate::currentDate().toString(Qt::ISODate));

	if (!availableVersion.isEmpty())
	{
		const QString text = tr("New update %1 from %2 channel is available!").arg(availableVersion).arg(availableChannel);

		if (m_showDialog)
		{
			QMessageBox messageBox;
			messageBox.setWindowTitle(tr("New version of Otter Browser is available"));
			messageBox.setText(text);
			messageBox.setInformativeText(tr("Do you want to open a new tab with download page?"));
			messageBox.setIcon(QMessageBox::Question);
			messageBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
			messageBox.setDefaultButton(QMessageBox::No);

			if (messageBox.exec() == QMessageBox::Yes)
			{
				runUpdate();
			}
			else
			{
				deleteLater();
			}
		}
		else
		{
			Notification *updateNotification = NotificationsManager::createNotification(NotificationsManager::UpdateAvailableEvent, text);

			connect(updateNotification, SIGNAL(clicked()), this, SLOT(runUpdate()));
			connect(updateNotification, SIGNAL(ignored()), this, SLOT(deleteLater()));
		}
	}
	else
	{ 
		deleteLater();
	}
}