Example #1
0
void QRestClient::oAuthLogin(
        QVariant id,
        QVariant secret,
        jsonPayloadFn successCb,
        jsonPayloadFn errCb)
{
    QJsonObject clientCredentials
    {
        {"client_id", QJsonValue::fromVariant(id)},
        {"client_secret", QJsonValue::fromVariant(secret)},
        {"grant_type", QJsonValue::fromVariant("client_credentials")}
    };

    this->asyncJsonCall("post", "oauth/access_token",
        QJsonDocument(clientCredentials),
        //Success callback
        [this, successCb, errCb](QJsonDocument payload){
            if(!payload.isObject() || !payload.object().contains("access_token")) {
                //Custom oAuth Error
                if(errCb)
                    errCb(buildJsonError("OAuth2: Error while getting bearer token", payload.toJson()));
                return;
            }

            this->m_oAuthToken = payload.object()["access_token"].toVariant().toByteArray();
            this->setAuthMethod(OAuth2);
            if(successCb)
                successCb(QJsonDocument());
        //For other errors
        },
        errCb
    );
}
Example #2
0
/*!
 Creates a QJsonDocument from \a data.

 \a validation decides whether the data is checked for validity before being used.
 By default the data is validated. If the \a data is not valid, the method returns
 a null document.

 \sa toBinaryData(), fromRawData(), isNull(), DataValidation
 */
QJsonDocument QJsonDocument::fromBinaryData(const QByteArray &data, DataValidation validation)
{
    if (data.size() < (int)(sizeof(QJsonPrivate::Header) + sizeof(QJsonPrivate::Base)))
        return QJsonDocument();

    QJsonPrivate::Header h;
    memcpy(&h, data.constData(), sizeof(QJsonPrivate::Header));
    QJsonPrivate::Base root;
    memcpy(&root, data.constData() + sizeof(QJsonPrivate::Header), sizeof(QJsonPrivate::Base));

    // do basic checks here, so we don't try to allocate more memory than we can.
    if (h.tag != QJsonDocument::BinaryFormatTag || h.version != 1u ||
        sizeof(QJsonPrivate::Header) + root.size > (uint)data.size())
        return QJsonDocument();

    const uint size = sizeof(QJsonPrivate::Header) + root.size;
    char *raw = (char *)malloc(size);
    if (!raw)
        return QJsonDocument();

    memcpy(raw, data.constData(), size);
    QJsonPrivate::Data *d = new QJsonPrivate::Data(raw, size);

    if (validation != BypassValidation && !d->valid()) {
        delete d;
        return QJsonDocument();
    }

    return QJsonDocument(d);
}
Example #3
0
void Application::incomingGuiMessage(const QJsonDocument& message) {
    try {
        // The message contains a JSON object of the GenericMessage
        common::GenericMessage msg = common::GenericMessage(message);
            
        qDebug() << "Received message of type " << msg.type;

        if (msg.type == common::GuiStartCommand::Type) {
            // We have received a message from the GUI to start a new application
            handleIncomingGuiStartCommand(
                common::GuiStartCommand(QJsonDocument(msg.payload))
            );
        } else if (msg.type == common::GuiProcessCommand::Type) {
            // We have received a message from the GUI to start a new application
            handleIncomingGuiProcessCommand(
                common::GuiProcessCommand(QJsonDocument(msg.payload))
            );
        }
        else if (msg.type == "GuiReloadConfigCommand") {
             // We have received a message from the GUI to reload the configs
            handleIncomingGuiReloadConfigCommand();
         }
    } catch (const std::runtime_error& e) {
        Log(QString("Error with incoming gui message: ") + e.what());
        Log(message.toJson());
    }
}
Example #4
0
void MainWindow::enginioFinished(EnginioReply *msg)
{
  if(msg->errorType() != EnginioReply::NoError) {
    return;
  }

  logDebug(QJsonDocument(msg->data()).toJson());

  if(msg == m_exportReply) {
    QJsonArray jsonArray(m_exportReply->data().value("results").toArray());
    QByteArray jsonText = QJsonDocument(jsonArray).toJson();
    QFile exportFile(m_exportFile->text());
    bool ok = exportFile.open(QIODevice::WriteOnly);
    if(ok) {
      exportFile.write(jsonText);
      log(tr("%1 object(s) exported to %2").arg(jsonArray.size()).arg(exportFile.fileName()));
    }
    else {
      logError(tr("Error %1 opening file %2").arg(exportFile.error()).arg(exportFile.fileName()));
    }
  }
  if(msg == m_queryForRemovalReply) {
    QJsonArray jsonArray(m_queryForRemovalReply->data().value("results").toArray());
    foreach(const QJsonValue &v, jsonArray) {
      QJsonObject removeObject(v.toObject());
      setObjectType(&removeObject);
      m_client->remove(removeObject);
    }
Example #5
0
void LocationService::getImpl(const QByteArray& operation, const APIParameters &parameters, APIServiceResponse &response)
{
	if(operation=="list")
	{
		//for now, this does not return location objects (which would require a much larger data transfer), but only the location strings
		//same as in the LocationDialog list

		//TODO not fully thread safe
		QJsonArray list = QJsonArray::fromStringList(QStringList(locMgr->getAllMap().keys()));

		response.writeJSON(QJsonDocument(list));
	}
	else if(operation == "countrylist")
	{
		const StelTranslator& trans = *StelTranslator::globalTranslator;

		QStringList allCountries = StelApp::getInstance().getLocaleMgr().getAllCountryNames();
		QJsonArray list;
		foreach(QString str, allCountries)
		{
			QJsonObject obj;
			obj.insert("name",str);
			obj.insert("name_i18n",trans.qtranslate(str));
			list.append(obj);
		}

		response.writeJSON(QJsonDocument(list));
	}
Example #6
0
QJsonDocument jsonparser::jsonOpenFile(QString filename){
    QFile jDocFile;
    QFileInfo cw(filename);
    if(startDir.isEmpty()){
        startDir = cw.absolutePath();
        jDocFile.setFileName(startDir+"/"+cw.fileName());
    }else
        jDocFile.setFileName(startDir+"/"+cw.fileName());
    if (!jDocFile.exists()) {
        sendProgressTextUpdate(tr("Failed due to the file %1 not existing").arg(jDocFile.fileName()));
        return QJsonDocument();
    }
    if (!jDocFile.open(QIODevice::ReadOnly|QIODevice::Text)) {
        sendProgressTextUpdate(tr("Failed to open the requested file"));
        return QJsonDocument();
    }
    QJsonParseError initError;
    QJsonDocument jDoc = QJsonDocument::fromJson(jDocFile.readAll(),&initError);
    if (initError.error != 0){
        reportError(2,tr("ERROR: jDoc: %s\n").arg(initError.errorString()));
        sendProgressTextUpdate(tr("An error occured. Please take a look at the error message to see what went wrong."));
        return QJsonDocument();
    }
    if (jDoc.isNull() || jDoc.isEmpty()) {
        sendProgressTextUpdate(tr("Failed to import file"));
        return QJsonDocument();
    }
    return jDoc;
}
Example #7
0
void Application::incomingTrayMessage(const Cluster& cluster, const Cluster::Node& node,
                                      const QJsonDocument& message)
{
    try {
        // The message contains a JSON object of the GenericMessage
        common::GenericMessage msg = common::GenericMessage(message);

        qDebug() << "Received message of type " << msg.type;

        if (msg.type == common::TrayProcessStatus::Type) {
            // We have received a message from the GUI to start a new application
            handleTrayProcessStatus(
                cluster,
                node,
                common::TrayProcessStatus(QJsonDocument(msg.payload))
            );
        } else if (msg.type == common::TrayProcessLogMessage::Type) {
            // We have received a message from the GUI to start a new application
            handleTrayProcessLogMessage(
                cluster,
                node,
                common::TrayProcessLogMessage(QJsonDocument(msg.payload))
            );
        }
    }
    catch (const std::runtime_error& e) {
        Log(QString("Error with incoming tray message: ") + e.what());
        Log(message.toJson());
    }
}
Example #8
0
void ScriptService::getImpl(const QByteArray& operation, const APIParameters &parameters, APIServiceResponse &response)
{
	if(operation=="list")
	{
		//list all scripts, this should be thread safe
		QStringList allScripts = scriptMgr->getScriptList();

		response.writeJSON(QJsonDocument(QJsonArray::fromStringList(allScripts)));
	}
	else if (operation == "info")
	{
		if(parameters.contains("id"))
		{
			//retrieve detail about a single script
			QString scriptId = QString::fromUtf8(parameters.value("id"));

			if(parameters.contains("html"))
			{
				QString html = scriptMgr->getHtmlDescription(scriptId, false);
				response.setHeader("Content-Type","text/html; charset=UTF-8");
				response.setData(wrapHtml(html, scriptId).toUtf8());
				return;
			}

			QJsonObject obj;
			//if the script name is wrong, this will return empty strings
			obj.insert("id",scriptId);
			QString d = scriptMgr->getName(scriptId).trimmed();
			obj.insert("name",d);
			obj.insert("name_localized", StelTranslator::globalTranslator->qtranslate(d));
			d = scriptMgr->getDescription(scriptId).trimmed();
			obj.insert("description",d);
			obj.insert("description_localized", StelTranslator::globalTranslator->qtranslate(d));
			obj.insert("author",scriptMgr->getAuthor(scriptId).trimmed());
			obj.insert("license",scriptMgr->getLicense(scriptId).trimmed());
			//shortcut often causes a large delay because the whole file gets searched, and it is usually missing, so we ignore it
			//obj.insert("shortcut",scriptMgr->getShortcut(scriptId));

			response.writeJSON(QJsonDocument(obj));
		}
		else
		{
			response.writeRequestError("need parameter: id");
		}
	}
	else if(operation == "status")
	{
		//generic script status
		QJsonObject obj;
		obj.insert("scriptIsRunning",scriptMgr->scriptIsRunning());
		obj.insert("runningScriptId",scriptMgr->runningScriptId());

		response.writeJSON(QJsonDocument(obj));
	}
	else
	{
		//TODO some sort of service description?
		response.writeRequestError("unsupported operation. GET: list,info,status POST: run,stop");
	}
}
void LocationSearchService::getImpl(const QByteArray& operation, const APIParameters &parameters, APIServiceResponse &response)
{
	if(operation=="search")
	{
		//parameter must be named "term" to be compatible with jQuery UI autocomplete without further JS code
		QString term = QString::fromUtf8(parameters.value("term"));

		if(term.isEmpty())
		{
			response.writeRequestError("needs non-empty 'term' parameter");
			return;
		}

		//the filtering in the app is provided by QSortFilterProxyModel in the view
		//we dont have that luxury, but we make sure the filtering happens in the separate HTTP thread
		locMgrMutex.lock();
		LocationMap allItems = locMgr.getAllMap();
		locMgrMutex.unlock();

		QJsonArray results;
		const QList<QString>& list = allItems.keys();

		//use a regexp in wildcard mode, the app does the same
		QRegExp exp(term,Qt::CaseInsensitive, QRegExp::Wildcard);

		for(QList<QString>::const_iterator it = list.begin();it!=list.end();++it)
		{
			if(it->contains(exp))
				results.append(*it);
		}

		response.writeJSON(QJsonDocument(results));
	}
	else if(operation=="nearby")
	{
		QString sPlanet = QString::fromUtf8(parameters.value("planet"));
		QString sLatitude = QString::fromUtf8(parameters.value("latitude"));
		QString sLongitude = QString::fromUtf8(parameters.value("longitude"));
		QString sRadius = QString::fromUtf8(parameters.value("radius"));

		float latitude = sLatitude.toFloat();
		float longitude = sLongitude.toFloat();
		float radius = sRadius.toFloat();

		locMgrMutex.lock();
		LocationMap results = locMgr.pickLocationsNearby(sPlanet,longitude,latitude,radius);
		locMgrMutex.unlock();

		response.writeJSON(QJsonDocument(QJsonArray::fromStringList(results.keys())));
	}
	else
	{
		//TODO some sort of service description?
		response.writeRequestError("unsupported operation. GET: search,nearby");
	}
}
Example #10
0
void NetworkManager::processJson(QString json)
{
    //log("Json received : " + json);

    // Parse main parts of the message (type and body)

    QJsonDocument doc; doc = doc.fromJson(json.toUtf8());
    QString type = doc.object().take("type").toString();
    QJsonValue body = doc.object().take("body");

    // Routing messages by type

    if ( type == "hbAck" ){

        emit hearthbeatReceived(body.toString());
    }
    else if ( type == "setVariable" ){

        QString variable = body.toObject().take("variable").toString();
        QString option = body.toObject().take("option").toString();
        QString json = QJsonDocument( body.toObject().take("value").toObject() ).toJson();

        emit systemVariableChanged(variable, option, json);
    }
    else if ( type == "call" ){

            QString module = body.toObject().take("module").toString();
            QString function = body.toObject().take("function").toString();
            if (function == "")
                function = body.toObject().take("fct").toString();
            QString params = QJsonDocument( body.toObject().take("param").toArray() ).toJson();

            emit callRequest(module, function, params);
    }
    else if ( type == "ssid" ){

        setssid(body.toString());

        setLoggedState(true);
    }
    else if ( type == "login-error" ){

        log("Login error : " + body.toString());
        setLoggedState(false);
    }
    else if ( type == "error"){

        log("Server error : " + body.toString());
    }
    else{

        emit jsonReceived(type, body);
        emit jsonStringReceived(json);
    }
}
Example #11
0
void Ledger::send(const QString& endpoint, const QString& success, const QString& fail, QNetworkAccessManager::Operation method, AccountManagerAuth::Type authType, QJsonObject request) {
    auto accountManager = DependencyManager::get<AccountManager>();
    const QString URL = "/api/v1/commerce/";
    JSONCallbackParameters callbackParams(this, success, this, fail);
    qCInfo(commerce) << "Sending" << endpoint << QJsonDocument(request).toJson(QJsonDocument::Compact);
    accountManager->sendRequest(URL + endpoint,
        authType,
        method,
        callbackParams,
        QJsonDocument(request).toJson());
}
Example #12
0
 char *toString(const QJsonValue &value)
 {
     QByteArray ret;
     if (value.isObject())
         ret = QJsonDocument(value.toObject()).toJson();
     else if (value.isArray())
         ret = QJsonDocument(value.toArray()).toJson();
     else
         ret = value.toString().toLatin1();
     return qstrdup(ret.data());
 }
Example #13
0
File: var.cpp Project: Aspenka/SSD
QString Var::exportToJsonString()
{
	QJsonDocument doc;
	if(getType()=="string")
		return this->exportToJson().toString();
	if(getType()=="map")
		doc=QJsonDocument(this->exportToJson().toObject());
	if(getType()=="list")
		doc=QJsonDocument(this->exportToJson().toArray());
	return doc.toJson();
}
Example #14
0
QByteArray NJson::stringify(QJsonDocument::JsonFormat format) const
{
    QJsonDocument doc;
    if (mRootValue.isArray()) {
        doc = QJsonDocument(mRootValue.toArray());
    } else {
        doc = QJsonDocument(mRootValue.toObject());
    }

    return doc.toJson(format);
}
bool OwnCloudNetworkFactory::createFeed(const QString &url, int parent_id) {
  QJsonObject json;

  json["url"] = url;
  json["folderId"] = parent_id;

  QByteArray result_raw;
  NetworkResult network_reply = NetworkFactory::performNetworkOperation(m_urlFeeds,
                                                                        qApp->settings()->value(GROUP(Feeds),
                                                                                                SETTING(Feeds::UpdateTimeout)).toInt(),
                                                                        QJsonDocument(json).toJson(QJsonDocument::Compact),
                                                                        QSL("application/json"),
                                                                        result_raw,
                                                                        QNetworkAccessManager::PostOperation,
                                                                        true, m_authUsername, m_authPassword, true);

  m_lastError = network_reply.first;

  if (network_reply.first != QNetworkReply::NoError) {
    qWarning("ownCloud: Creating of category failed with error %d.", network_reply.first);
    return false;
  }
  else {
    return true;
  }
}
Example #16
0
bool FileManager::saveToFile( QString path, QString categoryPath, QList<TrackModel*> trackModels )
{
    QJsonObject jsonObject;
    QJsonArray  trackArray;

    for ( int i = 0; i < trackModels.size(); i++ )
        trackArray.append( trackModels[i]->serializeToJson() );

    // Put into json document
    jsonObject["categoryPath"] = categoryPath;
    jsonObject["tracks"] = trackArray;
    QJsonDocument jsonDoc = QJsonDocument( jsonObject );

    // Prep file
    QFile file;
    file.setFileName( path );

    // Open
    if ( !file.open( QIODevice::WriteOnly | QIODevice::Text ) )
        return false;

    // Write
    int result = file.write( jsonDoc.toJson() );
    qDebug() << "...wrote" << result << "bytes to" << path;

    return result != -1;
}
Example #17
0
	// returns null array on error
	QByteArray makeJsonpStart(int code, const QByteArray &reason, const HttpHeaders &headers)
	{
		QByteArray out = "/**/" + jsonpCallback + "(";

		if(jsonpExtendedResponse)
		{
			QByteArray reasonJson = serializeJsonString(QString::fromUtf8(reason));
			if(reasonJson.isNull())
				return QByteArray();

			QVariantMap vheaders;
			foreach(const HttpHeader h, headers)
			{
				if(!vheaders.contains(h.first))
					vheaders[h.first] = h.second;
			}

			QByteArray headersJson = QJsonDocument(QJsonObject::fromVariantMap(vheaders)).toJson(QJsonDocument::Compact);
			if(headersJson.isNull())
				return QByteArray();

			out += "{\"code\": " + QByteArray::number(code) + ", \"reason\": " + reasonJson + ", \"headers\": " + headersJson + ", \"body\": \"";
		}

		return out;
	}
Example #18
0
void MainWindow::loadthreadfromeinternet()
{
    MyMutexLocker mml2("mainwindowtest1",1000);
    if (!mml2.success()) return;
    clearAll();
    //322 383 359 390
    //403
    //391
    //454 278 387 415 366 385 368  402  307  405
// add 371
    int a[17] = {322, 383, 359, 390, 403, 391,  454, 278, 387, 415, 366, 385, 368,  402,  307,  405, 371};
    for (int i=0; i<17; i++) {
        //if (a[i] == 359) continue;   // jiuwen  bucha
        QString s = "forum";
        s+=QString::number(a[i]);
        s+=".txt";
        QJsonDocument jd;
        FileCenter::load(s, jd);
        SisThread::read( jd.array());
        SisThread::getOneForum(QString::number(a[i]));
        QJsonArray aa;
        SisThread::write(aa);
        FileCenter::save(s, QJsonDocument(aa));
        clearAll();
    }
}
Example #19
0
int OctreeQuery::getBroadcastData(unsigned char* destinationBuffer) {
    unsigned char* bufferStart = destinationBuffer;
    
    // back a boolean (cut to 1 byte) to designate if this query uses the sent view frustum
    memcpy(destinationBuffer, &_usesFrustum, sizeof(_usesFrustum));
    destinationBuffer += sizeof(_usesFrustum);
    
    if (_usesFrustum) {
        // TODO: DRY this up to a shared method
        // that can pack any type given the number of bytes
        // and return the number of bytes to push the pointer
        
        // camera details
        memcpy(destinationBuffer, &_cameraPosition, sizeof(_cameraPosition));
        destinationBuffer += sizeof(_cameraPosition);
        destinationBuffer += packOrientationQuatToBytes(destinationBuffer, _cameraOrientation);
        destinationBuffer += packFloatAngleToTwoByte(destinationBuffer, _cameraFov);
        destinationBuffer += packFloatRatioToTwoByte(destinationBuffer, _cameraAspectRatio);
        destinationBuffer += packClipValueToTwoByte(destinationBuffer, _cameraNearClip);
        destinationBuffer += packClipValueToTwoByte(destinationBuffer, _cameraFarClip);
        memcpy(destinationBuffer, &_cameraEyeOffsetPosition, sizeof(_cameraEyeOffsetPosition));
        destinationBuffer += sizeof(_cameraEyeOffsetPosition);
    }
    
    // desired Max Octree PPS
    memcpy(destinationBuffer, &_maxQueryPPS, sizeof(_maxQueryPPS));
    destinationBuffer += sizeof(_maxQueryPPS);

    // desired voxelSizeScale
    memcpy(destinationBuffer, &_octreeElementSizeScale, sizeof(_octreeElementSizeScale));
    destinationBuffer += sizeof(_octreeElementSizeScale);

    // desired boundaryLevelAdjust
    memcpy(destinationBuffer, &_boundaryLevelAdjust, sizeof(_boundaryLevelAdjust));
    destinationBuffer += sizeof(_boundaryLevelAdjust);

    memcpy(destinationBuffer, &_cameraCenterRadius, sizeof(_cameraCenterRadius));
    destinationBuffer += sizeof(_cameraCenterRadius);
    
    // create a QByteArray that holds the binary representation of the JSON parameters
    QByteArray binaryParametersDocument;
    
    if (!_jsonParameters.isEmpty()) {
        binaryParametersDocument = QJsonDocument(_jsonParameters).toBinaryData();
    }
    
    // write the size of the JSON parameters
    uint16_t binaryParametersBytes = binaryParametersDocument.size();
    memcpy(destinationBuffer, &binaryParametersBytes, sizeof(binaryParametersBytes));
    destinationBuffer += sizeof(binaryParametersBytes);
    
    // pack the binary JSON parameters
    // NOTE: for now we assume that the filters that will be set are all small enough that we will not have a packet > MTU
    if (binaryParametersDocument.size() > 0) {
        memcpy(destinationBuffer, binaryParametersDocument.data(), binaryParametersBytes);
        destinationBuffer += binaryParametersBytes;
    }
    
    return destinationBuffer - bufferStart;
}
Example #20
0
void ImageProvider::saveLastPicture() const {
    QFile f("/home/ilya/.myQtProgs/photos_last.json");
    if (f.open(QIODevice::WriteOnly)) {
        f.write(QJsonDocument(lastPicture).toJson());
        f.close();
    }
}
Example #21
0
void LoginDialog::linkSteam() {
    qDebug() << "Attempting to link Steam account";
    if (auto steamClient = PluginManager::getInstance()->getSteamClientPlugin()) {
        steamClient->requestTicket([this](Ticket ticket) {
            if (ticket.isNull()) {
                emit handleLoginFailed();
                return;
            }

            JSONCallbackParameters callbackParams;
            callbackParams.jsonCallbackReceiver = this;
            callbackParams.jsonCallbackMethod = "linkCompleted";
            callbackParams.errorCallbackReceiver = this;
            callbackParams.errorCallbackMethod = "linkFailed";

            const QString LINK_STEAM_PATH = "api/v1/user/steam/link";

            QJsonObject payload;
            payload.insert("steam_auth_ticket", QJsonValue::fromVariant(QVariant(ticket)));

            auto accountManager = DependencyManager::get<AccountManager>();
            accountManager->sendRequest(LINK_STEAM_PATH, AccountManagerAuth::Required,
                                        QNetworkAccessManager::PostOperation, callbackParams,
                                        QJsonDocument(payload).toJson());
        });
    }
}
Example #22
0
void ChatServer::broadcastUsers(QList<ChatUser *> users, ChatUser * const exclude)
{
    QJsonArray jsonUsers;
    for(ChatUser* u: users) {
        if (!u) continue;
        QJsonObject jsonUser;
        jsonUser["id"] = u->id();
        jsonUser["name"] = u->name();
        jsonUser["isOnline"] = u->isOnline();
        jsonUser["status"] = u->status();
        jsonUsers.append(QJsonValue(jsonUser));
    }

    QJsonObject jsonContainer;
    jsonContainer["type"] = QString("updateusers");
    jsonContainer["users"] = jsonUsers;

    QJsonDocument jsonDoc = QJsonDocument(jsonContainer);
    QByteArray userData = jsonDoc.toBinaryData();
    qWarning() << "ONLINE USERS" << _chatUsers;
    for (QTcpSocket* c: _chatUsers) {
        // если нет подключения или это подключение логинящегося - пропускаем
        if (!c) continue; // || c == _chatUsers[exclude]
        c->write(userData);
    }
}
bool OwnCloudNetworkFactory::renameFeed(const QString &new_name, int feed_id) {
  QString final_url = m_urlRenameFeed.arg(QString::number(feed_id));
  QByteArray result_raw;
  QJsonObject json;

  json["feedTitle"] = new_name;

  NetworkResult network_reply = NetworkFactory::performNetworkOperation(final_url,
                                                                        qApp->settings()->value(GROUP(Feeds),
                                                                                                SETTING(Feeds::UpdateTimeout)).toInt(),
                                                                        QJsonDocument(json).toJson(QJsonDocument::Compact),
                                                                        QSL("application/json"), result_raw,
                                                                        QNetworkAccessManager::PutOperation,
                                                                        true, m_authUsername, m_authPassword,
                                                                        true);
  m_lastError = network_reply.first;

  if (network_reply.first != QNetworkReply::NoError) {
    qWarning("ownCloud: Renaming of feed failed with error %d.", network_reply.first);
    return false;
  }
  else {
    return true;
  }
}
void UserActivityLogger::logAction(QString action, QJsonObject details, JSONCallbackParameters params) {
    if (_disabled.get()) {
        return;
    }
    
    auto accountManager = DependencyManager::get<AccountManager>();
    QHttpMultiPart* multipart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
    
    // Adding the action name
    QHttpPart actionPart;
    actionPart.setHeader(QNetworkRequest::ContentDispositionHeader, "form-data; name=\"action_name\"");
    actionPart.setBody(QByteArray().append(action));
    multipart->append(actionPart);
    
    // If there are action details, add them to the multipart
    if (!details.isEmpty()) {
        QHttpPart detailsPart;
        detailsPart.setHeader(QNetworkRequest::ContentDispositionHeader, "form-data;"
                              " name=\"action_details\"");
        detailsPart.setBody(QJsonDocument(details).toJson(QJsonDocument::Compact));
        multipart->append(detailsPart);
    }
    
    // if no callbacks specified, call our owns
    if (params.isEmpty()) {
        params.errorCallbackReceiver = this;
        params.errorCallbackMethod = "requestError";
    }
    
    accountManager->sendRequest(USER_ACTIVITY_URL,
                               AccountManagerAuth::Optional,
                               QNetworkAccessManager::PostOperation,
                               params, NULL, multipart);
}
Example #25
0
void Utils::saveConfig()
{
	QFile conf("./Config.txt");
	conf.open(QIODevice::WriteOnly|QIODevice::Text);
	conf.write(QJsonDocument(config).toJson());
	conf.close();
}
Example #26
0
void LoginDialog::createAccountFromStream(QString username) {
    qDebug() << "Attempting to create account from Steam info";
    if (auto steamClient = PluginManager::getInstance()->getSteamClientPlugin()) {
        steamClient->requestTicket([this, username](Ticket ticket) {
            if (ticket.isNull()) {
                emit handleLoginFailed();
                return;
            }

            JSONCallbackParameters callbackParams;
            callbackParams.jsonCallbackReceiver = this;
            callbackParams.jsonCallbackMethod = "createCompleted";
            callbackParams.errorCallbackReceiver = this;
            callbackParams.errorCallbackMethod = "createFailed";

            const QString CREATE_ACCOUNT_FROM_STEAM_PATH = "api/v1/user/steam/create";

            QJsonObject payload;
            payload.insert("steam_auth_ticket", QJsonValue::fromVariant(QVariant(ticket)));
            if (!username.isEmpty()) {
                payload.insert("username", QJsonValue::fromVariant(QVariant(username)));
            }

            auto accountManager = DependencyManager::get<AccountManager>();
            accountManager->sendRequest(CREATE_ACCOUNT_FROM_STEAM_PATH, AccountManagerAuth::None,
                                        QNetworkAccessManager::PostOperation, callbackParams,
                                        QJsonDocument(payload).toJson());
        });
    }

}
QByteArray QuickModWriter::modToJson(const QuickMod &mod)
{
	QJsonObject obj;

	obj.insert("formatVersion", 1);
	obj.insert("name", mod.name);
	obj.insert("description", mod.description);
	obj.insert("nemName", mod.nemName);
	obj.insert("modId", mod.modId);
	QJsonObject urls;
	for (auto it = mod.urls.begin(); it != mod.urls.end(); ++it)
	{
		urls.insert(it.key(), QJsonArray::fromStringList(it.value()));
	}
	obj.insert("urls", urls);
	obj.insert("updateUrl", mod.updateUrl);
	obj.insert("categories", QJsonArray::fromStringList(mod.categories));
	obj.insert("tags", QJsonArray::fromStringList(mod.tags));
	obj.insert("references", stringStringMapToJson(mod.references));
	obj.insert("authors", stringStringListMapToJson(mod.authors));
	obj.insert("uid", mod.uid);
	obj.insert("repo", mod.repo);
	obj.insert("versions", versionToJson(mod));
	obj.insert("license", mod.license);

	return QJsonDocument(obj).toJson(QJsonDocument::Indented);
}
Example #28
0
void LoginDialog::signup(const QString& email, const QString& username, const QString& password) {

    JSONCallbackParameters callbackParams;
    callbackParams.jsonCallbackReceiver = this;
    callbackParams.jsonCallbackMethod = "signupCompleted";
    callbackParams.errorCallbackReceiver = this;
    callbackParams.errorCallbackMethod = "signupFailed";

    QJsonObject payload;

    QJsonObject userObject;
    userObject.insert("email", email);
    userObject.insert("username", username);
    userObject.insert("password", password);

    payload.insert("user", userObject);

    static const QString API_SIGNUP_PATH = "api/v1/users";

    qDebug() << "Sending a request to create an account for" << username;

    auto accountManager = DependencyManager::get<AccountManager>();
    accountManager->sendRequest(API_SIGNUP_PATH, AccountManagerAuth::None,
                                QNetworkAccessManager::PostOperation, callbackParams,
                                QJsonDocument(payload).toJson());
}
Example #29
0
QString SettingsFrame::inspect() const
{
    QJsonObject settingsObj;
    for(SettingsType key: settings_.keys()) {
        QString keyStr;
        int value = settings_[key];
        switch (key) {
        case SETTINGS_HEADER_TABLE_SIZE:
            keyStr = "HEADER_TABLE_SIZE";
            break;
        case SETTINGS_ENABLE_PUSH:
            keyStr = "ENABLE_PUSH";
            break;
        case SETTINGS_MAX_CONCURRENT_STREAMS:
            keyStr = "MAX_CONCURRENT_STREAMS";
            break;
        case SETTINGS_INITIAL_WINDOW_SIZE:
            keyStr = "INITIAL_WINDOW_SIZE";
            break;
        case SETTINGS_FLOW_CONTROL_OPTIONS:
            keyStr = "FLOW_CONTROL_OPTIONS";
            break;
        }
        settingsObj[keyStr] = value;
    }
    QJsonObject obj;
    obj["ack"] = ack();
    obj["settings"] = settingsObj;

    return "SETTINGS " + QString::fromUtf8(QJsonDocument(obj).toJson(QJsonDocument::Indented));
}
Example #30
-1
QNetworkReply* MNetworkManager::sendJWT(const QString url, QJsonObject &params, QString method ) {
    QJsonObject header;
    header["typ"] = "JWT";
    header["alg"] = "sha256";

    QByteArray encode;
    encode.append(QJsonDocument(header).toJson().toBase64(QByteArray::Base64Encoding));
    encode.append(".");
    encode.append(QJsonDocument(params).toJson().toBase64(QByteArray::Base64Encoding));
    QByteArray signature = QMessageAuthenticationCode::hash(encode, QByteArray(SECRET), QCryptographicHash::Sha256).toHex();

    QByteArray jwt;
    jwt.append(encode);
    jwt.append(".");
    jwt.append(signature);

    QString apiUrl = APIHOST;
    apiUrl.append(url);

    QNetworkRequest request;
    request.setUrl(QUrl(apiUrl));
    request.setRawHeader("JWT", jwt);

    QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
    QNetworkReply* reply;

    if (method == "post") {
        reply = this->post(request,multiPart);
    } else {
        reply = this->get(request);
    }
    multiPart->setParent(reply);

    return reply;
}