static Nuria::JsonMetaObjectReader::Error parseMethodArgumentList (const QJsonArray &names, const QJsonArray &types,
								   QVector< QByteArray > &outNames,
								   QVector< QByteArray > &outTypes) {
	if (names.size () != types.size ()) {
		return Nuria::JsonMetaObjectReader::MethodArgumentsHaveDifferentLengths;
	}
	
	// 
	for (int i = 0; i < names.size (); i++) {
		QJsonValue curName = names.at (i);
		QJsonValue curType = types.at (i);
		
		if (!curName.isString ()) return Nuria::JsonMetaObjectReader::MethodArgumentNamesContainsNonString;
		if (!curType.isString ()) return Nuria::JsonMetaObjectReader::MethodArgumentTypesContainsNonString;
		
		// 
		outNames.append (curName.toString ().toLatin1 ());
		outTypes.append (curType.toString ().toLatin1 ());
		
	}
	
	// 
	return Nuria::JsonMetaObjectReader::NoError;
	
}
bool TestClusterModel::loadFromFile(const QString& fileName) {
    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        return false;
    }
    QByteArray bytes = file.readAll();
    file.close();
    QJsonParseError parseError;
    QJsonDocument doc = QJsonDocument::fromJson(bytes, &parseError);
    if (parseError.error != QJsonParseError::NoError) {
        return false;
    }
    if (!doc.isArray()) {
        return false;
    }
    QList<HostInfo> newHosts;
    QJsonArray array = doc.array();
    for (const QJsonValue& value : array) {
        HostInfo info;
        QJsonObject object = value.toObject();
        QJsonValue typeVal = object["type"];
        if (!typeVal.isString()) {
            return false;
        }
        int type = findHostTypeByInternalName(typeVal.toString().toUtf8().data());
        if (type < 0) {
            return false;
        }
        info.type = (HostType)type;
        QJsonValue portVal = object["port"];
        if (!portVal.isDouble()) {
            return false;
        }
        info.port = static_cast<int>(portVal.toDouble());
        QJsonValue dbPathVal = object["dbPath"];
        if (dbPathVal.isString()) {
            info.dbPath = dbPathVal.toString();
        }
        QJsonValue replicaSetVal = object["replicaSet"];
        if (replicaSetVal.isString()) {
            info.replicaSet = replicaSetVal.toString();
        }
        QJsonValue configDBVal = object["configDB"];
        if (configDBVal.isString()) {
            info.configDB = configDBVal.toString();
        }
        newHosts.append(info);
    }
    for (HostInfo& info : newHosts) {
        info.process = new QProcess(this);
        info.state = QProcess::NotRunning;
    }
    beginInsertRows(QModelIndex(), 0, newHosts.size() - 1);
    _hosts = newHosts;
    endInsertRows();
    _fileName = fileName;
    _dirty = false;
    return true;
}
bool feedBackMessage::loadfromJson(QByteArray textJson)
{
    QJsonParseError jsonParseError;
    QJsonDocument jsonDocument = QJsonDocument::fromJson(textJson, &jsonParseError);
    if(jsonParseError.error == QJsonParseError::NoError)
    {
        if(jsonDocument.isObject())
        {

            QJsonObject jsonObject = jsonDocument.object();
            if(jsonObject.contains("username"))
            {
                QJsonValue jsonValue = jsonObject.take("username");
                if(jsonValue.isString())
                {
                    user = jsonValue.toString();
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
            if(jsonObject.contains("status"))
            {
                QJsonValue jsonValue = jsonObject.take("status");
                if(jsonValue.isString())
                {
                    stat = jsonValue.toString();
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }
    else
    {
        return false;
    }
    return true;
}
Beispiel #4
0
Goods *Parser::ParseGoods(const QJsonObject &jGoods) {
    QJsonValue jValue;

    // barcode
    jValue = jGoods.value("barcode");
    if (jValue.isUndefined() || !jValue.isString()) {
        return NULL;
    }
    QString strBarcode = jValue.toString();

    // name
    jValue = jGoods.value("name");
    if (jValue.isUndefined() || !jValue.isString()) {
        return NULL;
    }
    QString strName = jValue.toString();

    // unit
    jValue = jGoods.value("unit");
    if (jValue.isUndefined() || !jValue.isString()) {
        return NULL;
    }
    QString strUnit = jValue.toString();

    // category
    jValue = jGoods.value("category");
    if (jValue.isUndefined() || !jValue.isString()) {
        return NULL;
    }
    QString strCategory = jValue.toString();

    // subCategory
    jValue = jGoods.value("subCategory");
    if (jValue.isUndefined() || !jValue.isString()) {
        return NULL;
    }
    QString strSubCategory = jValue.toString();

    // price
    jValue = jGoods.value("price");
    if (jValue.isUndefined() || !jValue.isDouble()) {
        return NULL;
    }
    float fPrice = (float)jValue.toDouble();

    // new a goods object
    Goods *pGoods = new Goods(strBarcode, strName);
    pGoods->SetCategory(strCategory, strSubCategory);
    pGoods->SetQuantUnit(strUnit);
    pGoods->SetUnitPrice(fPrice);

    return pGoods;
}
Beispiel #5
0
bool BlockInfoData::readMetaData(const QJsonObject &metaData)
{
    QJsonValue value;
    value = metaData.value("IID");
    if (!value.isString()) {
        qWarning() << "Not a plugin (no IID found)";
        return false;
    }

    value = metaData.value("MetaData");
    if (!value.isObject()) {
        qWarning() << "Plugin meta data not found";
        return false;
    }
    QJsonObject pluginInfo = value.toObject();

    value = pluginInfo.value("provides");
    if (!value.isString()) {
        qWarning() << "Plugin doesn't provide anything (check \"provides\" field)";
        return false;
    }
    provides = BlockVersion(value.toString());

    if (!provides.isValid()) {
        qWarning() << "Plugin provides invalid version";
        return false;
    }

    value = pluginInfo.value("provides_compat");
    if (!value.isString()) {
        qWarning() << "Plugin doesn't provide compatibility version "
                      "(check \"provides_compat\" field)";
        return false;
    }
    provides_compat = BlockVersion(value.toString());

    if (!provides_compat.isValid()) {
        qWarning() << "Plugin provides invalid version";
        return false;
    }

    value = pluginInfo.value("needs");
    if (value.isArray()) {
        QJsonArray deps = value.toArray();
        foreach(const QJsonValue &d, deps) {
            if (d.isString()) {
                BlockVersion version(d.toString());
                if (version.isValid())
                    needs.append(version);
            }
        }
    }
BlockOption BlockOption_fromJson(QJsonValue node, bool *ok) {
    bool success = true;
    bool callSuccess;
    QJsonObject nodeObj = node.toObject();
    QJsonValue displayNameVal = nodeObj["displayName"];
    if (!displayNameVal.isString()) {
        success = false;
    }
    QString displayName = displayNameVal.toString();
    QJsonValue defaultValueVal = nodeObj["defaultValue"];
    if (!defaultValueVal.isString()) {
        success = false;
    }
    QString defaultValue = defaultValueVal.toString();
    BlockOptionType type = BlockOptionType_fromJson(nodeObj["type"], &callSuccess);
    if (!callSuccess) {
        success = false;
    }
    BlockOption result;
    QMap<QString, QString> choices;
    QJsonValue minimumVal;
    int minimum;
    QJsonValue maximumVal;
    int maximum;
    switch (type) {
    case BLOCK_OPTION_TYPE_COMBOBOX:
        choices = QMap_QString_QString_fromJson(nodeObj["choices"], &callSuccess);
        if (!callSuccess) {
            success = false;
        }
        result = BlockOption::makeComboBox(displayName, defaultValue, choices);
        break;
    case BLOCK_OPTION_TYPE_INTEGER:
        minimumVal = nodeObj["minimum"];
        if (!minimumVal.isDouble() || (minimumVal.toInt() != minimumVal.toDouble())) {
            success = false;
        }
        minimum = minimumVal.toInt();
        maximumVal = nodeObj["maximum"];
        if (!maximumVal.isDouble() || (maximumVal.toInt() != maximumVal.toDouble())) {
            success = false;
        }
        maximum = maximumVal.toInt();
        result = BlockOption::makeInteger(displayName, defaultValue, minimum, maximum);
        break;
    }
    if (ok) {
        *ok = success;
    }
    return result;
}
Beispiel #7
0
void QPubNub::onSubscribeReadyRead() {
  QNetworkReply * reply = qobject_cast<QNetworkReply*>(sender());
  QJsonArray response;
  if (handleResponse(reply, response)) {
    return;
  }
  QJsonValue firstElement(response.at(0));
  if (!firstElement.isArray()) {
    emit error("First element of response is not an JSON array", 0);
    subscribe();
  }
  
  QJsonValue timeTokenElement = response.at(1);
  if (!timeTokenElement.isString()) {
    emit error("Second element of response is not a string", 0);
    subscribe();
  }
  m_timeToken = timeTokenElement.toString();
  QJsonValue channelListString = response.at(2);
  QStringList channels;
  QJsonArray messages = firstElement.toArray();
  if (channelListString.isString()) {
    channels = channelListString.toString().split(',');
  } else {
    int len = messages.isEmpty() ? 0 : messages.size();
    for (int i = 0; i < len; i++)
    {
        channels << m_channelUrlPart;
    }
  }
  if (messages.isEmpty()) {
    emit connected();
  } else {
#ifdef Q_PUBNUB_CRYPT
    if (m_cipherKey.isEmpty()) {
      for (int i=0,len=messages.size();i<len;++i) {
        emit message(messages[i], m_timeToken, channels[i]);
      }
    } else {
      decrypt(messages, channels);
    }
  #else
    for (int i=0,len=messages.size();i<len;++i) {
      emit message(messages[i], m_timeToken, channels[i]);
    }
#endif // Q_PUBNUB_CRYPT
  }
  subscribe();
}
Beispiel #8
0
bool MessageFacade::obtainRaidAndDataStructure(QJsonObject *root, QString *pRaid, QString *pDataStructure)
{
    QJsonValue jsonValue = root->value(RAID_TYPE);
    bool success = false;
    if (!jsonValue.isUndefined() && jsonValue.isString()){
        *pRaid = jsonValue.toString();
        success = StorageblockFacade::getInstance()->isValidRaid(*pRaid);
    }
    jsonValue = root->value(DATASTRUCTURE_TYPE);
    if (!jsonValue.isUndefined() && jsonValue.isString()){
        *pDataStructure=jsonValue.toString();
        success = success&&StorageblockFacade::getInstance()->isValidDataStructure(*pDataStructure);
    }
    return success;
}
QMap<QString, BlockOption> QMap_QString_BlockOption_fromJson(QJsonValue node, bool *ok) {
    bool success = true;
    bool callSuccess;
    QMap<QString, BlockOption> obj;
    if (!node.isArray()) {
        success = false;
    }
    QJsonArray nodeArr = node.toArray();
    for (auto i = nodeArr.constBegin(); i != nodeArr.constEnd(); i++) {
        QJsonObject item = (*i).toObject();
        QJsonValue keyVal = item["key"];
        if (!keyVal.isString()) {
            success = false;
        }
        QString key = keyVal.toString();
        BlockOption value = BlockOption_fromJson(item["value"], &callSuccess);
        if (!callSuccess) {
            success = false;
        }
        obj.insert(key, value);
    }
    if (ok) {
        *ok = success;
    }
    return obj;
}
void DomainServerSettingsManager::recurseJSONObjectAndOverwriteSettings(const QJsonObject& postedObject,
                                                                        QVariantMap& settingsVariant,
                                                                        QJsonObject descriptionObject) {
    foreach(const QString& key, postedObject.keys()) {

        QJsonValue rootValue = postedObject[key];
        
        // we don't continue if this key is not present in our descriptionObject
        if (descriptionObject.contains(key)) {
            if (rootValue.isString()) {
                settingsVariant[key] = rootValue.toString();
            } else if (rootValue.isBool()) {
                settingsVariant[key] = rootValue.toBool();
            } else if (rootValue.isObject()) {
                // there's a JSON Object to explore, so attempt to recurse into it
                QJsonObject nextDescriptionObject = descriptionObject[key].toObject();
                
                if (nextDescriptionObject.contains(DESCRIPTION_SETTINGS_KEY)) {
                    if (!settingsVariant.contains(key)) {
                        // we don't have a map below this key yet, so set it up now
                        settingsVariant[key] = QVariantMap();
                    }
                    
                    recurseJSONObjectAndOverwriteSettings(rootValue.toObject(),
                                                          *reinterpret_cast<QVariantMap*>(settingsVariant[key].data()),
                                                          nextDescriptionObject[DESCRIPTION_SETTINGS_KEY].toObject());
                }
            }
        }
    }
}
ActionsManager::ActionEntryDefinition ToolBarsManager::decodeEntry(const QJsonValue &value)
{
	ActionsManager::ActionEntryDefinition definition;

	if (value.isString())
	{
		definition.action = value.toString();

		return definition;
	}

	const QJsonObject object(value.toObject());

	definition.action = object.value(QLatin1String("identifier")).toString();
	definition.options = object.value(QLatin1String("options")).toObject().toVariantMap();

	if (object.contains(QLatin1String("actions")))
	{
		const QJsonArray actions(object.value(QLatin1String("actions")).toArray());

		for (int i = 0; i < actions.count(); ++i)
		{
			definition.entries.append(decodeEntry(actions.at(i)));
		}
	}

	return definition;
}
void EnginioBackendConnection::onEnginioFinished(EnginioReply *reply)
{
    struct ReplyScope {
        EnginioReply *_reply;
        ReplyScope(EnginioReply *r) : _reply(r) { }
        ~ReplyScope() { _reply->deleteLater(); }
    } scope(reply);

    if (reply->isError()) {
        qDebug() << "\n\n### EnginioBackendConnection ERROR";
        qDebug() << reply->errorString();
        reply->dumpDebugInfo();
        qDebug() << "\n###\n";
        return;
    }

    QJsonValue urlValue = reply->data()[EnginioString::expiringUrl];

    if (!urlValue.isString()) {
        qDebug() << "## Retrieving connection url failed.";
        return;
    }

    qDebug() << "## Initiating WebSocket connection.";

    _socketUrl = QUrl(urlValue.toString());
    _tcpSocket->connectToHost(_socketUrl.host(), _socketUrl.port(8080));
}
Beispiel #13
0
bool QJsonValueProto::isString() const
{
  QJsonValue *item = qscriptvalue_cast<QJsonValue*>(thisObject());
  if (item)
    return item->isString();
  return false;
}
Beispiel #14
0
void Repository::requestedDataReceived(const QByteArray& data) noexcept {
  QJsonDocument doc = QJsonDocument::fromJson(data);
  if (doc.isNull() || doc.isEmpty() || (!doc.isObject())) {
    emit errorWhileFetchingLibraryList(
        tr("Received JSON object is not valid."));
    return;
  }
  QJsonValue nextResultsLink = doc.object().value("next");
  if (nextResultsLink.isString()) {
    QUrl url = QUrl(nextResultsLink.toString());
    if (url.isValid()) {
      qDebug() << "Request more results from repository:" << url.toString();
      requestLibraryList(url);
    } else {
      qWarning() << "Invalid URL in received JSON object:"
                 << nextResultsLink.toString();
    }
  }
  QJsonValue reposVal = doc.object().value("results");
  if ((reposVal.isNull()) || (!reposVal.isArray())) {
    emit errorWhileFetchingLibraryList(
        tr("Received JSON object does not contain "
           "any results."));
    return;
  }
  emit libraryListReceived(reposVal.toArray());
}
Beispiel #15
0
AnimNode::Pointer AnimNodeLoader::load(const QByteArray& contents, const QUrl& jsonUrl) {

    // convert string into a json doc
    QJsonParseError error;
    auto doc = QJsonDocument::fromJson(contents, &error);
    if (error.error != QJsonParseError::NoError) {
        qCCritical(animation) << "AnimNodeLoader, failed to parse json, error =" << error.errorString();
        return nullptr;
    }
    QJsonObject obj = doc.object();

    // version
    QJsonValue versionVal = obj.value("version");
    if (!versionVal.isString()) {
        qCCritical(animation) << "AnimNodeLoader, bad string \"version\"";
        return nullptr;
    }
    QString version = versionVal.toString();

    // check version
    // AJT: TODO version check
    if (version != "1.0" && version != "1.1") {
        qCCritical(animation) << "AnimNodeLoader, bad version number" << version << "expected \"1.0\"";
        return nullptr;
    }

    // root
    QJsonValue rootVal = obj.value("root");
    if (!rootVal.isObject()) {
        qCCritical(animation) << "AnimNodeLoader, bad object \"root\"";
        return nullptr;
    }

    return loadNode(rootVal.toObject(), jsonUrl);
}
Beispiel #16
0
void MessageFacade::interpretMessage(QString pMessage, ControllerNode *pControllerNode)
{
    mut.lock();
    QJsonObject root;
    // se llama al decifrador
    pMessage = decrypt(pMessage);
    QString messageType;
    //se veridica si cumple con el formato JSON
    if (isValidJsonSyntax(pMessage,&root)){
        //Verifica el tipo de mensaje
        QJsonValue jsonValue = root.value(MESSAGE_TYPE);
        if (!jsonValue.isUndefined() && jsonValue.isString()) {
            messageType = jsonValue.toString();
            //para mensajes de tipo storage block
            if (messageType.compare(MESSAGE_TYPE_STORAGE_BLOCK) == 0){
                interpretStorageBlockMessage(&root,pControllerNode);
            }
            //para mensajes que operen sobre los registros
            else if (messageType.compare(MESSAGE_TYPE_REGISTER) == 0){
                interpretRegisterkMessage(&root,pControllerNode);
            }
            //para mensajes que operen sobre los usarios
            else if (messageType.compare(MESSAGE_TYPE_USER) == 0){
                interpretUserMessage(&root,pControllerNode);
            }
        }
    }
    mut.unlock();

}
static Nuria::JsonMetaObjectReader::Error parseFieldObject (const QString &name, const QJsonObject &field,
							    Nuria::RuntimeMetaObject *metaObject) {
	using namespace Nuria;
	
	QJsonValue annotationsValue = field.value (QStringLiteral("annotations"));
	QJsonValue readOnlyValue = field.value (QStringLiteral("readOnly"));
	QJsonValue typeValue = field.value (QStringLiteral("type"));
	
	// Type check
	if (!annotationsValue.isArray ()) return JsonMetaObjectReader::AnnotationsIsNotAnArray;
	if (!readOnlyValue.isBool ()) return JsonMetaObjectReader::FieldReadOnlyIsNotABoolean;
	if (!typeValue.isString ()) return JsonMetaObjectReader::FieldTypeIsNotAString;
	
	// Parse annotations
	JsonMetaObjectReader::Error error;
	
	RuntimeMetaObject::AnnotationMap annotations;
	error = parseAnnotationsArray (annotationsValue.toArray (), annotations);
	if (error != JsonMetaObjectReader::NoError) return error;
	
	// Store and done.
	QByteArray typeName = typeValue.toString ().toLatin1 ();
	
	if (readOnlyValue.toBool ()) {
		metaObject->addField (name.toLatin1 (), typeName, annotations, invalidGetter);
	} else {
		metaObject->addField (name.toLatin1 (), typeName, annotations, invalidGetter, invalidSetter);
	}
	
	return JsonMetaObjectReader::NoError;
}
Beispiel #18
0
QString JsonObject::string(const QString& key) const {
    checkContains(key);
    QJsonValue value = o.value(key);
    if ( ! value.isString())
        wrongType("string", key);
    return value.toString();
}
Beispiel #19
0
void PosProperty::loadData(const QJsonObject & json)
{
    const QJsonValue v = json["pos"];
    if (v.isString()) {
        const QString pos = v.toString();
        m_pos = Pos::fromString(pos);
    }
}
Beispiel #20
0
void OctreePersistThread::parseSettings(const QJsonObject& settings) {
    if (settings["backups"].isArray()) {
        const QJsonArray& backupRules = settings["backups"].toArray();
        qCDebug(octree) << "BACKUP RULES:";

        foreach (const QJsonValue& value, backupRules) {

            QJsonObject obj = value.toObject();

            int interval = 0;
            int count = 0;
            
            QJsonValue intervalVal = obj["backupInterval"];
            if (intervalVal.isString()) {
                interval = intervalVal.toString().toInt();
            } else {
                interval = intervalVal.toInt();
            }

            QJsonValue countVal = obj["maxBackupVersions"];
            if (countVal.isString()) {
                count = countVal.toString().toInt();
            } else {
                count = countVal.toInt();
            }

            qCDebug(octree) << "    Name:" << obj["Name"].toString();
            qCDebug(octree) << "        format:" << obj["format"].toString();
            qCDebug(octree) << "        interval:" << interval;
            qCDebug(octree) << "        count:" << count;

            BackupRule newRule = { obj["Name"].toString(), interval, obj["format"].toString(), count, 0};
                                    
            newRule.lastBackup = getMostRecentBackupTimeInUsecs(obj["format"].toString());
            
            if (newRule.lastBackup > 0) {
                quint64 now = usecTimestampNow();
                quint64 sinceLastBackup = now - newRule.lastBackup;
                qCDebug(octree) << "        lastBackup:" << qPrintable(formatUsecTime(sinceLastBackup)) << "ago";
            } else {
                qCDebug(octree) << "        lastBackup: NEVER";
            }
            
            _backupRules << newRule;
        }        
    } else {
DocumentFormattingProperty::DocumentFormattingProperty(const QJsonValue &value)
{
    if (value.isBool())
        *this = value.toBool();
    if (value.isDouble())
        *this = value.toDouble();
    if (value.isString())
        *this = value.toString();
}
Beispiel #22
0
QString YggdrasilTask::processError(QJsonObject responseData)
{
	QJsonValue errorVal = responseData.value("error");
	QJsonValue errorMessageValue = responseData.value("errorMessage");
	QJsonValue causeVal = responseData.value("cause");

	if (errorVal.isString() && errorMessageValue.isString())
	{
		m_error = std::shared_ptr<Error>(new Error{
			errorVal.toString(""), errorMessageValue.toString(""), causeVal.toString("")});
		return m_error->m_errorMessageVerbose;
	}
	else
	{
		// Error is not in standard format. Don't set m_error and return unknown error.
		return tr("An unknown Yggdrasil error occurred.");
	}
}
void QProcessResultThread::GetStringValue( QString& strValue, const char* pKey, const QJsonObject& jsonObj )
{
    strValue = "";

    QJsonValue jsonVal = jsonObj.value( pKey );
    if ( !jsonVal.isUndefined( ) && jsonVal.isString( ) ) {
        strValue = jsonVal.toString( );
    }
}
Beispiel #24
0
QString errorStringFromAPIObject(const QJsonValue& apiObject) {
    if (apiObject.isArray()) {
        return apiObject.toArray()[0].toString();
    } else if (apiObject.isString()) {
        return apiObject.toString();
    } else {
        return "is invalid";
    }
}
//---------------------------------------------------------
//   onGetMediaUrlReply
//---------------------------------------------------------
void LoginManager::onGetMediaUrlReply(QNetworkReply* reply, int code, const QJsonObject& response)
      {
      if (code == HTTP_OK) {
            QJsonValue urlValue = response.value("url");
            if (urlValue.isString()) {
                  _mediaUrl = urlValue.toString();
                  QString mp3Path = QDir::tempPath() + QString("/temp_%1.mp3").arg(qrand() % 100000);
                  _mp3File = new QFile(mp3Path);
                  Score* score = mscore->currentScore()->masterScore();
                  int br = preferences.getInt(PREF_EXPORT_MP3_BITRATE);
                  preferences.setPreference(PREF_EXPORT_MP3_BITRATE, 128);
                  if (mscore->saveMp3(score, mp3Path)) { // no else, error handling is done in saveMp3
                        _uploadTryCount = 0;
                        uploadMedia();
                        }
                  preferences.setPreference(PREF_EXPORT_MP3_BITRATE, br);
                  }
            }
      else // TODO: handle request error properly
            qWarning("%s", getErrorString(reply, response).toUtf8().constData());
#if 0
      disconnect(_oauthManager, SIGNAL(requestReady(QByteArray)),
            this, SLOT(onGetMediaUrlRequestReady(QByteArray)));
      QJsonDocument jsonResponse = QJsonDocument::fromJson(ba);
      QJsonObject response = jsonResponse.object();
      QJsonValue urlValue = response.value("url");
      if (urlValue.isString()) {
            _mediaUrl = response.value("url").toString();
            QString mp3Path = QDir::tempPath() + QString("/temp_%1.mp3").arg(qrand() % 100000);
            _mp3File = new QFile(mp3Path);
            Score* score = mscore->currentScore()->masterScore();
            int br = preferences.getInt(PREF_EXPORT_MP3_BITRATE);
            preferences.setPreference(PREF_EXPORT_MP3_BITRATE, 128);
            if (mscore->saveMp3(score, mp3Path)) { // no else, error handling is done in saveMp3
                  _uploadTryCount = 0;
                  uploadMedia();
                  }
            preferences.setPreference(PREF_EXPORT_MP3_BITRATE, br);
            }
#endif
      }
Beispiel #26
0
Mode7::Mode7(const Comment &comment)
	: sprite(nullptr)
{
	Q_ASSERT(comment.mode == 7);
	QJsonArray data = QJsonDocument::fromJson(comment.string.toUtf8()).array();
	int l = data.size();
	if (l < 5){
		throw format_unrecognized();
	}
	QSize size = lApp->findObject<ARender>()->getActualSize();
	auto getDouble = [&data](int i){return data.at(i).toVariant().toDouble(); };
	double scale = getScale(comment.mode, comment.date, size);
	bPos = QPointF(getDouble(0), getDouble(1));
	ePos = l < 8 ? bPos : QPointF(getDouble(7), getDouble(8));
	int w = size.width(), h = size.height();
	if (bPos.x() < 1 && bPos.y() < 1 && ePos.x() < 1 && ePos.y() < 1){
		bPos.rx() *= w;
		ePos.rx() *= w;
		bPos.ry() *= h;
		ePos.ry() *= h;
		scale = 1;
	}
	else if (scale == 0){
		scale = 1;
	}
	else{
		QSizeF player = getPlayer(comment.date);
		QPoint offset = QPoint((w - player.width()*scale) / 2, (h - player.height()*scale) / 2);
		bPos = bPos*scale + offset;
		ePos = ePos*scale + offset;
	}
	QStringList alpha = data[2].toString().split('-');
	bAlpha = alpha[0].toDouble();
	eAlpha = alpha[1].toDouble();
	life = getDouble(3);
	QJsonValue v = l < 12 ? QJsonValue(true) : data[11];
	int effect = (v.isString() ? v.toString() == "true" : v.toVariant().toBool()) ? Config::getValue("/Danmaku/Effect", 5) / 2 : -1;
	QFont font = getFont(scale ? comment.font*scale : comment.font, l < 13 ? Utils::defaultFont(true) : data[12].toString());
	QString string = data[4].toString();
	sprite = lApp->findObject<ARender>()->getSprite();
	sprite->setAlpha(1.0);
	sprite->setColor(QColor::fromRgb(comment.color));
	sprite->setEffect(effect);
	sprite->setFont(font);
	sprite->setFrame(comment.isLocal());
	sprite->setText(string);
	zRotate = l < 6 ? 0 : getDouble(5);
	yRotate = l < 7 ? 0 : getDouble(6);
	wait = l < 11 ? 0 : getDouble(10) / 1000;
	stay = l < 10 ? 0 : life - wait - getDouble(9) / 1000;
	source = &comment;
	time = 0;
}
Beispiel #27
0
long Utils::getLong(const QString &key, const QJsonObject &obj)
{
    if(obj.isEmpty() || key.isEmpty()) {
        return -1;
    }
    if (obj.contains(key)) {
        QJsonValue value = obj.value(key);
        if (value.isDouble() || value.isString()) {
            return value.toString().toLong();
        }
    }
    return -1;
}
Beispiel #28
0
bool JsonDbObject::isAncestorOf(const QJsonArray &history, const int updateCount, const QString &hash) const
{
    if (updateCount < 1 || history.size() < updateCount)
        return false;

    QJsonValue knownHashes = history.at(updateCount - 1);
    if (knownHashes.isString())
        return knownHashes.toString() == hash;
    else if (knownHashes.isArray())
        return knownHashes.toArray().contains(hash);
    else
        return false;
}
static Nuria::JsonMetaObjectReader::Error parseMethodObject (Nuria::MetaMethod::Type type, const QJsonObject &method,
							     Nuria::RuntimeMetaObject *metaObject) {
	using namespace Nuria;
	
	QJsonValue annotationsValue = method.value (QStringLiteral("annotations"));
	QJsonValue argNamesValue = method.value (QStringLiteral("argumentNames"));
	QJsonValue argTypesValue = method.value (QStringLiteral("argumentTypes"));
	QJsonValue resultTypeValue = method.value (QStringLiteral("resultType"));
	QJsonValue nameValue = method.value (QStringLiteral("name"));
	
	// Type checks
	if (!annotationsValue.isArray ()) return JsonMetaObjectReader::AnnotationsIsNotAnArray;
	if (!argNamesValue.isArray ()) return JsonMetaObjectReader::MethodArgumentNamesIsNotAnArray;
	if (!argTypesValue.isArray ()) return JsonMetaObjectReader::MethodArgumentTypesIsNotAnArray;
	if (!resultTypeValue.isString ()) return JsonMetaObjectReader::MethodResultTypeIsNotAString;
	if (!nameValue.isString ()) return JsonMetaObjectReader::MethodNameIsNotAString;
	
	// Parse annotations
	Nuria::JsonMetaObjectReader::Error error;
	
	RuntimeMetaObject::AnnotationMap annotations;
	error = parseAnnotationsArray (annotationsValue.toArray (), annotations);
	if (error != Nuria::JsonMetaObjectReader::NoError) return error;
	
	// Arguments
	QVector< QByteArray > argNames;
	QVector< QByteArray > argTypes;
	
	error = parseMethodArgumentList (argNamesValue.toArray (), argTypesValue.toArray (), argNames, argTypes);
	if (error != Nuria::JsonMetaObjectReader::NoError) return error;
	
	// Base
	QByteArray name = nameValue.toString ().toLatin1 ();
	QByteArray resultType = resultTypeValue.toString ().toLatin1 ();
	
	// Store
	metaObject->addMethod (type, name, resultType, argNames, argTypes, annotations, invalidCallbackCreator);
	return Nuria::JsonMetaObjectReader::NoError;
}
Beispiel #30
0
static inline int jsonToDouble(const QJsonValue &value,
                               const QMap<QString, QJsonValue> &defines)
{
    QJsonValue trueValue = value;
    if (value.isString()) {
        QString valueString = value.toString();
        if (defines.contains(valueString)) {
            trueValue = defines.value(valueString);
        }
    }
        
    return trueValue.toDouble();
}