void ArtistBiography::FetchWikipediaImages(int id, const QString& wikipedia_url,
                                           CountdownLatch* latch) {
  latch->Wait();
  qLog(Debug) << wikipedia_url;
  QRegExp regex("([a-z]+)\\.wikipedia\\.org/wiki/(.*)");
  if (regex.indexIn(wikipedia_url) == -1) {
    emit Finished(id);
    return;
  }
  QString wiki_title = QUrl::fromPercentEncoding(regex.cap(2).toUtf8());
  QString language = regex.cap(1);
  QUrl url(QString(kWikipediaImageListUrl).arg(language));
  url.addQueryItem("titles", wiki_title);

  qLog(Debug) << "Wikipedia images:" << url;

  QNetworkRequest request(url);
  QNetworkReply* reply = network_->get(request);
  NewClosure(reply, SIGNAL(finished()), [this, id, reply, language, latch]() {
    reply->deleteLater();

    QJson::Parser parser;
    QVariantMap response = parser.parse(reply).toMap();

    QStringList image_titles = ExtractImageTitles(response);

    for (const QString& image_title : image_titles) {
      latch->Wait();
      QUrl url(QString(kWikipediaImageInfoUrl).arg(language));
      url.addQueryItem("titles", image_title);
      qLog(Debug) << "Image info:" << url;

      QNetworkRequest request(url);
      QNetworkReply* reply = network_->get(request);
      NewClosure(reply, SIGNAL(finished()), [this, id, reply, latch]() {
        reply->deleteLater();
        QJson::Parser parser;
        QVariantMap json = parser.parse(reply).toMap();
        QUrl url = ExtractImageUrl(json);
        qLog(Debug) << "Found wikipedia image url:" << url;
        if (!url.isEmpty()) {
          emit ImageReady(id, url);
        }
        latch->CountDown();
      });
    }

    latch->CountDown();
  });
}
Exemple #2
0
QVariant decode(const QByteArray &token, const QByteArray &key)
{
	if(!QCA::isSupported("hmac(sha256)"))
		return QVariant();

	int at = token.indexOf('.');
	if(at == -1)
		return QVariant();

	QByteArray headerPart = token.mid(0, at);

	++at;
	int start = at;
	at = token.indexOf('.', start);
	if(at == -1)
		return QVariant();

	QByteArray claimPart = token.mid(start, at - start);
	QByteArray sig = token.mid(at + 1);

	bool ok;
	QJson::Parser parser;

	QByteArray headerJson = unbase64url(headerPart);
	if(headerJson.isEmpty())
		return QVariant();

	QVariant headerObj = parser.parse(headerJson, &ok);
	if(!ok || headerObj.type() != QVariant::Map)
		return QVariant();

	QVariantMap header = headerObj.toMap();
	if(header.value("typ").toString() != "JWT" || header.value("alg").toString() != "HS256")
		return QVariant();

	QByteArray claimJson = unbase64url(claimPart);
	if(claimJson.isEmpty())
		return QVariant();

	QVariant claim = parser.parse(claimJson, &ok);
	if(!ok)
		return QVariant();

	if(jws_sign(headerPart, claimPart, key) != sig)
		return QVariant();

	return claim;
}
void PlacesDataManager::
replyFinished(QNetworkReply * reply) const
{
    QApplication::restoreOverrideCursor();

    if( existsReplyError(reply) ) return;

    QString strUrl = reply->url().toString();
    QString data = reply->readAll();

    //qDebug() << Q_FUNC_INFO << "\n" << reply->operation() <<  strUrl << "\n" << data;

    QObject * origObject = reply->request().originatingObject();


    //it's ok, just simple usage of QNetworkAccessManager, without DataManagerHelper
    if( ! origObject ) {
        //qDebug() << "empty originating Object...";
        //qDebug() << "try simple work with result";
        //qDebug() << data;

        QJson::Parser parser;
        bool ok;
        // json is a QString containing the data to convert
        QVariant result = parser.parse (data.toLatin1(), &ok);
        if(!ok)
        {
            emit errorOccured(QString("Cannot convert to QJson object: %1").arg(data));
            return;
        }

        int code = result.toMap()["Status"].toMap()["code"].toInt();
        if(code != 200 && code != 0)
        {
            emit errorOccured(QString("Code of request is: %1").arg(code));
            return;
        }
        QVariantList placeMarks = result.toMap()["Placemark"].toList();
        if (!placeMarks.empty())
        {
            double east  = placeMarks[0].toMap()["Point"].toMap()["coordinates"].toList()[0].toDouble();
            double north = placeMarks[0].toMap()["Point"].toMap()["coordinates"].toList()[1].toDouble();

            QString str = QString::number(north)+","+QString::number(east);
            emit findCoordinatesByAddress(str);

        }
        return;
    }

    DataManagerHelper * helper = qobject_cast<DataManagerHelper*>(origObject);
    if( ! helper ) {
        //qDebug() << "empty helper Object...";
        return;
    }

    //qDebug() << "Helper object present." ;
    helper->evalData(data);
    helper->deleteLater();
}
Exemple #4
0
void
GrooveClient::Private::processSessionToken ()
{
  QNetworkReply *reply = qobject_cast<QNetworkReply *> (sender ());

  if (GROOVE_VERIFY (reply, "called without a QNetworkReply as sender"))
    return;

  bool ok;
  QJson::Parser parser;

  QByteArray sessionTokenReply = reply->readAll ();
  QVariantMap result = parser.parse (sessionTokenReply, &ok).toMap ();

  if (!ok)
    LDEBUG << "Session token request failed:" << sessionTokenReply;

  GROOVE_VERIFY_OR_DIE (ok, "couldn't parse reply to session token request");
  GROOVE_VERIFY_OR_DIE (result["message"].toString ().isEmpty (), qPrintable (result["message"].toString ()));

  m_sessionToken = result["result"].toString ();
  LDEBUG << "Got session token: " << m_sessionToken;

  if (!m_sessionToken.length ())
    {
      LDEBUG << "Session token empty:";
      LDEBUG << sessionTokenReply;
      LDEBUG << reply->errorString ();
    }

  emit connected ();
}
bool FilterRectangleRequestJSON::parseJson(const QByteArray&data)
{
  clearContainers();
  FilterRequestJSON::parseJson(data);

  QJson::Parser parser;
  bool ok;
  QVariantMap result = parser.parse(data, &ok).toMap();
  if (!ok) return false;
  QString auth_token = result["auth_token"].toString();
  setTimeFrom(QDateTime::fromString(result["time_from"].toString(), "dd MM yyyy HH:mm:ss.zzz"));
  setTimeTo(QDateTime::fromString(result["time_to"].toString(), "dd MM yyyy HH:mm:ss.zzz"));

  double lat1, lat2, lon1, lon2;
  QVariantMap latData = result["latitude_shift"].toMap();
  lat1 = latData["latitude1"].toDouble(&ok);
  if (!ok) return false;

  lat2 = latData["latitude2"].toDouble(&ok);
  if (!ok) return false;

  QVariantMap lonData = result["longitude_shift"].toMap();
  lon1 = lonData["longitude1"].toDouble(&ok);
  if (!ok) return false;

  lon2 = lonData["longitude2"].toDouble(&ok);
  if (!ok) return false;

  syslog(LOG_INFO, "rect %f ,%f ,%f ,%f ", lat1, lat2, lon2, lon2);

  FShapeRectangle * shape = new FShapeRectangle(lat1, lon1, lat2, lon2);
  setShape(QSharedPointer<FShape>(shape));
  m_sessionsContainer->push_back(QSharedPointer<Session>(new JsonSession(auth_token, QDateTime::currentDateTime(), QSharedPointer<common::User>(NULL))));
  return true;
}
bool FilterPolygonRequestJSON::parseJson(const QByteArray&data)
{
  clearContainers();
  FilterRequestJSON::parseJson(data);

  QJson::Parser parser;
  bool ok;
  QVariantMap result = parser.parse(data, &ok).toMap();
  if (!ok) return false;

  QString auth_token = result["auth_token"].toString();
  setTimeFrom(QDateTime::fromString(result["time_from"].toString(), "dd MM yyyy HH:mm:ss.zzz"));
  setTimeTo(QDateTime::fromString(result["time_to"].toString(), "dd MM yyyy HH:mm:ss.zzz"));

  FShapePolygon * shape = new FShapePolygon();
  QVariantList polygon = result["polygon"].toList();
  for (int i = 0; i < polygon.size(); i++)
  {
    QVariantMap p = polygon.at(i).toMap();
    int number = p["number"].toInt(&ok);
    if (!ok) return false;

    double lat = p["latitude"].toDouble(&ok);
    if (!ok) return false;

    double lon = p["longitude"].toDouble(&ok);
    if (!ok) return false;

    shape->addPoint(number, lat, lon);
  }
  setShape(QSharedPointer<FShape>(shape));
  m_sessionsContainer->push_back(QSharedPointer<Session>(new JsonSession(auth_token, QDateTime::currentDateTime(), QSharedPointer<common::User>(NULL))));
  return true;
}
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;
}
/**
 * From JSON
 */
WorkModel * WorkModel::fromJSON(QString *jsonString) {
	QJson::Parser parser;
	QVariant variant = parser.parse(jsonString->toUtf8());
	WorkModel *workModel = new WorkModel();
	QJson::QObjectHelper::qvariant2qobject(variant.toMap(), workModel);
	return workModel;
}
Exemple #9
0
bool WriteTagRequestJSON::parseJson(const QByteArray &data)
{
  clearContainers();
  QJson::Parser parser;
  bool ok;
  QVariantMap result = parser.parse(data, &ok).toMap();
  if (!ok) return false;

  QString auth_token = result["auth_token"].toString();
  QString channel_name = result["channel"].toString();
  QString title = result["title"].toString();
  QString link = result["link"].toString();
  QString description = result["description"].toString();
  double altitude = result["altitude"].toDouble(&ok);
  if (!ok) return false;
  double longitude = result["longitude"].toDouble(&ok);
  if (!ok) return false;

  double latitude = result["latitude"].toDouble(&ok);
  if (!ok) return false;

  QDateTime time = QDateTime::fromString(result["time"].toString(), "dd MM yyyy HH:mm:ss.zzz");

  Session session(auth_token, QDateTime::currentDateTime(), common::BasicUser());
  Channel channel(channel_name, "unknown");

  Tag tag(altitude, latitude, longitude, title, description, link, time);
  tag.setChannel(channel);
  //tag.setSession(session);
  m_channels.push_back(channel);
  m_token = auth_token;
  m_tags.push_back(tag);

  return true;
}
Exemple #10
0
bool WriteTagRequestJSON::parseJson(const QByteArray &data)
{
  clearContainers();
  QJson::Parser parser;
  bool ok;
  QVariantMap result = parser.parse(data, &ok).toMap();
  if (!ok) return false;

  QString auth_token = result["auth_token"].toString();
  QString channel_name = result["channel"].toString();
  QString title = result["title"].toString();
  QString link = result["link"].toString();
  QString description = result["description"].toString();
  double altitude = result["altitude"].toDouble(&ok);
  if (!ok) return false;
  double longitude = result["longitude"].toDouble(&ok);
  if (!ok) return false;

  double latitude = result["latitude"].toDouble(&ok);
  if (!ok) return false;

  QDateTime time = QDateTime::fromString(result["time"].toString(), "dd MM yyyy HH:mm:ss.zzz");

  QSharedPointer<Session> session(new JsonSession(auth_token, QDateTime::currentDateTime(), QSharedPointer<common::User>(NULL)));
  QSharedPointer<Channel> channel(new JsonChannel(channel_name, "unknown"));

  QSharedPointer<DataMark> tag(new JsonDataMark(altitude, latitude, longitude, title, description, link, time));
  //tag->setChannel(channel);
  //tag->setSession(session);
  m_channelsContainer->push_back(channel);
  m_sessionsContainer->push_back(session);
  m_tagsContainer->push_back(tag);

  return true;
}
void MusicKWBackgroundThread::downLoadDataFinished(const QByteArray &bytes)
{
    QJson::Parser parser;
    bool ok;

    if(bytes != "NO_PIC")
    {
        QVariant data = parser.parse(bytes, &ok);
        if(ok)
        {
            QVariantMap dataMap = data.toMap();
            QVariantList datas = dataMap["array"].toList();
            foreach(const QVariant &value, datas)
            {
                dataMap = value.toMap();
                if(m_counter < 5 && !dataMap.isEmpty())
                {
                    QString url = dataMap.values().first().toString();
                    M_LOGGER_ERROR(url);
                    MusicDataDownloadThread *download = new MusicDataDownloadThread(url, QString("%1%2%3%4").arg(BACKGROUND_DIR_FULL)
                                                            .arg(m_savePath).arg(m_counter++).arg(SKN_FILE),
                                                            MusicDownLoadThreadAbstract::DownloadBigBG, this);
                    connect(download, SIGNAL(downLoadDataChanged(QString)), SLOT(downLoadFinished()));
                    download->startToDownload();
                }
            }
        }
Exemple #12
0
void LinTORManager::receiveAuthToken()
{
  QJson::Parser parser;

  bool ok;

  QVariantMap result = parser.parse(authReply->readAll(), &ok).toMap();

  authReply->deleteLater();
  authReply = 0;

  if (!ok)
  {
    qWarning() << "Failed to parse The Old Reader authorization data";
    emit loginFailed();
    return;
  }

  authToken = result["Auth"].toString();

  authHeaderString = "GoogleLogin auth=";
  authHeaderString += authToken;

  qDebug() << "Authentication: " << authHeaderString;

  // Initialize the display:
  getFolders();
//  getUnread();
//  getSubscriptions();
}
DigitallyImportedClient::ChannelList
DigitallyImportedClient::ParseChannelList(QNetworkReply* reply) const {
  ChannelList ret;

  QJson::Parser parser;
  QVariantMap data = parser.parse(reply).toMap();

  if (!data.contains("channel_filters"))
    return ret;

  QVariantList filters = data["channel_filters"].toList();

  foreach (const QVariant& filter, filters) {
    // Find the filter called "All"
    QVariantMap filter_map = filter.toMap();
    if (filter_map.value("name", QString()).toString() != "All")
      continue;

    // Add all its stations to the result
    QVariantList channels = filter_map.value("channels", QVariantList()).toList();
    foreach (const QVariant& channel_var, channels) {
      QVariantMap channel_map = channel_var.toMap();

      Channel channel;
      channel.art_url_ = QUrl(channel_map.value("asset_url").toString());
      channel.description_ = channel_map.value("description").toString();
      channel.director_ = channel_map.value("channel_director").toString();
      channel.key_ = channel_map.value("key").toString();
      channel.name_ = channel_map.value("name").toString();
      ret << channel;
    }
Exemple #14
0
void LinTORManager::collectItems()
{
  // Marshall the current item:
  QJson::Parser parser;
  bool ok;
  QVariantMap result = parser.parse(torItemReply->readAll(), &ok).toMap();
  torItemReply->deleteLater();
  torItemReply = 0;

  if (!ok)
  {
    qWarning() << "Failed to parse The Old Reader item contents";
    return;
  }

  // Try to pull the usable bits out of the item contents:
  QList<QVariant> itemsVariants = result["items"].toList();

  QList<QVariant>::const_iterator index = itemsVariants.constBegin();
  QList<QVariant>::const_iterator end = itemsVariants.constEnd();

  while (index != end)
  {
    QVariantMap itemMap = (*index).toMap();

    LinTORItem item;

    item.setTitle(itemMap["title"].toString());

    QList<QVariant> canonicalList = itemMap["canonical"].toList();

    // For now, just pull the first item out of the list:
    if (!canonicalList.isEmpty())
    {
      QVariantMap canonicalMap = canonicalList.first().toMap();
      item.setSourceUrl(canonicalMap["href"].toString());
    }

    QList<QVariant> enclosureList = itemMap["enclosure"].toList();

    // For now, just pull the first item out of the list:
    if (!enclosureList.isEmpty())
    {
      QVariantMap enclosureMap = enclosureList.first().toMap();

      item.setEnclosureUrl(enclosureMap["href"].toString());
      item.setEnclosureType(enclosureMap["type"].toString());
    }

    QVariantMap summaryMap = itemMap["summary"].toMap();

    item.setSummary(summaryMap["content"].toString());

    torItems[itemMap["id"].toString()] = item;

    ++index;
  }

  emit itemsReady();
}
Exemple #15
0
void DBTalker::parseResponseAddPhoto(const QByteArray& data)
{
    bool success        = false;
    QJson::Parser parser;
    bool ok;
    QVariant result     = parser.parse(data, &ok);
    QVariantMap rmap    = result.toMap();
    QList<QString> keys = rmap.uniqueKeys();

    for(int i=0;i<rmap.size();i++)
    {
        if(keys[i] == "bytes")
        {
            success = true;
            break;
        }
    }

    emit signalBusy(false);

    if(!success)
    {
        emit signalAddPhotoFailed(i18n("Failed to upload photo"));
    }
    else
    {
        emit signalAddPhotoSucceeded();
    }
}
void MusicIdentifySongsThread::downLoadFinished()
{
    m_songIdentifys.clear();
    if(m_reply && m_reply->error() == QNetworkReply::NoError)
    {
        QJson::Parser parser;
        bool ok;
        QVariant data = parser.parse(m_reply->readAll(), &ok);
        if(ok)
        {
            QVariantMap value = data.toMap();
            if(value.contains("metadata"))
            {
                value = value["metadata"].toMap();
                QVariantList list = value["music"].toList();
                foreach(const QVariant &var, list)
                {
                    value = var.toMap();

                    MusicSongIdentify song;
                    song.m_songName = value["title"].toString();
                    foreach(const QVariant &artists, value["artists"].toList())
                    {
                        value = artists.toMap();
                        song.m_singerName = value["name"].toString();
                        break;
                    }
                    m_songIdentifys << song;
                    break;
                }
            }
Exemple #17
0
void FbTalker::parseExchangeSession(const QByteArray& data)
{
    int errCode = -1;
    QString errMsg;
    bool ok;
    QJson::Parser parser;

    kDebug() << "Parse exchange_session response:" << endl << data;

    QVariantList result = parser.parse (data, &ok).toList();

    if(ok)
    {
        QVariantMap session = result[0].toMap();
        m_accessToken       = session["access_token"].toString();
        m_sessionExpires    = session["expires"].toUInt();
        if( m_sessionExpires != 0 ) {
#if QT_VERSION >= 0x40700
            m_sessionExpires += QDateTime::currentMSecsSinceEpoch() / 1000;
#else
            m_sessionExpires += QDateTime::currentDateTime().toTime_t();
#endif
        }
        if( m_accessToken.isEmpty() )
            // Session did not convert. Reauthenticate.
            doOAuth();
        else
            // Session converted to OAuth. Proceed normally.
            getLoggedInUser();
    }
    else
    {
        authenticationDone(errCode, errorToText(errCode, errMsg));
    }
}
Exemple #18
0
void QgsAmsLegendFetcher::handleFinished()
{
  // Parse result
  QJson::Parser parser;
  bool ok = false;
  QVariantMap queryResults = parser.parse( mQueryReply, &ok ).toMap();
  if ( !ok )
  {
    emit error( QString( "Parsing error at line %1: %2" ).arg( parser.errorLine() ).arg( parser.errorString() ) );
  }
  QgsDataSourceURI dataSource( mProvider->dataSourceUri() );
  QList< QPair<QString, QImage> > legendEntries;
  foreach ( const QVariant& result, queryResults["layers"].toList() )
  {
    QVariantMap queryResultMap = result.toMap();
    QString layerId = queryResultMap["layerId"].toString();
    if ( layerId != dataSource.param( "layer" ) && !mProvider->subLayers().contains( layerId ) )
    {
      continue;
    }
    QVariantList legendSymbols = queryResultMap["legend"].toList();
    foreach ( const QVariant& legendEntry, legendSymbols )
    {
      QVariantMap legendEntryMap = legendEntry.toMap();
      QString label = legendEntryMap["label"].toString();
      if ( label.isEmpty() && legendSymbols.size() == 1 )
        label = queryResultMap["layerName"].toString();
      QByteArray imageData = QByteArray::fromBase64( legendEntryMap["imageData"].toByteArray() );
      legendEntries.append( qMakePair( label, QImage::fromData( imageData ) ) );
    }
  }
void
HatchetSipPlugin::messageReceived( const QByteArray &msg )
{
    tDebug( LOGVERBOSE ) << Q_FUNC_INFO << "WebSocket message: " << msg;

    QJson::Parser parser;
    bool ok;
    QVariant jsonVariant = parser.parse( msg, &ok );
    if ( !jsonVariant.isValid() )
    {
        tLog() << Q_FUNC_INFO << "Failed to parse message back from server";
        return;
    }

    QVariantMap retMap = jsonVariant.toMap();

    if ( m_sipState == AcquiringVersion )
    {
        tLog() << Q_FUNC_INFO << "In acquiring version state, expecting versioninformation";
        if ( !retMap.contains( "version" ) )
        {
            tLog() << Q_FUNC_INFO << "Failed to acquire version information";
            disconnectPlugin();
            return;
        }
        bool ok = false;
        int ver = retMap[ "version" ].toInt( &ok );
        if ( ver == 0 || !ok )
        {
            tLog() << Q_FUNC_INFO << "Failed to acquire version information";
            disconnectPlugin();
            return;
        }

        /*
        if ( retMap[ "nonce" ].toString() != m_uuid )
        {
            tLog() << Q_FUNC_INFO << "Failed to validate nonce";
            disconnectPlugin();
            return;
        }
        */

        m_version = ver;

        QVariantMap registerMap;
        registerMap[ "command" ] = "register";
        registerMap[ "token" ] = m_token;
        registerMap[ "dbid" ] = Tomahawk::Database::instance()->impl()->dbid();
        registerMap[ "alias" ] = QHostInfo::localHostName();

        QList< SipInfo > sipinfos = Servent::instance()->getLocalSipInfos( "default", "default" );
        QVariantList hostinfos;
        foreach ( SipInfo sipinfo, sipinfos )
        {
            QVariantMap hostinfo;
            hostinfo[ "host" ] = sipinfo.host();
            hostinfo[ "port" ] = sipinfo.port();
            hostinfos << hostinfo;
        }
Exemple #20
0
const SipInfo
SipInfo::fromJson( QString json )
{
    SipInfo info;

    QJson::Parser parser;
    bool ok;
    QVariant v = parser.parse( json.toLatin1(), &ok );
    if ( !ok  || v.type() != QVariant::Map )
    {
        qDebug() << Q_FUNC_INFO << "Invalid JSON: " << json;
        return info;
    }
    QVariantMap m = v.toMap();

    info.setVisible( m["visible"].toBool() );
    if ( m["visible"].toBool() )
    {
        info.setHost( m["host"].toString() );
        info.setPort( m["port"].toInt() );
        info.setNodeId( m["uniqname"].toString() );
        info.setKey( m["key"].toString() );
    }

    return info;
}
    void AMQPWatcher::newMessage(QAMQP::Queue * q)
    {
        // Retrieve message
        QAMQP::MessagePtr message = q->getMessage();
        qDebug() << "New message received: " << message->payload;

        // Ack to server
        q->ack(message);

        QJson::Parser parser;
        QVariantMap response = parser.parse(message->payload).toMap();

        QString type(response.value("type").toString());
        QVariantMap sms = response.value("message").toMap();

        if (type == QString("new_message"))
        {
            qlonglong id = sms.value("id").toLongLong();
            QString from = sms.value("from").toString();
            QString to = sms.value("to").toString();
            QString body = sms.value("body").toString();

            emit messageReceived(new MessageInfo(from, to, body, id));
        }
    }
void SkydriveService::ListFilesFinished(QNetworkReply* reply) {
  reply->deleteLater();
  QJson::Parser parser;
  QVariantMap response = parser.parse(reply).toMap();

  QVariantList files = response["data"].toList();
  for (const QVariant& f : files) {
    QVariantMap file = f.toMap();
    if (file["type"].toString() == "folder") {
      ListFiles(file["id"].toString());
    } else {
      QString mime_type = GuessMimeTypeForFile(file["name"].toString());
      QUrl url;
      url.setScheme("skydrive");
      url.setPath(file["id"].toString());

      Song song;
      song.set_url(url);
      song.set_ctime(file["created_time"].toDateTime().toTime_t());
      song.set_mtime(file["updated_time"].toDateTime().toTime_t());
      song.set_comment(file["description"].toString());
      song.set_filesize(file["size"].toInt());
      song.set_title(file["name"].toString());

      QUrl download_url = file["source"].toUrl();
      // HTTPS appears to be broken somehow between Qt & Skydrive downloads.
      // Fortunately, just changing the scheme to HTTP works.
      download_url.setScheme("http");
      MaybeAddFileToDatabase(song, mime_type, download_url, QString::null);
    }
  }
}
Exemple #23
0
void ApplyMarkQuery::onManagerFinished(QNetworkReply *reply)
{
  QByteArray jsonResponseByteArray = reply->readAll();

  if (jsonResponseByteArray.size() > 0)
  {
    QString jsonResponse(jsonResponseByteArray);
    qDebug() << "Gotten response (json): " << jsonResponse;
    QJson::Parser parser;
    bool ok;
    QVariantMap result = parser.parse(QByteArray(jsonResponse.toAscii()), &ok).toMap();
    QString status("");
    QString status_description("");
    if (!ok)
    {
      qFatal("An error occured during parsing json with response to apply mark");
    }
    else
    {
      status = result["status"].toString();
      status_description = result["status_description"].toString();
    }

    Q_EMIT responseReceived(status,status_description);
  }
}
Exemple #24
0
void SpotifyImages::FetchImagesForArtist(int id, const QString& spotify_id) {
  QUrl artist_url(QString(kSpotifyArtistUrl).arg(spotify_id));
  qLog(Debug) << "Fetching images for artist:" << artist_url;
  QNetworkRequest request(artist_url);
  QNetworkReply* reply = network_->get(request);
  NewClosure(reply, SIGNAL(finished()), [this, id, reply]() {
    reply->deleteLater();
    QJson::Parser parser;
    QVariantMap result = parser.parse(reply).toMap();
    QVariantList images = result["images"].toList();
    QList<QPair<QUrl, QSize>> image_candidates;
    for (QVariant i : images) {
      QVariantMap image = i.toMap();
      int height = image["height"].toInt();
      int width = image["width"].toInt();
      QUrl url = image["url"].toUrl();
      image_candidates.append(qMakePair(url, QSize(width, height)));
    }
    if (!image_candidates.isEmpty()) {
      QPair<QUrl, QSize> winner =
          *std::max_element(
              image_candidates.begin(), image_candidates.end(),
              [](const QPair<QUrl, QSize>& a, const QPair<QUrl, QSize>& b) {
                return (a.second.height() * a.second.width()) <
                       (b.second.height() * b.second.width());
              });
      emit ImageReady(id, winner.first);
    }
    emit Finished(id);
  });
}
//--------------------------------------------------------------------------------------------------
AiredEpisodeDetails SeriesProvider::nextAiredEpisode(const Serie & serie) const 
{
    AiredEpisodeDetails details;

    _network->read(getEpisodesDetailsUrl(serie));
    if (_network->contentIsReady())
    {
        bool           parsingIsOk;
        QJson::Parser  parser;
        QVariantMap    jsonResult = parser.parse(_network->content(),
                                                 &parsingIsOk).toMap();
        
        if (parsingIsOk)
        {
            QVariantMap   seasons  = jsonResult["root"].toMap()["seasons"].toMap();
            QVariantMap   episodes = seasons["0"].toMap()["episodes"].toMap();
            
            QList<QVariant> episodeList = episodes.values();
            qSort(episodeList.begin(), episodeList.end());
            
            foreach (const QVariant & episode, episodeList)
            {          
                const QDateTime episodeDate =  
                                  QDateTime::fromTime_t(episode.toMap()["date"].toUInt());  
                
                if (episodeDate > _currentDate)
                {
                    return AiredEpisodeDetails(episode.toMap()["episode"].toUInt(),
                                               episodeDate.date());
                }                               
            }
        }
    }
Exemple #26
0
bool GetBlobResponseJSON::parseJson(const QByteArray &data)
{
    clearContainers();

    QJson::Parser parser;
    bool ok;
    QVariantMap result = parser.parse (data, &ok).toMap ();
    if (!ok)
        return false;

    /*result["errno"].toInt(&ok);
    if (!ok) return false;*/
    int errno = result["errno"].toInt();
    QString blob = result["blob"].toString ();

    /*if (blob.isEmpty())
    {
      DEBUG() << "Some of the string fields are empty." << data;
      return false;
    }*/

    m_errno = errno;
    m_blob = blob;
    return true;
}
Exemple #27
0
void
DiscogsPlugin::albumSearchSlot( const InfoRequestData &requestData, QNetworkReply *reply )
{
    QJson::Parser p;
    QVariantMap results = p.parse( reply ).toMap();

    if ( !results.contains( "results" ) || results.value( "results" ).toList().isEmpty() )
    {
        emit info( requestData, QVariant() );
        return;
    }

    const QVariantMap result = results.value( "results" ).toList().first().toMap();
    if ( !result.contains( "id" ) )
    {
        emit info( requestData, QVariant() );
        return;
    }

    const int id = result.value( "id" ).toInt();
    QUrl url( QString( "http://api.discogs.com/release/%1" ).arg( id ) );
    QNetworkRequest req( url );
    req.setRawHeader( "User-Agent", "TomahawkPlayer/1.0 +http://tomahawk-player.org" );

    QNetworkReply* reply2 = TomahawkUtils::nam()->get( req );
    NewClosure( reply2, SIGNAL( finished() ),  this, SLOT( albumInfoSlot( Tomahawk::InfoSystem::InfoRequestData, QNetworkReply* ) ), requestData, reply2 );
}
void QgsArcGisRestCatalogProvider::parseFolderDo()
{
  QNetworkReply* reply = qobject_cast<QNetworkReply*>( QObject::sender() );
  reply->deleteLater();
  QString path = reply->property( "path" ).toString();
  QStringList catTitles = reply->property( "catTitles" ).toStringList();

  if ( reply->error() == QNetworkReply::NoError )
  {
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
    QJson::Parser parser;
    QVariantMap folderData = parser.parse( reply->readAll() ).toMap();
#else
    QVariantMap folderData = QJsonDocument::fromJson( reply->readAll() ).object().toVariantMap();
#endif
    QString catName = QFileInfo( path ).baseName();
    if ( !catName.isEmpty() )
    {
      catTitles.append( catName );
    }
    foreach ( const QVariant& folderName, folderData["folders"].toList() )
    {
      parseFolder( path + "/" + folderName.toString(), catTitles );
    }
    foreach ( const QVariant& serviceData, folderData["services"].toList() )
    {
      parseService( QString( "/" ) + serviceData.toMap()["name"].toString(), catTitles );
    }
  }
Exemple #29
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
        }
    }
bool FilterSubstringRequestJSON::parseJson(const QByteArray &data)
{
  clearContainers();

  QJson::Parser parser;
  bool ok;
  QVariantMap result = parser.parse(data, &ok).toMap();

  if(!ok) return false;

  QString field = result["field"].toString();
  QString substring = result["substring"].toString();
  QString auth_token = result["auth_token"].toString();
  qulonglong tagNumber = result["tag_number"].toULongLong(&ok);
  if (ok) m_tagNumber = tagNumber;

  if ( !Tag::isFieldNameValid(field) || substring.isEmpty() || auth_token.isEmpty())
    return false;

  setField(field);
  setSubstring(substring);
  setSessionToken(auth_token);

  return true;
}