QVariantMap RenderableModelEntityItem::parseTexturesToMap(QString textures) {
    // If textures are unset, revert to original textures
    if (textures.isEmpty()) {
        return _originalTextures;
    }

    // Legacy: a ,\n-delimited list of filename:"texturepath"
    if (*textures.cbegin() != '{') {
        textures = "{\"" + textures.replace(":\"", "\":\"").replace(",\n", ",\"") + "}";
    }

    QJsonParseError error;
    QJsonDocument texturesJson = QJsonDocument::fromJson(textures.toUtf8(), &error);
    // If textures are invalid, revert to original textures
    if (error.error != QJsonParseError::NoError) {
        qCWarning(entitiesrenderer) << "Could not evaluate textures property value:" << textures;
        return _originalTextures;
    }

    QVariantMap texturesMap = texturesJson.toVariant().toMap();
    // If textures are unset, revert to original textures
    if (texturesMap.isEmpty()) {
        return _originalTextures;
    }

    return texturesJson.toVariant().toMap();
}
Exemplo n.º 2
0
QString Posterous::getAuthToken(const QUrl &localUrl)
{
    QUrl url(QLatin1String("http://posterous.com/api/2/auth/token"));
    QString login = PosterousSettings::login();
    QString pass = Choqok::PasswordManager::self()->readPassword(QStringLiteral("posterous_%1").arg(PosterousSettings::login()));
    KIO::StoredTransferJob *job = KIO::storedGet(url, KIO::Reload, KIO::HideProgressInfo);
    job->addMetaData(QLatin1String("customHTTPHeader"),
                     QLatin1String("Authorization: Basic ") + QLatin1String(QStringLiteral("%1:%2").arg(login).arg(pass).toUtf8().toBase64()));
    job->exec();
    if (!job->error()) {
        const QByteArray data = job->data();
        const QJsonDocument json = QJsonDocument::fromJson(data);
        if (!json.isNull()) {
            QVariantMap map = json.toVariant().toMap();
            if (map.contains(QLatin1String("api_token"))) {
                QString tkn = map.value(QLatin1String("api_token")).toString();
                return tkn;
            } else {
                Q_EMIT uploadingFailed(localUrl, map.value(QLatin1String("error")).toString());
                qWarning() << "Parse error:" << data;
            }
        }
    } else {
        qCritical() << "Job error:" << job->errorString();
    }

    return QString();
}
Exemplo n.º 3
0
void EventPlugin::onDbEvent(const QString &name, QSqlDriver::NotificationSource source, const QVariant &payload)
{
	qfLogFuncFrame() << "name:" << name << "source:" << source << "payload:" << payload;
	if(name == QLatin1String(DBEVENT_NOTIFY_NAME)) {
		if(source == QSqlDriver::OtherSource) {
			QJsonDocument jsd = QJsonDocument::fromJson(payload.toString().toUtf8());
			QVariantMap m = jsd.toVariant().toMap();
			QString domain = m.value(QStringLiteral("domain")).toString();
			if(domain.isEmpty()) {
				qfWarning() << "DbNotify with invalid domain, payload:" << payload.toString();
				return;
			}
			QString event_name = m.value(QStringLiteral("event")).toString();
			if(event_name.isEmpty()) {
				qfWarning() << "DbNotify with invalid event name, payload:" << payload.toString();
				return;
			}
			if(event_name == eventName()) {
				QVariant pl = m.value(QStringLiteral("payload"));
				qfDebug() << "emitting domain:" << domain << "payload:" << pl;
				emit dbEventNotify(domain, pl);
			}
		}
		else {
			//qfDebug() << "self db notify";
		}
	}
}
Exemplo n.º 4
0
Client::MusicRes Client::music_daily() {
    QJsonDocument root;

    // Build a URI and get the contents
    // The fist parameter forms the path part of the URI.
    // The second parameter forms the CGI parameters.
    get( { "browse", "all", "music" }, { { "format", "json" }
         }, root);
    // https://api2.sofurry.com/browse/all/photos?format=json
    MusicRes result;

    QVariantMap variant = root.toVariant().toMap();


    for (const QVariant &i : variant["items"].toList()) {
        QVariantMap item = i.toMap();


        // Extract the temperature data

        // Add a result to the weather list
        result.musics.emplace_back(
                    Music {
                        item["thumbnail"].toString().toStdString(),
                        item["title"].toString().toStdString(),
                        item["author"].toString().toStdString(),
                        item["authorID"].toString().toStdString(),
                        item["link"].toString().toStdString(),
                        item["tags"].toString().toStdString(),
                        item["description"].toString().toStdString(),
                    });
    }

    return result;
}
Exemplo n.º 5
0
QVariant loadJSON(const std::string& json) {
  QJsonDocument doc = QJsonDocument::fromJson(toQString(json).toUtf8());
  if (doc.isNull()) {
    LOG_FREE_AND_THROW("openstudio.Json","Error parsing JSON");
  }
  return doc.toVariant();
}
Exemplo n.º 6
0
Client::Email Client::messages_set_unread(const std::string& id, bool unread) {
    std::string command = unread ? "addLabelIds" : "removeLabelIds";
    std::string payload = "{ \"" + command + "\": [\"UNREAD\"] }";
    QJsonDocument root;
    post({ "users", "me", "messages", id, "modify" }, {}, payload, root);
    return parse_email(root.toVariant());
}
void
YTVideoUrlFetcher::onProcessFinished(int code, QProcess::ExitStatus status)
{
    qDebug() << "youtube-dl process finished, status:" << status
             << ", exit code:" << code;
    if (status == QProcess::NormalExit && code == 0) {
        QByteArray rawJson = _process->readAllStandardOutput();
        QJsonParseError error;
        QJsonDocument doc = QJsonDocument::fromJson(rawJson, &error);
        if (error.error != QJsonParseError::NoError) {
            qCritical() << "JSON parse error:" << error.errorString();
            emit failure();
        } else {
            Q_ASSERT(!doc.isNull());
            QVariantMap response = parseResponse(doc);
            if (!response.isEmpty()) {
                QVariantMap map = doc.toVariant().toMap();
                Q_ASSERT(!map.isEmpty() && map.contains("id"));
                _response_cache.insert(map["id"].toString(), new QVariantMap(response));
                emit success(response);
            } else {
                emit failure();
            }
        }
    } else {
        qCritical() << "YouTubeDL process did not finish cleanly:"
                    << _process->readAllStandardError();
        emit failure();
    }
    delete _process;
    _process = NULL;
}
void DefaultReminderAttribute::deserialize(const QByteArray &data)
{
    QJsonDocument json = QJsonDocument::fromJson(data);
    if (json.isNull()) {
        return;
    }

    QVariant var = json.toVariant();
    const QVariantList list = var.toList();
    for (const QVariant &l : list) {
        QVariantMap reminder = l.toMap();

        KGAPI2::ReminderPtr rem(new KGAPI2::Reminder);

        if (reminder[QStringLiteral("type")].toString() == QLatin1String("display")) {
            rem->setType(KCalCore::Alarm::Display);
        } else if (reminder[QStringLiteral("type")].toString() == QLatin1String("email")) {
            rem->setType(KCalCore::Alarm::Email);
        }

        KCalCore::Duration offset(reminder[QStringLiteral("time")].toInt(), KCalCore::Duration::Seconds);
        rem->setStartOffset(offset);

        m_reminders << rem;
    }
}
Exemplo n.º 9
0
Client::LabelList Client::get_labels() {
    if (config_->labels.empty()) {
        QJsonDocument root;
        get({ "users", "me", "labels" }, {}, root);

        LabelList::iterator iter;
        QVariantMap variant = root.toVariant().toMap();
        QVariantList labels = variant["labels"].toList();

        for (const QVariant &i : labels) {
            QVariantMap label_map = i.toMap();
            if (label_map["messageListVisibility"] == "show") {
                iter = config_->labels.begin();
                std::string name = label_map["name"].toString().toStdString();
                // Sort by names, case insensitively
                while (iter != config_->labels.end() &&
                       strcasecmp(iter->second.c_str(), name.c_str()) <= 0)
                    iter += 1;
                config_->labels.insert(iter,
                                       std::make_pair(label_map["id"].toString().toStdString(),
                                       name));
            }
        }
    }
    return config_->labels;
}
Exemplo n.º 10
0
QMap<QUrl,QUrl>* Fetcher::parseJson(QByteArray json)
{
    QMap<QUrl,QUrl>* urls = new QMap<QUrl,QUrl>();
    QJsonDocument jsonDoc = QJsonDocument::fromJson(json);

    QVariantMap  result = jsonDoc.toVariant().toMap();
    QVariantMap  responseData = (*result.find("responseData")).toMap();
    QVariantList resultList = (*responseData.find("results")).toList();
    QVariantMap  tmp;
    QVariant     tbUrl,imgUrl;
    QString      tbUrlString,imgUrlString;

    QVariantList::iterator it;
    for(it = resultList.begin() ; it != resultList.end() ; ++it)
    {
        tmp = (*it).toMap();

        tbUrl = (*tmp.find("tbUrl"));
        imgUrl = (*tmp.find("unescapedUrl"));
        tbUrlString = tbUrl.toString();
        imgUrlString = imgUrl.toString();
        urls->insert(QUrl(imgUrlString),QUrl(tbUrlString));
    }

    return urls;
}
Exemplo n.º 11
0
BookmarkItem* ChromeImporter::importBookmarks()
{
    const QByteArray data = m_file.readAll();
    m_file.close();

    QJsonParseError err;
    QJsonDocument json = QJsonDocument::fromJson(data, &err);
    const QVariant res = json.toVariant();

    if (err.error != QJsonParseError::NoError || res.type() != QVariant::Map) {
        setError(BookmarksImporter::tr("Cannot parse JSON file!"));
        return 0;
    }

    QVariantMap rootMap = res.toMap().value("roots").toMap();

    BookmarkItem* root = new BookmarkItem(BookmarkItem::Folder);
    root->setTitle("Chrome Import");

    BookmarkItem* toolbar = new BookmarkItem(BookmarkItem::Folder, root);
    toolbar->setTitle(rootMap.value("bookmark_bar").toMap().value("name").toString());
    readBookmarks(rootMap.value("bookmark_bar").toMap().value("children").toList(), toolbar);

    BookmarkItem* other = new BookmarkItem(BookmarkItem::Folder, root);
    other->setTitle(rootMap.value("other").toMap().value("name").toString());
    readBookmarks(rootMap.value("other").toMap().value("children").toList(), other);

    BookmarkItem* synced = new BookmarkItem(BookmarkItem::Folder, root);
    synced->setTitle(rootMap.value("synced").toMap().value("name").toString());
    readBookmarks(rootMap.value("synced").toMap().value("synced").toList(), other);

    return root;
}
QVariant ContentItemInterfacePrivate::parseReplyDataVariant(const QByteArray &replyData, bool *ok)
{
    QVariant parsed;

#if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0))
    QJson::Parser jsonParser;
    parsed = jsonParser.parse(replyData, ok);
    if (!*ok) {
        qWarning() << Q_FUNC_INFO << "Error parsing JSON file:" << jsonParser.errorString()
                   << "at" << jsonParser.errorLine();
    }
#else
    QJsonParseError jsonError;
    QJsonDocument jsonDocument = QJsonDocument::fromJson(replyData, &jsonError);
    *ok = !jsonDocument.isEmpty();
    if (!*ok) {
        qWarning() << Q_FUNC_INFO << "Error parsing JSON file:" << jsonError.errorString()
                   << "at" << jsonError.offset;
    }
    parsed = jsonDocument.toVariant();
#endif

    if (!*ok) {
        parsed.clear();
    }

    return parsed;
}
Exemplo n.º 13
0
bool LoadFromJSON(QVariantMap &data, QIODevice &f, const char *magicIdentifier, uint32_t magicVersion)
{
  QByteArray json = f.readAll();

  if(json.isEmpty())
  {
    qCritical() << "Read invalid empty JSON data from file " << f.errorString();
    return false;
  }

  QJsonDocument doc = QJsonDocument::fromJson(json);

  if(doc.isEmpty() || doc.isNull())
  {
    qCritical() << "Failed to convert file to JSON document";
    return false;
  }

  data = doc.toVariant().toMap();

  if(data.isEmpty() || !data.contains(magicIdentifier))
  {
    qCritical() << "Converted config data is invalid or unrecognised";
    return false;
  }

  if(data[magicIdentifier].toUInt() != magicVersion)
  {
    qCritical() << "Converted config data is not the right version";
    return false;
  }

  return true;
}
Exemplo n.º 14
0
Query *Query::fromJSON(const QByteArray &json)
{
    QJsonParseError error;
    QJsonDocument doc = QJsonDocument::fromJson(json, &error);
    if (doc.isNull()) {
        qWarning() << "Could not parse json query" << error.errorString();
        return 0;
    }

    QVariantMap result = doc.toVariant().toMap();
    const QString type = result[QStringLiteral("type")].toString().toLower();
    if (type != QLatin1String("contact")) {
        qWarning() << "Can only handle contact queries";
        return 0;
    }

    ContactQuery *cq = new ContactQuery();
    cq->matchName(result[QStringLiteral("name")].toString());
    cq->matchNickname(result[QStringLiteral("nick")].toString());
    cq->matchEmail(result[QStringLiteral("email")].toString());
    cq->matchUID(result[QStringLiteral("uid")].toString());
    cq->match(result[QStringLiteral("$")].toString());

    const QString criteria = result[QStringLiteral("matchCriteria")].toString().toLower();
    if (criteria == QLatin1String("exact")) {
        cq->setMatchCriteria(ContactQuery::ExactMatch);
    } else if (criteria == QLatin1String("startswith")) {
        cq->setMatchCriteria(ContactQuery::StartsWithMatch);
    }

    cq->setLimit(result[QStringLiteral("limit")].toInt());

    return cq;
}
Exemplo n.º 15
0
QVariant JsonTranslationService::parseJson(const QByteArray &json)
{
#if QT_VERSION < QT_VERSION_CHECK(5,0,0)
    QString js;
    js.reserve(json.size() + 2);
    js.append("(").append(QString::fromUtf8(json)).append(")");

    static QScriptEngine engine;
    if (!engine.canEvaluate(js)) {
        m_error = tr("Couldn't parse response from the server because of an error: \"%1\"")
                  .arg(tr("Can't evaluate JSON data"));
        return QVariant();
    }

    QScriptValue data = engine.evaluate(js);
    if (engine.hasUncaughtException()) {
        m_error = tr("Couldn't parse response from the server because of an error: \"%1\"")
                  .arg(engine.uncaughtException().toString());
        return QVariant();
    }

    return data.toVariant();
#else
    QJsonParseError err;
    QJsonDocument doc = QJsonDocument::fromJson(json, &err);

    if (err.error != QJsonParseError::NoError) {
        m_error = tr("Couldn't parse response from the server because of an error: \"%1\"")
                  .arg(err.errorString());
        return QVariant();
    }

    return doc.toVariant();
#endif
}
Exemplo n.º 16
0
void Posterous::slotUpload(KJob *job)
{
    QUrl localUrl = mUrlMap.take(job);
    if (job->error()) {
        qCritical() << "Job Error:" << job->errorString();
        Q_EMIT uploadingFailed(localUrl, job->errorString());
        return;
    } else {
        KIO::StoredTransferJob *stj = qobject_cast<KIO::StoredTransferJob *>(job);
        //qDebug() << stj->data();
        const QJsonDocument json = QJsonDocument::fromJson(stj->data());
        if (!json.isNull()) {
            const QVariantMap map = json.toVariant().toMap();
            if (map.contains(QLatin1String("error"))) {
                Q_EMIT uploadingFailed(localUrl, map.value(QLatin1String("error")).toString());
            } else {
                if (PosterousSettings::oauth()) {
                    Q_EMIT mediumUploaded(localUrl, map.value(QLatin1String("url")).toString());
                }
                if (PosterousSettings::basic()) {
                    Q_EMIT mediumUploaded(localUrl, map.value(QLatin1String("full_url")).toString());
                }
            }
        } else {
            Q_EMIT uploadingFailed(localUrl, i18n("Malformed response"));
            qWarning() << "Parse error:" << stj->data();
        }
    }
}
Exemplo n.º 17
0
Client::CodeRes Client::code(const string &query, const string &repo = NULL)
{
    // This is the method that we will call from the Query class.
    // It connects to an HTTP source and returns the results.

    // In this case we are going to retrieve JSON data.
    QJsonDocument root;

    // Build a URI and get the contents.
    // The fist parameter forms the path part of the URI.
    // The second parameter forms the CGI parameters.
    get(
    { "search", "code" },
    { { "q", query + "+repo:" + repo } },
                root);
    // e.g. http://api.openweathermap.org/data/2.5/weather?q=QUERY&units=metric

    CodeRes result;

    // Read out the city we found
    QVariantMap variant = root.toVariant().toMap();
    result.total_count = variant["total_count"].toUInt();

    // Read the Users
    QVariantList items = variant["items"].toList();
    for (const QVariant &i : items) {
        QVariantMap item = i.toMap();
        QVariantMap repository = item["repository"].toMap();
        QVariantMap owner = repository["owner"].toMap();
        result.codes.emplace_back(
                    Code {
                        item["name"].toString().toStdString(),
                        item["path"].toString().toStdString(),
                        item["html_url"].toString().toStdString(),
                        Repository {
                            Owner {
                                owner["login"].toString().toStdString(),
                                owner["id"].toUInt(),
                                owner["avatar_url"].toString().toStdString(),
                                owner["html_url"].toString().toStdString()
                            },
                            repository["name"].toString().toStdString(),
                            repository["full_name"].toString().toStdString(),
                            repository["description"].toString().toStdString(),
                            repository["private"].toBool(),
                            repository["fork"].toBool(),
                            repository["html_url"].toString().toStdString(),
                            repository["language"].toString().toStdString(),
                            repository["forks_count"].toUInt(),
                            repository["stargazers_count"].toUInt(),
                            repository["watchers_count"].toUInt(),
                            repository["open_issues_count"].toUInt(),
                            repository["created_at"].toString().toStdString(),
                            repository["pushed_at"].toString().toStdString()
                        }
                    }
                    );
    }
    return result;
}
Exemplo n.º 18
0
    virtual void OnObserve(const char* aTopic, const PRUnichar* aData) {
        // LOGT("aTopic: %s, data: %s", aTopic, NS_ConvertUTF16toUTF8(aData).get());
        QString data((QChar*)aData);
        if (!data.startsWith('{') && !data.startsWith('[') && !data.startsWith('"')) {
            QVariant vdata = QVariant::fromValue(data);
            Q_EMIT q->recvObserve(aTopic, vdata);
            return;
        }
        bool ok = true;
#if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0))
        QJson::Parser parser;
        QVariant vdata = parser.parse(data.toUtf8(), &ok);
#else
        QJsonParseError error;
        QJsonDocument doc = QJsonDocument::fromJson(data.toUtf8(), &error);
        ok = error.error == QJsonParseError::NoError;
        QVariant vdata = doc.toVariant();
#endif
        if (ok) {
            // LOGT("mesg:%s, data:%s", aTopic, data.toUtf8().data());
            Q_EMIT q->recvObserve(aTopic, vdata);
        } else {
#if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0))
            LOGT("parse: s:'%s', err:%s, errLine:%i", data.toUtf8().data(), parser.errorString().toUtf8().data(), parser.errorLine());
#else
            LOGT("parse: s:'%s', err:%s, errLine:%i", data.toUtf8().data(), error.errorString().toUtf8().data(), error.offset);
#endif
        }
    }
Exemplo n.º 19
0
Client::RepositoryRes Client::repositories(const string& query,
                                           bool name, bool description, bool readme) {
    // This is the method that we will call from the Query class.
    // It connects to an HTTP source and returns the results.


    // In this case we are going to retrieve JSON data.
    QJsonDocument root;

    // Build a URI and get the contents.
    // The fist parameter forms the path part of the URI.
    // The second parameter forms the CGI parameters.
    std::string in = "+in:";
    if(name) in += "name,";
    if(description) in += "description,";
    if(readme) in += "readme,";
    in = in.substr(0, in.size()-1);
    get(
    { "search", "repositories" },
    { { "q", query + in } },
                root);
    // e.g. http://api.openweathermap.org/data/2.5/weather?q=QUERY&units=metric

    RepositoryRes result;

    // Read out the city we found
    QVariantMap variant = root.toVariant().toMap();
    result.total_count = variant["total_count"].toUInt();

    // Read the Users
    QVariantList items = variant["items"].toList();
    for (const QVariant &i : items) {
        QVariantMap item = i.toMap();
        QVariantMap owner = item["owner"].toMap();
        result.repositories.emplace_back(
                    Repository {
                        Owner {
                            owner["login"].toString().toStdString(),
                            owner["id"].toUInt(),
                            owner["avatar_url"].toString().toStdString(),
                            owner["html_url"].toString().toStdString()
                        },
                        item["name"].toString().toStdString(),
                        item["full_name"].toString().toStdString(),
                        item["description"].toString().toStdString(),
                        item["private"].toBool(),
                        item["fork"].toBool(),
                        item["html_url"].toString().toStdString(),
                        item["language"].toString().toStdString(),
                        item["forks_count"].toUInt(),
                        item["stargazers_count"].toUInt(),
                        item["watchers_count"].toUInt(),
                        item["open_issues_count"].toUInt(),
                        item["created_at"].toString().toStdString(),
                        item["pushed_at"].toString().toStdString()
                    }
                    );
    }
    return result;
}
Exemplo n.º 20
0
void OpenSearchEngine::suggestionsObtained()
{
    const QByteArray response = m_suggestionsReply->readAll();

    m_suggestionsReply->close();
    m_suggestionsReply->deleteLater();
    m_suggestionsReply = 0;

    QJsonParseError err;
    QJsonDocument json = QJsonDocument::fromJson(response, &err);
    const QVariant res = json.toVariant();

    if (err.error != QJsonParseError::NoError || res.type() != QVariant::List)
        return;

    const QVariantList list = res.toList();

    if (list.size() < 2)
        return;

    QStringList out;

    foreach (const QVariant &v, list.at(1).toList())
        out.append(v.toString());

    emit suggestions(out);
}
Exemplo n.º 21
0
void NetLogicMainProcess::task(NetCommunicationModule &NCM)
{
	QTcpSocket *sock = NCM.sock;
	QJsonParseError error;
	QJsonDocument jsonDocument = QJsonDocument::fromJson(NCM.data, &error);
	if (error.error != QJsonParseError::NoError){
		qDebug() << "json parse error! in" << __FUNCSIG__;
		qDebug() << "data of recieving is :\"" << NCM.data << "\"";
		return;
	}
	QVariantMap data = jsonDocument.toVariant().toMap();
	int protocol = Packet::Protocol(data);
	auto pck = net::get(protocol);
	if (!pck){
		qDebug() << "非法协议号:" << protocol;
	}
	pck->write(data);

	//事务开始
	static Error err;
	err.opt() = protocol;
	transactionObject->lock(pck, sock, &err);
	try{
		(transactionObject->*transactionObject->getTransactionMap()[(NetCommunicationProtocol)protocol])();
	}
	catch (...){
		qDebug() << "事务出现错误!协议号:" << protocol << "协议语言:" << net::ProtocolToString(protocol);
		return;
	}
	//事务结束
	anyPacket = transactionObject->unlockForResponse();

	//处理Error,发送ServerBackPacket AND 客户端需要的数据
	this->sendMsgDependsOnError(&err, sock);
}
Exemplo n.º 22
0
void ExtScript::readJsonFilters()
{
    QString fileName = QStandardPaths::locate(
        QStandardPaths::GenericDataLocation,
        QString(
            "awesomewidgets/scripts/awesomewidgets-extscripts-filters.json"));
    qCInfo(LOG_LIB) << "Filters file" << fileName;
    QFile jsonFile(fileName);
    if (!jsonFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qCWarning(LOG_LIB) << "Could not open" << fileName;
        return;
    }
    QString jsonText = jsonFile.readAll();
    jsonFile.close();

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

    qCInfo(LOG_LIB) << "Filters" << jsonFilters;
}
Exemplo n.º 23
0
Client::Email Client::send_message(const Client::Contact& to, const std::string& subject,
                                   const std::string& body, const std::string& from_name,
                                   const std::string& ref_id, const std::string& thread_id) {
    QByteArray message;
    Contact from;
    from.address = users_address();
    from.name = from_name;

    add_rfc822_header(message, "In-Reply-To: " + ref_id);
    add_rfc822_header(message, "References: " + ref_id);
    if (from.address != "")
        add_rfc822_header(message, "From: " + rfc822_address(from));
    // Otherwise, Google will add a From header for us.
    add_rfc822_header(message, "To: " + rfc822_address(to));
    add_rfc822_header(message, "Subject: " + encode_rfc2074(subject));
    end_rfc822_header(message, config_->user_agent);
    add_rfc822_body(message, body);

    std::string request_body = "{ \"raw\": \"" +
            std::string(message.toBase64(QByteArray::Base64UrlEncoding).constData()) +
            "\", \"threadId\": \"" + thread_id + "\" }";
    std::cerr << request_body << std::endl;
    QJsonDocument root;
    post({ "users", "me", "messages", "send" }, {}, request_body, root);
    return parse_email(root.toVariant());
}
void DevicePluginNetworkInfo::actionDataReady(const ActionId &actionId, const QByteArray &data)
{
    // Convert the rawdata to a json document
    QJsonParseError error;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &error);

    // Check if we got a valid JSON document
    if(error.error != QJsonParseError::NoError) {
        qCWarning(dcNetworkInfo) << "Failed to parse JSON data" << data << ":" << error.errorString();

        // the action execution is finished, and was not successfully
        emit actionExecutionFinished(actionId, DeviceManager::DeviceErrorHardwareFailure);
        return;
    }

    // print the fetched data in json format to stdout
    qCDebug(dcNetworkInfo) << jsonDoc.toJson();

    // Get the device for this action
    Device *device = m_asyncActions.take(actionId);

    // Parse the data and update the states of our device
    QVariantMap dataMap = jsonDoc.toVariant().toMap();

    // Set the city state
    if (dataMap.contains("city")) {
        device->setStateValue(cityStateTypeId, dataMap.value("city").toString());
    }

    // Set the country state
    if (dataMap.contains("countryCode")) {
        device->setStateValue(countryStateTypeId, dataMap.value("countryCode").toString());
    }

    // Set the wan ip
    if (dataMap.contains("query")) {
        device->setStateValue(addressStateTypeId, dataMap.value("query").toString());
    }

    // Set the time zone state
    if (dataMap.contains("timezone")) {
        device->setStateValue(timeZoneStateTypeId, dataMap.value("timezone").toString());
    }

    // Set the longitude state
    if (dataMap.contains("lon")) {
        device->setStateValue(lonStateTypeId, dataMap.value("lon").toDouble());
    }

    // Set the latitude state
    if (dataMap.contains("lat")) {
        device->setStateValue(latStateTypeId, dataMap.value("lat").toDouble());
    }

    qCDebug(dcNetworkInfo) << "Action" << actionId << "execution finished successfully.";

    // Emit the successfull action execution result to the device manager
    emit actionExecutionFinished(actionId, DeviceManager::DeviceErrorNoError);
}
Exemplo n.º 25
0
std::string Client::users_address() {
    if (config_->users_address.empty()) {
        QJsonDocument root;
        get({ "users", "me", "profile" }, {}, root);
        config_->users_address = root.toVariant().toMap()["emailAddress"].toString().toStdString();
    }
    return config_->users_address;
}
Exemplo n.º 26
0
QList<Course> IversityClient::courses(const QString &query)
{
    QList<Course> list;

    QByteArray data;
    net::Uri::Path path;
    net::Uri::QueryParameters params;

    qCDebug(Iversity) << "Download started...";
    if (data.isNull())
        get( path, params, data);
    qCDebug(Iversity) << "Data received:" << data.length() << "bytes";
    QJsonDocument root = QJsonDocument::fromJson(data);

    QVariantMap variant = root.toVariant().toMap();
    QList<QVariant> courses = variant["courses"].toList();
    qCDebug(Iversity) << "Element count:" << courses.length();

    SearchEngine se(query);

    for (const QVariant &i : courses)
    {
        QVariantMap map = i.toMap();

        Course course;
        course.id = map["id"].toString();
        course.slug = map["url"].toString();
        course.title = map["title"].toString();
        course.description = map["description"].toString();
        course.headline = map["subtitle"].toString();
        course.art = map["cover"].toString();
        course.link = map["url"].toString();
        course.extra = grabExtra(map);
        course.video = map["trailer_video"].toString();

        QList<QVariant> instructors = map["instructors"].toList();
        for (const QVariant& j : instructors)
        {
            QVariantMap imap = j.toMap();
            Instructor instr;
            instr.image = imap["image"].toString();
            instr.bio = imap["biography"].toString();
            instr.name = imap["name"].toString();

            course.instructors.append(instr);
        }

        course.departments.append(map["discipline"].toString());

        //qCDebug(Iversity) << "Category count: " << course.departments;
        //qCDebug(Iversity) << "Instr count: " << course.instructors.size();
        if (query.isEmpty() || se.isMatch(course))
            list.append(course);
    }

    return list;
}
QVariant TaskScheduler::loadFromFile(QString fileName)
{
    QFile file(fileName);
    file.open(QIODevice::ReadOnly);
    QByteArray fileContent = file.readAll();
    QJsonDocument document = QJsonDocument::fromJson(fileContent);
    file.close();
    return document.toVariant();
}
Exemplo n.º 28
0
void Server::processRequest(const QList<QByteArray> &request)
{
    static quint64 counter = 0;
    counter++;
//    qDebug() << "Replier::requestReceived> " << counter << request;

    QJsonDocument doc = QJsonDocument::fromJson(request[0]);
    emit requestReceived(doc.toVariant());

}
void QSerienJunkiesReply::seriesSearchReplyFinished()
{
    QNetworkReply *reply = static_cast<QNetworkReply *>(sender());
    if(!reply)
        return;

    QJsonParseError jsonError;
    QJsonDocument jsonDocument = QJsonDocument::fromJson(reply->readAll(), &jsonError);
    reply->deleteLater();
    reply = nullptr;

    if(jsonError.error != QJsonParseError::NoError) {
        data->errorString = "The returned JSON was not valid: "+jsonError.errorString();
        emit error();
        return;
    }

    QVariant v = jsonDocument.toVariant();
    if(static_cast<QMetaType::Type>(v.type()) != QMetaType::QVariantList) {
        data->errorString = "The returned JSON is no list.";
        emit error();
        return;
    }

    QVariantList resultList = v.toList();
    data->seasonCount = resultList.size();

    if(data->seasonCount == 0) {
        emit finished();
        return;
    }

    // Get the given URLs, because the actual URL of a series is in the "Location" header of these URLs.
    foreach(QVariant result, resultList) {
        QVariantList list = result.toList();
        if(list.size() != 2)
            continue;
        Series r;
        r.id = list.at(0).toInt();
        r.name = list.at(1).toString();
        data->series.append(r);

        QUrl url(QString("http://serienjunkies.org/?cat=%1").arg(r.id));
        QNetworkReply *locationReply = QSerienJunkies::networkAccessManager()->get(QNetworkRequest(url));
        locationReply->setProperty("index", data->series.size() - 1);

        QObject::connect(locationReply, &QNetworkReply::finished,
                         this, &QSerienJunkiesReply::seriesLocationReplyFinished);

        QObject::connect(locationReply, SIGNAL(error(QNetworkReply::NetworkError)),
                         this, SLOT(onError()));

        QObject::connect(this, &QObject::destroyed,
                         locationReply, &QNetworkReply::deleteLater);
    }
Exemplo n.º 30
0
Client::UserRes Client::users(const string& query) {
    // This is the method that we will call from the Query class.
    // It connects to an HTTP source and returns the results.


    // In this case we are going to retrieve JSON data.
    QJsonDocument root;

    // Build a URI and get the contents.
    // The fist parameter forms the path part of the URI.
    // The second parameter forms the CGI parameters.
    get(
    { "search", "users" },
    { { "q", query } },
                root);
    // e.g. http://api.openweathermap.org/data/2.5/weather?q=QUERY&units=metric

    UserRes result;

    // Read out the city we found
    QVariantMap variant = root.toVariant().toMap();
    result.total_count = variant["total_count"].toUInt();

    // Read the Users
    QVariantList items = variant["items"].toList();//.first().toMap();
    for (const QVariant &i : items) {
        QVariantMap item = i.toMap();
        result.users.emplace_back(
                    User {
                        item["id"].toUInt(),
                        item["avatar_url"].toString().toStdString(),
                        item["html_url"].toString().toStdString(),
                        item["followers_url"].toString().toStdString(),
                        item["following_url"].toString().toStdString(),
                        item["gists_url"].toString().toStdString(),
                        item["starred_url"].toString().toStdString(),
                        item["organizations_url"].toString().toStdString(),
                        item["repos_url"].toString().toStdString(),
                        item["name"].toString().toStdString(),
                        item["company"].toString().toStdString(),
                        item["blog"].toString().toStdString(),
                        item["location"].toString().toStdString(),
                        item["email"].toString().toStdString(),
                        item["hireable"].toBool(),
                        item["bio"].toString().toStdString(),
                        item["public_repos"].toUInt(),
                        item["public_gists"].toUInt(),
                        item["followers"].toUInt(),
                        item["following"].toUInt()
                    }
                    );
    }
    return result;
}