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
        }
    }
Beispiel #2
0
const SipInfo
SipInfo::fromJson( QString json )
{
    SipInfo info;

    QJson::Parser parser;
    bool ok;
    QVariant v = parser.parse( json.toAscii(), &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() )
    {
        QHostInfo hostInfo;
        hostInfo.setHostName( m["host"].toString() );
        info.setHost( hostInfo );
        info.setPort( m["port"].toInt() );
        info.setUniqname( m["uniqname"].toString() );
        info.setKey( m["key"].toString() );
    }

    return info;
}
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();
                }
            }
        }
Beispiel #4
0
/*
  Reads a JSON file and returns the parsed version of it as a QVariantMap
*/
QVariantMap ReadJSONFromFile(QString filename) {
    QFile file(filename);
    if (!file.exists()) {
        QString s = "File does not exist: ";
        s.append(filename);
        throw JSONOpenError(s.toStdString());
    }

    QByteArray rawstring;

    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QString s = "Failure to open: ";
        s.append(filename);
        throw JSONOpenError(s.toStdString());
    }

    while (!file.atEnd()) {
        rawstring.append(file.readLine());
    }

    QJson::Parser parser;
    bool ok;
    QVariantMap results = parser.parse(rawstring, &ok).toMap();
    if (!ok) {
        QString s = "Failure to parse: ";
        s.append(filename);
        throw JSONParseError(s.toStdString());
    }

    return results;
}
Beispiel #5
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 ) ) );
    }
  }
Beispiel #6
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;
    }
Beispiel #8
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;
}
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 );
    }
  }
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;
                }
            }
Beispiel #11
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();
    }
}
Beispiel #12
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;
}
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;
}
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);
    }
  }
}
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();
}
Beispiel #16
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 ();
}
Beispiel #17
0
    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));
        }
    }
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;
}
Beispiel #19
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);
  });
}
Beispiel #20
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();
}
Beispiel #21
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
DatabaseCommand_LoadDynamicPlaylistEntries::exec( DatabaseImpl* dbi )
{
//    qDebug() << "Loading dynamic playlist guid" << guid();
    // load the entries first
    generateEntries( dbi );

    // now load the controls etc

    TomahawkSqlQuery controlsQuery = dbi->newquery();
    controlsQuery.prepare("SELECT playlist_revision.playlist, controls, plmode, pltype "
                          "FROM dynamic_playlist_revision, playlist_revision "
                          "WHERE dynamic_playlist_revision.guid = ? AND playlist_revision.guid = dynamic_playlist_revision.guid");
    controlsQuery.addBindValue( revisionGuid() );
    controlsQuery.exec();

    QString type;
    GeneratorMode mode;

    QList< QVariantMap > controls;
    QString playlist_guid;
//    qDebug() << "Loading controls..." << revisionGuid();
//    qDebug() << "SELECT playlist_revision.playlist, controls, plmode, pltype "
//    "FROM dynamic_playlist_revision, playlist_revision "
//    "WHERE dynamic_playlist_revision.guid = "<< revisionGuid() << " AND playlist_revision.guid = dynamic_playlist_revision.guid";

    if( controlsQuery.first() )
    {
        playlist_guid = controlsQuery.value( 0 ).toString();
        QJson::Parser parser;
        bool ok;
        QVariant v = parser.parse( controlsQuery.value(1).toByteArray(), &ok );
        Q_ASSERT( ok && v.type() == QVariant::List ); //TODO


        type = controlsQuery.value( 3 ).toString();
        mode = static_cast<GeneratorMode>( controlsQuery.value( 2 ).toInt() );

        QStringList controlIds = v.toStringList();
//        qDebug() << "Got controls in dynamic playlist, loading:" << controlIds << controlsQuery.value(1);
        foreach( const QString& controlId, controlIds )
        {
            TomahawkSqlQuery controlQuery = dbi->newquery();
            controlQuery.prepare( "SELECT selectedType, match, input "
                                  "FROM dynamic_playlist_controls "
                                  "WHERE id = :id" );
            controlQuery.bindValue( ":id", controlId );
            controlQuery.exec();
            if( controlQuery.next() )
            {
                QVariantMap c;
                c[ "type" ] = type;
                c[ "id" ] = controlId;
                c[ "selectedType" ] = controlQuery.value( 0 ).toString();
                c[ "match" ] = controlQuery.value( 1 ).toString();
                c[ "input" ] = controlQuery.value( 2 ).toString();
                controls << c;
            }
        }
void RemoteLogViewer::processLog(const QByteArray &log)
{
    QJson::Parser parser;
    bool ok = false;

    ui->textEdit->clear();

    QVariantMap mapA = parser.parse(log , &ok).toMap();
    if ( ! ok )
    {
        qDebug() << "Syntax error of log";
        return;
    }

    if ( mapA.value("ret").toInt() != 0 || mapA.value("tuin").toString() != _uin )
    {
        qDebug() << "Retcode: " << mapA.value("ret").toInt();
        return;
    }

    ui->logPage->setMaximum(mapA.value("total").toInt());
    if ( justLoaded )
    {
        justLoaded = false;
        ui->logPage->setValue(ui->logPage->maximum());
    }

    foreach (const QVariant & v , mapA.value("chatlogs").toList())
    {
        const QVariantMap & vMap = v.toMap();
        // 16: what you say ; 17: what he says
        const int & cmd = vMap.value("cmd").toInt();
        const QString & time = util->timeStr(vMap.value("time").toInt());

        QString msg;
        foreach (const QVariant & m , vMap.value("msg").toList())
        {
            if ( ! msg.isEmpty() )
                msg.append("\n");
            msg.append(m.toString());
        }

        msg = msg.trimmed().replace("&","&amp;").replace(">","&gt;").replace("<","&lt;");

        if ( msg.isEmpty() )
            continue;

        if ( cmd == 16 )
        {
            ui->textEdit->append(QString::fromUtf8("<font color='green'>我 %2</font>").arg(time));
        }
        else
        {
            ui->textEdit->append(QString("<font color='blue'>%1 %2</font>").arg(_title).arg(time));
        }

        ui->textEdit->append(msg);
    }
}
Beispiel #24
0
//加载完成
void SearchThread::slot_LoadFinished( QNetworkReply *replay )
{
	QTextCodec *codec = QTextCodec::codecForName("utf8");		//转换成utf8编码格式
	QString searchStr = codec->toUnicode(replay->readAll());
	if (searchStr == "")
	{
		emit sig_SearchTimeout();	//搜索超时
		return;
	}
	searchStr = QUrl::fromPercentEncoding(searchStr.toAscii());	//百分比编码

	//解析Json
	QJson::Parser parser;
	bool ok;
	QVariantMap result = parser.parse(searchStr.toUtf8(), &ok).toMap();
	if (!ok)
	{
		qDebug() << "转换成QVariantMap失败";
		return;
	}

	//搜索到的数量
	m_nMusicNum = result["total"].toInt();
	emit sig_SearchNum(m_nMusicNum);

	//得到结果数组
	QVariantList resultList = result["results"].toList();
	foreach (QVariant var, resultList)
	{
		QVariantMap resultMap = var.toMap();	//得到每一项的map

		//歌曲名
		QCheckBox *musicNameCheckBox = new QCheckBox(resultMap["song_name"].toString());
		musicNameCheckBox->setObjectName(tr("musicNameCheckBox"));
		musicNameCheckBox->setToolTip(resultMap["song_name"].toString());
		musicNameCheckBox->setFont(QFont("微软雅黑", 10));
		musicNameCheckBox->setStyleSheet("QCheckBox{color:white;}"
			"QCheckBox::indicator{width:10px;height:10px;border: 1px solid white;border-radius:2px}"
			"QCheckBox::indicator:checked {image: url(:/app/images/checked2.png);}");

		//艺人
		QTableWidgetItem *artistItem = new QTableWidgetItem(resultMap["artist_name"].toString());
		artistItem->setTextAlignment(Qt::AlignCenter);
		artistItem->setToolTip(resultMap["artist_name"].toString());
		artistItem->setFont(QFont("微软雅黑", 10));

		//专辑
		QTableWidgetItem *albumItem = new QTableWidgetItem("《" + resultMap["album_name"].toString() + "》");
		albumItem->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter);
		albumItem->setToolTip("《" + resultMap["album_name"].toString() + "》");
		albumItem->setFont(QFont("微软雅黑", 10));

		//插入播放列表
		int currentRows = m_searchList->rowCount();//返回列表中的行数
		m_searchList->insertRow(currentRows);//从播放列表中的当前行插入
		m_searchList->setCellWidget(currentRows, 0, musicNameCheckBox);
		m_searchList->setItem(currentRows, 1, artistItem);
		m_searchList->setItem(currentRows, 2, albumItem);
	}
Beispiel #25
0
void DropboxAuthenticator::RequestAccountInformationFinished(
    QNetworkReply* reply) {
  reply->deleteLater();
  QJson::Parser parser;
  QVariantMap response = parser.parse(reply).toMap();
  name_ = response["display_name"].toString();
  emit Finished();
}
Beispiel #26
0
void UbuntuOneService::VolumeListRequestFinished(QNetworkReply* reply) {
  reply->deleteLater();

  QJson::Parser parser;
  QVariantList result = parser.parse(reply).toList();
  foreach (const QVariant& v, result) {
    RequestFileList(v.toMap()["node_path"].toString());
  }
Beispiel #27
0
void
RoviPlugin::albumLookupFinished()
{
    QNetworkReply* reply = qobject_cast<QNetworkReply*>( sender() );
    Q_ASSERT( reply );

    if ( reply->error() != QNetworkReply::NoError )
        return;

    Tomahawk::InfoSystem::InfoRequestData requestData = reply->property( "requestData" ).value< Tomahawk::InfoSystem::InfoRequestData >();

    QJson::Parser p;
    bool ok;
    QVariantMap response = p.parse( reply, &ok ).toMap();

    if ( !ok || response.isEmpty() || !response.contains( "searchResponse" ) )
    {
        tLog() << "Error parsing JSON from Rovi!" << p.errorString() << response;
        emit info( requestData, QVariant() );
        return;
    }

    QVariantList resultList = response[ "searchResponse" ].toMap().value( "results" ).toList();
    if ( resultList.size() == 0 )
    {
        emit info( requestData, QVariant() );
        return;
    }

    QVariantMap results = resultList.first().toMap();
    QVariantList tracks = results[ "album" ].toMap()[ "tracks" ].toList();

    if ( tracks.isEmpty() )
    {
        tLog() << "Error parsing JSON from Rovi!" << p.errorString() << response;
        emit info( requestData, QVariant() );
    }


    QStringList trackNameList;
    foreach ( const QVariant& track, tracks )
    {
        const QVariantMap trackData = track.toMap();
        if ( trackData.contains( "title" ) )
            trackNameList << trackData[ "title" ].toString();
    }

    QVariantMap returnedData;
    returnedData["tracks"] = trackNameList;

    emit info( requestData, returnedData );

    Tomahawk::InfoSystem::InfoStringHash criteria;
    criteria["artist"] = requestData.input.value< Tomahawk::InfoSystem::InfoStringHash>()["artist"];
    criteria["album"] = requestData.input.value< Tomahawk::InfoSystem::InfoStringHash>()["album"];

    emit updateCache( criteria, 0, requestData.type, returnedData );
}
Beispiel #28
0
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 version/nonce information";
        if ( !retMap.contains( "version" ) || !retMap.contains( "nonce" ) )
        {
            tLog() << Q_FUNC_INFO << "Failed to acquire version or nonce 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;
        }
QVariant SoundCloudService::ExtractResult(QNetworkReply* reply) {
  QJson::Parser parser;
  bool ok;
  QVariant result = parser.parse(reply, &ok);
  if (!ok) {
    qLog(Error) << "Error while parsing SoundCloud result";
  }
  return result;
}
Beispiel #30
0
void LinTORManager::setupFolders()
{
  // Use the folders response to construct the flickableTabBar:
  QJson::Parser parser;
  bool ok;
  QVariantMap result = parser.parse(foldersReply->readAll(), &ok).toMap();

  foldersReply->deleteLater();
  foldersReply = 0;

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

  // Clear out any existing folder items:
  folderItems.clear();
  torTreeWidget->clear();

  QList<QVariant> folderVariants = result["tags"].toList();

  if (!folderVariants.isEmpty())
  {
    QList<QVariant>::const_iterator index = folderVariants.constBegin();
    QList<QVariant>::const_iterator end = folderVariants.constEnd();
    QMap<QString, QVariant> singleFolderMap;
    LinTORFolderItem *item;
    QString folderID;

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

      folderID = singleFolderMap["id"].toString(),
      
      item = new LinTORFolderItem(
        folderID,
        singleFolderMap["sortid"].toString(),
        Standard_TORFolder);

      torTreeWidget->addTopLevelItem(item);

      folderItems[folderID] = item;

      ++index;
    }
  }

  // Add a "reading-list" item:
  allSubsItem =
    new LinTORFolderItem("user/-/state/com.google/reading-list", "", Standard_TORFolder);

  torTreeWidget->addTopLevelItem(allSubsItem);

  getSubscriptions();
}