Ejemplo n.º 1
0
        progressBar->setValue(40);
        progressLabel->setText(tr("Upload ride... Sending"));

        networkMgr.post( request, out.toAscii());
    } else {
        QByteArray data;
        QUrl params;
        TcxFileReader reader;

        params.addQueryItem("token", token);
        params.addQueryItem("type", "tcx");
        params.addQueryItem("data", reader.toByteArray(mainWindow, ride->ride(), altitudeChk->isChecked(), powerChk->isChecked(), heartrateChk->isChecked(), cadenceChk->isChecked()));
        data = params.encodedQuery();

        QUrl url = QUrl(STRAVA_URL2 + "/upload");
        QNetworkRequest request = QNetworkRequest(url);
        request.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded");

        progressBar->setValue(40);
        progressLabel->setText(tr("Upload ride... Sending"));

        networkMgr.post( request, data);
    }

    //qDebug() << out;

    eventLoop.exec();
}

void
StravaUploadDialog::requestUploadFinished(QNetworkReply *reply)
void PlaylistModel::fetchFromUrl()
{
    m_manager->get(QNetworkRequest(QUrl("http://"+m_remoteUrl+"/requests/playlist.xml").toString()));
}
Ejemplo n.º 3
0
void FMList::init(){
    this->loaded_count=0;
    this->request=QNetworkRequest(QUrl("http://fm.renren.com/fm/home"));
    QObject::connect(this,SIGNAL(addFM(FMInfo*)),this->view,SLOT(addItem(FMInfo*)),Qt::QueuedConnection);
}
Ejemplo n.º 4
0
QNetworkReply* QtWebKitNetworkManager::createRequest(QNetworkAccessManager::Operation operation, const QNetworkRequest &request, QIODevice *outgoingData)
{
	if (request.url() == m_formRequestUrl)
	{
		m_formRequestUrl = QUrl();

		m_widget->openFormRequest(request.url(), operation, outgoingData);

		return QNetworkAccessManager::createRequest(QNetworkAccessManager::GetOperation, QNetworkRequest());
	}

	const QString host = request.url().host();

	if (!m_widget->isNavigating() && ContentBlockingManager::isUrlBlocked(m_widget->getContentBlockingProfiles(), request, m_widget->getUrl()))
	{
		Console::addMessage(QCoreApplication::translate("main", "Blocked request"), Otter::NetworkMessageCategory, LogMessageLevel, request.url().toString());

		QUrl url = QUrl();
		url.setScheme(QLatin1String("http"));

		if (m_blockedRequests.contains(host))
		{
			++m_blockedRequests[host];
		}
		else
		{
			m_blockedRequests[host] = 1;
		}

		return QNetworkAccessManager::createRequest(QNetworkAccessManager::GetOperation, QNetworkRequest(url));
	}

	++m_startedRequests;

	if (operation == GetOperation && request.url().isLocalFile() && QFileInfo(request.url().toLocalFile()).isDir())
	{
		return new LocalListingNetworkReply(this, request);
	}

	QNetworkRequest mutableRequest(request);

	if (!m_canSendReferrer)
	{
		mutableRequest.setRawHeader(QStringLiteral("Referer").toLatin1(), QByteArray());
	}

	if (operation == PostOperation && mutableRequest.header(QNetworkRequest::ContentTypeHeader).isNull())
	{
		mutableRequest.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/x-www-form-urlencoded"));
	}

	if (NetworkManagerFactory::isWorkingOffline())
	{
		mutableRequest.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::AlwaysCache);
	}
	else if (m_doNotTrackPolicy != NetworkManagerFactory::SkipTrackPolicy)
	{
		mutableRequest.setRawHeader(QByteArray("DNT"), QByteArray((m_doNotTrackPolicy == NetworkManagerFactory::DoNotAllowToTrackPolicy) ? "1" : "0"));
	}

	mutableRequest.setRawHeader(QStringLiteral("Accept-Language").toLatin1(), (m_acceptLanguage.isEmpty() ? NetworkManagerFactory::getAcceptLanguage().toLatin1() : m_acceptLanguage.toLatin1()));
	mutableRequest.setHeader(QNetworkRequest::UserAgentHeader, m_userAgent);

	emit messageChanged(tr("Sending request to %1…").arg(host));

	QNetworkReply *reply = QNetworkAccessManager::createRequest(operation, mutableRequest, outgoingData);

	if (!m_baseReply)
	{
		m_baseReply = reply;
	}

	if (m_isSecure >= 0)
	{
		const QString scheme = reply->url().scheme();

		if (scheme == QLatin1String("https"))
		{
			m_isSecure = 1;
		}
		else if (scheme == QLatin1String("http"))
		{
			m_isSecure = -1;
		}
	}

	m_replies[reply] = qMakePair(0, false);

	connect(reply, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(downloadProgress(qint64,qint64)));

	if (m_updateTimer == 0)
	{
		m_updateTimer = startTimer(500);
	}

	return reply;
}
Ejemplo n.º 5
0
QPlaceSearchReply *QPlaceManagerEngineOsm::search(const QPlaceSearchRequest &request)
{
    bool unsupported = false;

    // Only public visibility supported
    unsupported |= request.visibilityScope() != QLocation::UnspecifiedVisibility &&
                   request.visibilityScope() != QLocation::PublicVisibility;
    unsupported |= request.searchTerm().isEmpty() && request.categories().isEmpty();

    if (unsupported)
        return QPlaceManagerEngine::search(request);

    QUrlQuery queryItems;

    queryItems.addQueryItem(QStringLiteral("format"), QStringLiteral("jsonv2"));

    //queryItems.addQueryItem(QStringLiteral("accept-language"), QStringLiteral("en"));

    QGeoRectangle boundingBox;
    QGeoShape searchArea = request.searchArea();
    switch (searchArea.type()) {
    case QGeoShape::CircleType: {
        QGeoCircle c(searchArea);
        qreal radius = c.radius();
        if (radius < 0)
            radius = 50000;

        boundingBox = QGeoRectangle(c.center().atDistanceAndAzimuth(radius, -45),
                                    c.center().atDistanceAndAzimuth(radius, 135));
        break;
    }
    case QGeoShape::RectangleType:
        boundingBox = searchArea;
        break;
    default:
        ;
    }

    if (!boundingBox.isEmpty()) {
        queryItems.addQueryItem(QStringLiteral("bounded"), QStringLiteral("1"));
        QString coordinates;
        coordinates = QString::number(boundingBox.topLeft().longitude()) + QLatin1Char(',') +
                      QString::number(boundingBox.topLeft().latitude()) + QLatin1Char(',') +
                      QString::number(boundingBox.bottomRight().longitude()) + QLatin1Char(',') +
                      QString::number(boundingBox.bottomRight().latitude());
        queryItems.addQueryItem(QStringLiteral("viewbox"), coordinates);
    }

    QStringList queryParts;
    if (!request.searchTerm().isEmpty())
        queryParts.append(request.searchTerm());

    foreach (const QPlaceCategory &category, request.categories()) {
        QString id = category.categoryId();
        int index = id.indexOf(QLatin1Char('='));
        if (index != -1)
            id = id.mid(index+1);
        queryParts.append(QLatin1Char('[') + id + QLatin1Char(']'));
    }

    queryItems.addQueryItem(QStringLiteral("q"), queryParts.join(QLatin1Char('+')));

    QVariantMap parameters = request.searchContext().toMap();

    QStringList placeIds = parameters.value(QStringLiteral("ExcludePlaceIds")).toStringList();
    if (!placeIds.isEmpty())
        queryItems.addQueryItem(QStringLiteral("exclude_place_ids"), placeIds.join(QLatin1Char(',')));

    queryItems.addQueryItem(QStringLiteral("addressdetails"), QStringLiteral("1"));

    QUrl requestUrl(m_urlPrefix);
    requestUrl.setQuery(queryItems);

    QNetworkReply *networkReply = m_networkManager->get(QNetworkRequest(requestUrl));

    QPlaceSearchReplyOsm *reply = new QPlaceSearchReplyOsm(request, networkReply, this);
    connect(reply, SIGNAL(finished()), this, SLOT(replyFinished()));
    connect(reply, SIGNAL(error(QPlaceReply::Error,QString)),
            this, SLOT(replyError(QPlaceReply::Error,QString)));

    return reply;
}
Ejemplo n.º 6
0
void DefinitionUpdater::update() {
  reply = qnam.head(QNetworkRequest(url));
  connect(reply, SIGNAL(finished()),
          this, SLOT(checkReply()));
}
Ejemplo n.º 7
0
void NetworkComm::sendGetRequest(QString s){
    QUrl url(s);
    rply = nam->get(QNetworkRequest(url));
    qDebug()<<"get request to "<<s;
}
Ejemplo n.º 8
0
// Callback from fetchIcon
void
MainWindow::iconDownloaded()
{
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
    QString savePath = reply->request().attribute(QNetworkRequest::User).toString();
    int wasRedirected = reply->request().attribute((QNetworkRequest::Attribute)(QNetworkRequest::User+1)).toInt();
    QString username = reply->request().attribute((QNetworkRequest::Attribute)(QNetworkRequest::User+2)).toString();
    QString password = reply->request().attribute((QNetworkRequest::Attribute)(QNetworkRequest::User+3)).toString();

    QVariant redirect = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);

    if (!redirect.toUrl().isEmpty() && !wasRedirected)
    {
        qDebug() << "Was redirected to " << redirect.toUrl();
        reply->deleteLater();
        QUrl redir = redirect.toUrl();
        if (!username.isEmpty())
        {
            redir.setUserName(username);
            redir.setPassword(password);
        }
        QNetworkRequest req = QNetworkRequest(redir);
        req.setAttribute(QNetworkRequest::User, QVariant(savePath));
        req.setAttribute((QNetworkRequest::Attribute)(QNetworkRequest::User+1), QVariant(1));
        QNetworkReply *rep = pManager->get(req);
        connect(rep, SIGNAL(finished()),
                this, SLOT(iconDownloaded()));
        return;
    }

    qDebug() << "Icon downloaded";
    if (reply->error())
    {
        reply->close();
        qDebug() << "Couldn't get icon";
        fetchHTMLIcon(reply->url().toString(), savePath);
        return;
    }

    QByteArray logoData = reply->readAll();
    // The favicon can be in various formats, so convert it to something
    // we know we can safely display
    QBuffer logoBuffer(&logoData);
    logoBuffer.open(QIODevice::ReadOnly);
    QImageReader reader(&logoBuffer);
    QSize iconSize(16, 16);
    if(reader.canRead())
    {
        while((reader.imageCount() > 1) && (reader.currentImageRect() != QRect(0, 0, 16, 16)))
        {
            if (!reader.jumpToNextImage())
                   break;
        }

        reader.setScaledSize(iconSize);
        const QImage icon = reader.read();
        if (icon.format() == QImage::Format_Invalid)
        {
            fetchHTMLIcon(reply->url().toString(), savePath);
        }
        else
        {
            icon.save(savePath, "PNG");
            QFileInfo info(savePath);
            int tabIndex = compareTabName(info.baseName());
            if (tabIndex != -1)
                ui->trackerTab->setTabIcon(tabIndex, QIcon(QPixmap::fromImage(icon)));
        }
    }
    else
    {
        qDebug() << "Invalid image";
        fetchHTMLIcon(reply->url().toString(), savePath);
    }

    logoBuffer.close();
    reply->close();
}
Ejemplo n.º 9
0
void UpdateInfoDialog::CheckUpdate()
{
    int os_num = 0;

#if defined(Q_OS_WIN32)
    if(QT_POINTER_SIZE == 4){
        os_num = OS_NUM_WIN_32;
    }else{
        os_num = OS_NUM_WIN_64;
    }
#elif defined(Q_OS_MAC)
    if(QT_POINTER_SIZE == 4){
        os_num = OS_NUM_MAC_32;
    }else{
        os_num = OS_NUM_MAC_64;
    }
#else
    if(QT_POINTER_SIZE == 4){
        os_num = OS_NUM_LINUX_32;
    }else{
        os_num = OS_NUM_LINUX_64;
    }
#endif

//    qDebug() << "check update";
    QNetworkAccessManager *net = new QNetworkAccessManager(this);
    connect(net, &QNetworkAccessManager::finished, [this](QNetworkReply *reply) {
        if(reply->error() == QNetworkReply::NoError){

            QJsonDocument json = QJsonDocument::fromJson(reply->readAll());
            bool exist = json.object().value(KEY_UPDATE_EXIST).toBool();

//            qDebug() << "download " << json.object().value(KEY_DOWNLOAD_URL).toString();
//            qDebug() << "web " << json.object().value(KEY_WEBPAGE_URL).toString();
//            qDebug() << "exist " << exist;
//            qDebug() << "ver " << json.object().value(KEY_NEW_VERSION).toString();
//            qDebug() << "ver code " << json.object().value(KEY_NEW_VERSION_CODE).toDouble() << "<=" << KANMEMO_VERSION_CODE;

            //バージョンコード
            m_newVersionCode = static_cast<int>(json.object().value(KEY_NEW_VERSION_CODE).toDouble());
            if(isHide(m_newVersionCode) && !m_force){
                m_force = true; //1度通ったらはユーザー操作なので強制表示
                return; //非表示
            }

            if(exist){
                //ダイアログ表示
                //Download
                QString download_url = json.object().value(KEY_DOWNLOAD_URL).toString();
                QStringList url_list = download_url.split("|");
                ui->downloadUrlLabel1->setText(QString("<a href='%1'>%1</a>").arg(url_list[0]));
                if(url_list.count() > 1){
                    ui->downloadUrlLabel2->setText(QString("<a href='%1'>%1</a>").arg(url_list[1]));
                }else{
                    ui->downloadUrlLabel2->clear();
                }
                //WebPage
                ui->webpageUrlLabel->setText(QString("<a href='%1'>%1</a>").arg(json.object().value(KEY_WEBPAGE_URL).toString()));
                //Version Number
                ui->versionNumberLabel->setText(json.object().value(KEY_NEW_VERSION).toString());
                //message
                ui->messageTextEdit->setPlainText(json.object().value(KEY_MESSAGE).toString());
                //必ずチェックを外す
                ui->hideNextUpdatecheckBox->setChecked(false);

                show();
            }else if(m_force){
                //更新なし
                QMessageBox::information(this
                                     , tr("Kan Memo")
                                     , tr("There was no update.")
                                     , QMessageBox::Yes);
            }

            m_force = true; //1度通ったらはユーザー操作なので強制表示
        }
    });
    //プロキシ
    if(m_settings != NULL){
        QNetworkProxy *proxy = new QNetworkProxy();
        bool enable = m_settings->value(SETTING_GENERAL_PROXY_ENABLE, false).toBool();
        QString host = m_settings->value(SETTING_GENERAL_PROXY_HOST).toString();
        if(host.length() > 0 && enable){
            proxy->setType(QNetworkProxy::HttpProxy);
            proxy->setHostName(host);
            proxy->setPort(m_settings->value(SETTING_GENERAL_PROXY_PORT, 8888).toInt());

            net->setProxy(*proxy);
        }else{
            net->setProxy(QNetworkProxy::NoProxy);
        }
    }
    //アクセス開始
    net->get(QNetworkRequest(CHECK_UPDATE_URL
                             .arg(KANMEMO_VERSION)
                             .arg(KANMEMO_VERSION_CODE)
                             .arg(os_num)
                             .arg(QLocale::system().name())));
}
Ejemplo n.º 10
0
void Updater::startDownloadingUpdateInfo(const QUrl &url)
{
    QNetworkReply *reply = mApp->networkManager()->get(QNetworkRequest(QUrl(url)));

    connect(reply, SIGNAL(finished()), this, SLOT(downCompleted()));
}
Ejemplo n.º 11
0
QNetworkReply* ElisaNetworkService::makeRequest(QString uri)
{
    uri = BASE_URI + uri;
    return mNetworkManager->get(QNetworkRequest(QUrl(uri)));
}
void UltimateLyricsProvider::LyricsFetched() {
  QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
  if (!reply) {
    url_hop_ = false;
    return;
  }

  int id = requests_.take(reply);
  reply->deleteLater();

  if (reply->error() != QNetworkReply::NoError) {
    url_hop_ = false;
    emit Finished(id);
    return;
  }

  // Handle redirects
  QVariant redirect_target = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
  if (redirect_target.isValid()) {
    if (redirect_count_ >= kRedirectLimit) {
      url_hop_ = false;
      emit Finished(id);
      return;
    }

    QUrl target = redirect_target.toUrl();
    if (target.scheme().isEmpty() || target.host().isEmpty()) {
      QString path = target.path();
      target = reply->url();
      target.setPath(path);
    }

    redirect_count_ ++;
    QNetworkReply* reply = network_->get(QNetworkRequest(target));
    requests_[reply] = id;
    connect(reply, SIGNAL(finished()), SLOT(LyricsFetched()));
    return;
  }

  const QTextCodec* codec = QTextCodec::codecForName(charset_.toAscii().constData());
  const QString original_content = codec->toUnicode(reply->readAll());
  QString lyrics;

  // Check for invalid indicators
  foreach (const QString& indicator, invalid_indicators_) {
    if (original_content.contains(indicator)) {
      qLog(Debug) << "Found invalid indicator" << indicator;
      url_hop_ = false;
      emit Finished(id);
      return;
    }
  }

  if (!url_hop_) {
    // Apply extract rules
    foreach (const Rule& rule, extract_rules_) {
      // Modify the rule for this request's metadata
      Rule rule_copy(rule);
      for (Rule::iterator it = rule_copy.begin() ; it != rule_copy.end() ; ++it) {
        ReplaceFields(metadata_, &it->first);
      }

      QString content = original_content;
      if (ApplyExtractRule(rule_copy, &content)) {
        url_hop_ = true;
        QUrl url(content);
        qLog(Debug) << "Next url hop: " << url;
        QNetworkReply* reply = network_->get(QNetworkRequest(url));
        requests_[reply] = id;
        connect(reply, SIGNAL(finished()), SLOT(LyricsFetched()));
        return;
      }

      // Apply exclude rules
      foreach (const Rule& rule, exclude_rules_) {
        ApplyExcludeRule(rule, &lyrics);
      }
Ejemplo n.º 13
0
void AbstractReptile::handleReply(QNetworkReply *reply)
{
    if(reply->error()!=QNetworkReply::NoError)//请求错误
    {
        if(!this->data.isEmpty())
            this->save();
        emit requestError(QString("reply error:")+reply->errorString());
        if(this->replyError())
        {
            return;
        }
    }
    this->replyData=reply->readAll();
    reply->deleteLater();
    QString text=QString::fromUtf8(this->replyData);
    //-----------------解析网页,获得数据--------------------

    emit this->updateState(QString("update:request text from ")+this->currentUrl.url());

    int initCount=this->data.size();
    if(this->analysisData.isEmpty())
    {
        this->getData(text,this->data);
    }
    else
    {
        QRegExp reg=this->analysisData;
        int pos = 0;
        int count=0;
        while ((pos = reg.indexIn(text, pos)) != -1)
        {
            QString line=reg.cap(0);

            if(!line.isEmpty())
            {
                this->data.insert(line,0);
            }
            count++;
            pos += reg.matchedLength();
        }
    }
    if(data.size()<=initCount)
    {
        emit getDataError(QString("none data capture."));
        if(analysisDataError())
        {
            return;
        }
    }

    emit this->updateState(QString("update:get data ")+QString::number(data.size()-initCount));


    //-----------------解析网页,获得下一个网址---------------
    this->allUrl.insert(this->currentUrl.url(),-1);
    if(this->analysisNextUrl.isEmpty())
    {
        this->getNextUrl(text,this->currentUrl);
    }
    else
    {
        QRegExp reg=this->analysisNextUrl;
        int pos = 0;
        if((pos = reg.indexIn(text, pos)) != -1)
        {
            QString line=reg.cap(0);
            if(!line.isEmpty())
            {
                this->currentUrl=this->captureToUrl(line,this->currentUrl);
            }
            else
            {
                this->currentUrl=QUrl();
            }

        }
    }

    if(currentUrl.isEmpty())
    {
        emit getDataError(QString("none data capture."));
        if(analysisDataError())
        {
            return;
        }
    }

    emit this->updateState(QString("update:get next url ")+this->currentUrl.url());

    //-----------------验证终止-----------------------------
    if(finishWork(text))
    {
        emit this->updateState(QString("update:finish at finishWork()"));
        emit workFinish(this->data.keys());
        return;
        this->save();
    }
    if(allUrl.find(this->currentUrl.url())!=allUrl.end())
    {
        emit this->updateState(QString("update:finish : same url"));
        emit workFinish(this->data.keys());
        return;
        this->save();
    }
    if(this->currentUrl.isEmpty())
    {
        emit this->updateState(QString("update:finish empty url"));
        this->save();
        return;
    }
    //----------------开始下一个网页-------------------------
    emit this->updateState(QString("update:request url ")+this->currentUrl.url());

    this->manager->get(QNetworkRequest(this->currentUrl));
}
Ejemplo n.º 14
0
void
StravaUploadDialog::requestUpload()
{
    progressLabel->setText(tr("Upload ride..."));
    progressBar->setValue(10);

    QEventLoop eventLoop;
    QNetworkAccessManager networkMgr;

    int prevSecs = 0;
    long diffSecs = 0;

    int year = ride->fileName.left(4).toInt();
    int month = ride->fileName.mid(5,2).toInt();
    int day = ride->fileName.mid(8,2).toInt();
    int hour = ride->fileName.mid(11,2).toInt();
    int minute = ride->fileName.mid(14,2).toInt();;
    int second = ride->fileName.mid(17,2).toInt();;

    QDate rideDate = QDate(year, month, day);
    QTime rideTime = QTime(hour, minute, second);
    QDateTime rideDateTime = QDateTime(rideDate, rideTime);

    connect(&networkMgr, SIGNAL(finished(QNetworkReply*)), this, SLOT(requestUploadFinished(QNetworkReply*)));
    connect(&networkMgr, SIGNAL(finished(QNetworkReply *)), &eventLoop, SLOT(quit()));

    bool json = false;

    if (json) {
        QString out;

        QVector<RideFilePoint*> vectorPoints = ride->ride()->dataPoints();
        int totalSize = vectorPoints.size();

        int size = 0;

        out += "{\"token\": \"" + token + "\",\"data\":[";
        foreach (const RideFilePoint *point, ride->ride()->dataPoints())
        {
            size++;

            if (point->secs == 0.0)
                continue;

            diffSecs = point->secs - prevSecs;
            prevSecs = point->secs;
            rideDateTime = rideDateTime.addSecs(diffSecs);

            out += "[\"";
            out += rideDateTime.toUTC().toString(Qt::ISODate);
            out += "\",";
            out += QString("%1").arg(point->lat,0,'f',GPS_COORD_TO_STRING);
            out += ",";
            out += QString("%1").arg(point->lon,0,'f',GPS_COORD_TO_STRING);

            if (altitudeChk->isChecked()) {
                out += ",";
                out += QString("%1").arg(point->alt);

            }
            if (powerChk->isChecked()) {
                out += ",";
                out += QString("%1").arg(point->watts);
            }
            if (altitudeChk->isChecked()) {
                out += ",";
                out += QString("%1").arg(point->cad);
            }
            if (heartrateChk->isChecked()) {
                out += ",";
                out += QString("%1").arg(point->hr);
            }
            out += "]";
            if(totalSize == size)
                out += "],";
           else
               out += ",";
        }
        out += "\"type\": \"json\", ";
        out += "\"data_fields\": \[\"time\", \"latitude\", \"longitude\"";

        if (altitudeChk->isChecked())
            out += ", \"elevation\"";
        if (powerChk->isChecked())
            out += ", \"watts\"";
        if (cadenceChk->isChecked())
            out += ", \"cadence\"";
        if (heartrateChk->isChecked())
            out += ", \"heartrate\"";
        out += "]}";

        QUrl url = QUrl(STRAVA_URL2 + "/upload");
        QNetworkRequest request = QNetworkRequest(url);
        request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

        progressBar->setValue(40);
        progressLabel->setText(tr("Upload ride... Sending"));

        networkMgr.post( request, out.toAscii());
    } else {
Ejemplo n.º 15
0
void imageLoad::load(QString url)
{
    //get data from url
    access->get(QNetworkRequest(url));
}
Ejemplo n.º 16
0
void WebView::load(const QUrl &url)
{
    load(QNetworkRequest(url));
}
Ejemplo n.º 17
0
void QgsVersionInfo::checkVersion()
{
  QNetworkReply *reply = QgsNetworkAccessManager::instance()->get( QNetworkRequest( QUrl( QStringLiteral( "https://ubuntu.qgis.org/version.txt" ) ) ) );
  connect( reply, &QNetworkReply::finished, this, &QgsVersionInfo::versionReplyFinished );
}
Ejemplo n.º 18
0
void WebView::openUrlInNewTab(const QUrl &url, Qz::NewTabPositionFlags position)
{
    loadInNewTab(QNetworkRequest(url), QNetworkAccessManager::GetOperation, QByteArray(), position);
}
Ejemplo n.º 19
0
void RedditModel::FetchMoreFinished(QNetworkReply* reply) {
  is_fetching_more_ = false;

  if (reply->error() != QNetworkReply::NoError) {
    qLog(Warning) << "Error fetching links" << reply->url();
    no_more_links_ = true;
    return;
  }

  // Parse the JSON response
  QJson::Parser parser;
  QVariantMap data = parser.parse(reply).toMap();
  if (!data.contains("data") || !data["data"].toMap().contains("children")) {
    qLog(Warning) << "Error parsing link response" << reply->url();
    no_more_links_ = true;
    return;
  }

  QVariantList links = data["data"].toMap()["children"].toList();

  if (links.isEmpty()) {
    no_more_links_ = true;
    return;
  }

  QList<Link> new_links;
  int row = links_.count();
  foreach (const QVariant& link_variant, links) {
    QVariantMap link_data = link_variant.toMap();
    if (!link_data.contains("data"))
      continue;

    link_data = link_data["data"].toMap();

    Image image;
    image.InitFromJson(link_data);

    // Update the last seen name - this must be done before skipping anything
    // for the case that we skip all the images in this set.
    last_seen_name_ = image.reddit_name();

    // Skip self posts
    if (!show_self_posts_ && link_data["is_self"].toBool())
      continue;

    // Check if this image has been viewed before
    if (app_->image_backend()->FindImage(image, &image)) {
      if (image.is_viewed() && !show_viewed_images_)
        continue;
    }

    // Adjust the URL to get just the image if we can.
    image.set_reddit_url(ResolveUrl(image.reddit_url()));

    // Create a Link object
    new_links << Link(image);

    // Start fetching the thumbnail
    if (!image.reddit_thumbnail_url().scheme().isEmpty()) {
      qLog(Debug) << "Fetching thumbnail" << image.reddit_thumbnail_url();

      QNetworkReply* reply = network_->get(QNetworkRequest(image.reddit_thumbnail_url()));
      NewClosure(reply, SIGNAL(finished()),
                 this, SLOT(ThumbnailFinished(QNetworkReply*,int)),
                 reply, row);
    }
Ejemplo n.º 20
0
void MainWindow::downloadChangelog()
{
    QNetworkAccessManager *manager = new QNetworkAccessManager();
    manager->get(QNetworkRequest(QUrl("http://maj.outadoc.fr/freestance/notes.txt")));
    QObject::connect(manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(askForUpdate(QNetworkReply *)));
}
Ejemplo n.º 21
0
void HSCardDownloader::downloadWebImage(QString code)
{
    QNetworkReply * reply = networkManager->get(QNetworkRequest(QUrl(QString(CARDS_URL + code + ".png"))));
    gettingWebCards[reply] = code;
    emit pDebug("Web Cards remaining(+1): " + QString::number(gettingWebCards.count()));
}
void tst_QMediaResource::assign()
{
    const QUrl url(QString::fromLatin1("http://test.com/test.mp4"));
    const QString mimeType(QLatin1String("video/mp4"));
    const QString amrCodec(QLatin1String("amr"));
    const QString mp3Codec(QLatin1String("mp3"));
    const QString aacCodec(QLatin1String("aac"));
    const QString h264Codec(QLatin1String("h264"));

    QNetworkRequest request(QUrl(QString::fromLatin1("http://test.com/test.mp4")));
    const qint64 dataSize(23600);
    int audioBitRate = 1, sampleRate = 2, channelCount = 3, videoBitRate = 4;
    QSize resolution(QSize(640, 480));
    QString language("eng");

    QMediaResource copy(QUrl(QString::fromLatin1("file:///thumbs/test.jpg")));

    QMediaResource original(url, mimeType);
    original.setAudioCodec(amrCodec);

    copy = original;

    QCOMPARE(copy.url(), url);
    QCOMPARE(copy.mimeType(), mimeType);
    QCOMPARE(copy.audioCodec(), amrCodec);

    QCOMPARE(original == copy, true);
    QCOMPARE(original != copy, false);

    original.setAudioCodec(mp3Codec);

    QCOMPARE(copy.audioCodec(), amrCodec);
    QCOMPARE(original == copy, false);
    QCOMPARE(original != copy, true);

    copy.setAudioCodec(aacCodec);
    copy.setVideoCodec(h264Codec);

    QCOMPARE(copy.url(), url);
    QCOMPARE(copy.mimeType(), mimeType);

    QCOMPARE(original.audioCodec(), mp3Codec);

    /* for constructor of QMediaresource(QNetworkrequest,mimeType)*/

    QMediaResource copy1(QNetworkRequest(QUrl(QString::fromLatin1("file:///thumbs/test.jpg"))));

    QMediaResource original1(request, mimeType);

    original1.setAudioCodec(amrCodec);
    original1.setLanguage(QString("eng"));
    original1.setVideoCodec(h264Codec);
    original1.setDataSize(dataSize);
    original1.setAudioBitRate(audioBitRate);
    original1.setSampleRate(sampleRate);
    original1.setChannelCount(channelCount);
    original1.setVideoBitRate(videoBitRate);
    original1.setResolution(resolution);

    copy1 = original1;

    QCOMPARE(original1 == copy1, true);
}
Ejemplo n.º 23
0
void SongkickConcerts::FetchSongkickCalendar(const QString& artist_id, int id) {
  QUrl url(QString(kSongkickArtistCalendarUrl).arg(artist_id));
  qLog(Debug) << url;
  QNetworkReply* reply = network_.get(QNetworkRequest(url));
  NewClosure(reply, SIGNAL(finished()), this, SLOT(CalendarRequestFinished(QNetworkReply*, int)), reply, id);
}
void tst_QMediaResource::construct_data()
{
    QTest::addColumn<QUrl>("url");
    QTest::addColumn<QNetworkRequest>("request");
    QTest::addColumn<QString>("mimeType");
    QTest::addColumn<QString>("language");
    QTest::addColumn<QString>("audioCodec");
    QTest::addColumn<QString>("videoCodec");
    QTest::addColumn<qint64>("dataSize");
    QTest::addColumn<int>("audioBitRate");
    QTest::addColumn<int>("sampleRate");
    QTest::addColumn<int>("channelCount");
    QTest::addColumn<int>("videoBitRate");
    QTest::addColumn<QSize>("resolution");

    QTest::newRow("audio content")
            << QUrl(QString::fromLatin1("http:://test.com/test.mp3"))
            << QNetworkRequest(QUrl(QString::fromLatin1("http:://test.com/test.mp3")))
            << QString::fromLatin1("audio/mpeg")
            << QString::fromLatin1("eng")
            << QString::fromLatin1("mp3")
            << QString()
            << qint64(5465433)
            << 128000
            << 44100
            << 2
            << 0
            << QSize();
    QTest::newRow("image content")
            << QUrl(QString::fromLatin1("http:://test.com/test.jpg"))
            << QNetworkRequest(QUrl(QString::fromLatin1("http:://test.com/test.jpg")))
            << QString::fromLatin1("image/jpeg")
            << QString()
            << QString()
            << QString()
            << qint64(23600)
            << 0
            << 0
            << 0
            << 0
            << QSize(640, 480);
    QTest::newRow("video content")
            << QUrl(QString::fromLatin1("http:://test.com/test.mp4"))
            << QNetworkRequest(QUrl(QString::fromLatin1("http:://test.com/test.mp4")))
            << QString::fromLatin1("video/mp4")
            << QString()
            << QString::fromLatin1("aac")
            << QString::fromLatin1("h264")
            << qint64(36245851)
            << 96000
            << 44000
            << 5
            << 750000
            << QSize(720, 576);
    QTest::newRow("thumbnail")
            << QUrl(QString::fromLatin1("file::///thumbs/test.png"))
            << QNetworkRequest(QUrl(QString::fromLatin1("file::///thumbs/test.png")))
            << QString::fromLatin1("image/png")
            << QString()
            << QString()
            << QString()
            << qint64(2360)
            << 0
            << 0
            << 0
            << 0
            << QSize(128, 128);
}
Ejemplo n.º 25
0
void NewstuffModelPrivate::handleProviderData(QNetworkReply *reply)
{
    if ( reply->operation() == QNetworkAccessManager::HeadOperation ) {
        const QVariant redirectionAttribute = reply->attribute( QNetworkRequest::RedirectionTargetAttribute );
        if ( !redirectionAttribute.isNull() ) {
            for ( int i=0; i<m_items.size(); ++i ) {
                NewstuffItem &item = m_items[i];
                if ( item.m_payloadUrl == reply->url() ) {
                    item.m_payloadUrl = redirectionAttribute.toUrl();
                }
            }
            m_networkAccessManager.head( QNetworkRequest( redirectionAttribute.toUrl() ) );
            return;
        }

        QVariant const size = reply->header( QNetworkRequest::ContentLengthHeader );
        if ( size.isValid() ) {
            qint64 length = size.value<qint64>();
            for ( int i=0; i<m_items.size(); ++i ) {
                NewstuffItem &item = m_items[i];
                if ( item.m_payloadUrl == reply->url() ) {
                    item.m_payloadSize = length;
                    QModelIndex const affected = m_parent->index( i );
                    emit m_parent->dataChanged( affected, affected );
                }
            }
        }
        return;
    }

    FetchPreviewJob *const job = m_networkJobs.take( reply );

    // check if we are redirected
    const QVariant redirectionAttribute = reply->attribute( QNetworkRequest::RedirectionTargetAttribute );
    if ( !redirectionAttribute.isNull() ) {
        QNetworkReply *redirectReply = m_networkAccessManager.get( QNetworkRequest( QUrl( redirectionAttribute.toUrl() ) ) );
        if ( job ) {
            m_networkJobs.insert( redirectReply, job );
        }
        return;
    }

    if ( job ) {
        job->run( reply->readAll() );
        delete job;
        return;
    }

    QDomDocument xml;
    if ( !xml.setContent( reply->readAll() ) ) {
        mDebug() << "Cannot parse newstuff xml data ";
        return;
    }

    m_items.clear();

    QDomElement root = xml.documentElement();
    QDomNodeList items = root.elementsByTagName( "stuff" );
#if QT_VERSION < 0x050000
    unsigned int i=0;
#else
    int i=0;
#endif
    for ( ; i < items.length(); ++i ) {
        m_items << importNode( items.item( i ) );
    }

    updateModel();
}
Ejemplo n.º 26
0
void WebserviceTTSProvider::fetch(const QString& url)
{
  currentConnection = net->get(QNetworkRequest(KUrl(url)));
  connect(currentConnection, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(downloadProgress(qint64,qint64)));
  connect(currentConnection, SIGNAL(finished()), this, SLOT(replyReceived()));
}
Ejemplo n.º 27
0
	void PendingDisco::handleLookupFinished ()
	{
		auto reply = qobject_cast<QNetworkReply*> (sender ());
		reply->deleteLater ();

		const auto& data = reply->readAll ();
		QDomDocument doc;
		if (!doc.setContent (data))
		{
			qWarning () << Q_FUNC_INFO
					<< "unable to parse"
					<< data;
			emit error (tr ("Unable to parse MusicBrainz reply."));
			deleteLater ();
		}

		QMap<QString, QMap<QString, Media::ReleaseInfo>> infos;

		auto releaseElem = doc
				.documentElement ()
				.firstChildElement ("artist")
				.firstChildElement ("release-list")
				.firstChildElement ("release");
		while (!releaseElem.isNull ())
		{
			std::shared_ptr<void> guard (nullptr,
					[&releaseElem] (void*)
						{ releaseElem = releaseElem.nextSiblingElement ("release"); });

			auto elemText = [&releaseElem] (const QString& sub)
			{
				return releaseElem.firstChildElement (sub).text ();
			};

			if (elemText ("status") != "Official")
				continue;

			const auto& dateStr = elemText ("date");
			const int dashPos = dateStr.indexOf ('-');
			const int date = (dashPos > 0 ? dateStr.left (dashPos) : dateStr).toInt ();
			if (date < 1000)
				continue;

			const auto& title = elemText ("title");
			if (!ReleaseName_.isEmpty () && title.toLower () != ReleaseName_)
				continue;

			infos [title] [elemText ("country")] =
			{
				releaseElem.attribute ("id"),
				title,
				date,
				Media::ReleaseInfo::Type::Standard,
				QList<QList<Media::ReleaseTrackInfo>> ()
			};
		}

		for (const auto& key : infos.keys ())
		{
			const auto& countries = infos [key];
			const auto& release = countries.contains ("US") ?
					countries ["US"] :
					countries.values ().first ();
			Releases_ << release;

			++PendingReleases_;

			const auto urlStr = "http://musicbrainz.org/ws/2/release/" + release.ID_ + "?inc=recordings";

			Queue_->Schedule ([this, urlStr] () -> void
				{
					auto reply = NAM_->get (QNetworkRequest (QUrl (urlStr)));
					connect (reply,
							SIGNAL (finished ()),
							this,
							SLOT (handleReleaseLookupFinished ()));
					connect (reply,
							SIGNAL (error (QNetworkReply::NetworkError)),
							this,
							SLOT (handleReleaseLookupError ()));
				}, this);
		}

		std::sort (Releases_.begin (), Releases_.end (),
				[] (decltype (Releases_.at (0)) left, decltype (Releases_.at (0)) right)
					{ return left.Year_ < right.Year_; });
	}
Ejemplo n.º 28
0
/**
 * @brief Starts loading a list of mirrors
 */
void TheTvDb::setMirrors()
{
    QUrl url(QString("http://www.thetvdb.com/api/%1/mirrors.xml").arg(m_apiKey));
    QNetworkReply *reply = qnam()->get(QNetworkRequest(url));
    connect(reply, SIGNAL(finished()), this, SLOT(onMirrorsReady()));
}
Ejemplo n.º 29
0
void DownloadFile::download(const QUrl& url)
{
    // Start the download
    manager->get(QNetworkRequest(url));
}
Ejemplo n.º 30
0
void sendUsageStatistics() {
  QNetworkAccessManager* mgr = new QNetworkAccessManager;
  QObject::connect(mgr,SIGNAL(finished(QNetworkReply*)),mgr,SLOT(deleteLater()));
  mgr->get(QNetworkRequest(QUrl(QString("http://tulip.labri.fr/TulipStats/tulip_stats.php?tulip=") + TULIP_VERSION + "&os=" + OS_PLATFORM)));
}