void
Ut_AboutBusinessLogic::testBluetooth ()
{
    QSignalSpy spy (
        m_Api,
        SIGNAL (requestFinished (AboutBusinessLogic::requestType, QVariant)));

    QMap <QString, QVariant> properties;
    properties["Address"] = QString ("fake-bluetooth-address");

    /*
     * Let's initiate the Bluetooth query that will call the
     * QDBusAbstractInterface::callWithCallback() that is stubbed.
     */
    m_Api->initiateBluetoothQueries ();
    QCOMPARE (lastCalledMethod, QString ("DefaultAdapter"));

    /*
     * Let's answer the previous step by calling the DBus callback manually.
     * This will initiate an other DBus call also stubbed.
     */
    m_Api->defaultBluetoothAdapterReceived (
            QDBusObjectPath("/fakeObjectPath"));
    QCOMPARE (lastCalledMethod, QString ("GetProperties"));

    /*
     * Answering the second DBus call and checking if the businesslogic
     * processed the data as it should.
     */
    m_Api->defaultBluetoothAdapterAddressReceived (properties);

    QTest::qWait (100);
    QCOMPARE (spy.count (), 1);

    QList<QVariant> args = spy.first ();

    QCOMPARE (args.at (0).value<AboutBusinessLogic::requestType>(),
              AboutBusinessLogic::reqBtAddr);
#if 0
    /* for some strange reason it is not working :-S */
    QCOMPARE (args.at (1).toString (), QString ("fake-bluetooth-address"));
#endif

    /*
     * Let's test the failure socket. This does not do nothing...
     */
    m_Api->DBusMessagingFailure (QDBusError());

    delete m_Api;
    /*
     * Let's see what happens if we initate the data collection and instead of
     * producing answers to queries we just destroy the object.
     */
    m_Api = new AboutBusinessLogic;
    m_Api->initiateBluetoothQueries ();
    //XXX: delete m_Api; (done in cleanup ())
}
Exemplo n.º 2
0
void DownloadItem::init() {
    if (!m_reply)
        return;

    if (m_file.exists())
        m_file.remove();

    m_status = Starting;

    m_startedSaving = false;
    m_finishedDownloading = false;

    // attach to the m_reply
    m_url = m_reply->url();
    connect(m_reply, SIGNAL(readyRead()), this, SLOT(downloadReadyRead()));
    connect(m_reply, SIGNAL(error(QNetworkReply::NetworkError)),
            this, SLOT(error(QNetworkReply::NetworkError)));
    connect(m_reply, SIGNAL(downloadProgress(qint64, qint64)),
            this, SLOT(downloadProgress(qint64, qint64)));
    connect(m_reply, SIGNAL(metaDataChanged()),
            this, SLOT(metaDataChanged()));
    connect(m_reply, SIGNAL(finished()),
            this, SLOT(requestFinished()));

    // start timer for the download estimation
    m_totalTime = 0;
    m_downloadTime.start();
    speedCheckTimer->start();

    if (m_reply->error() != QNetworkReply::NoError) {
        error(m_reply->error());
        requestFinished();
    }
}
Exemplo n.º 3
0
TrackerClient::TrackerClient(const QUrl &URL, const QByteArray &infoHash, const TrackerClientManager *manager, TrackerClientSocket *socket)
				: URL(URL), key(Utility::rand(Q_INT64_C(0xffffffff))), infoHash(infoHash),
				manager(manager), socket(socket),
				minimalRequestInterval(defaultMinimalRequestInterval),
				requestTimer(startTimer(defaultRequestInterval)), running(false)
{
	connect(dynamic_cast<QObject*>(socket), SIGNAL(requestFinished(QByteArray)), SLOT(requestFinished(QByteArray)));
}
Exemplo n.º 4
0
void CommentsModel::getComments(int offset, int count)
{
    if (m_session.data() && m_postId) {
        auto reply = m_session.data()->getComments(offset, count);
        connect(reply, SIGNAL(resultReady(QVariant)), SIGNAL(requestFinished()));
    }
}
Exemplo n.º 5
0
int JsonDbPartition::create(const QJSValue &object,  const QJSValue &options, const QJSValue &callback)
{
    QJSValue actualOptions = options;
    QJSValue actualCallback = callback;
    if (options.isCallable()) {
        if (!callback.isUndefined()) {
            qWarning() << "Callback should be the last parameter.";
            return -1;
        }
        actualCallback = actualOptions;
        actualOptions = QJSValue(QJSValue::UndefinedValue);
    }
    //#TODO ADD options
    QVariant obj = qjsvalue_to_qvariant(object);
    QJsonDbWriteRequest *request(0);
    if (obj.type() == QVariant::List) {
        request = new QJsonDbCreateRequest(qvariantlist_to_qjsonobject_list(obj.toList()));
    } else {
        request = new QJsonDbCreateRequest(QJsonObject::fromVariantMap(obj.toMap()));
    }
    request->setPartition(_name);
    connect(request, SIGNAL(finished()), this, SLOT(requestFinished()));
    connect(request, SIGNAL(finished()), request, SLOT(deleteLater()));
    connect(request, SIGNAL(error(QtJsonDb::QJsonDbRequest::ErrorCode,QString)),
            this, SLOT(requestError(QtJsonDb::QJsonDbRequest::ErrorCode,QString)));
    connect(request, SIGNAL(error(QtJsonDb::QJsonDbRequest::ErrorCode,QString)),
            request, SLOT(deleteLater()));
    JsonDatabase::sharedConnection().send(request);
    writeCallbacks.insert(request, actualCallback);
    return request->property("requestId").toInt();
}
Exemplo n.º 6
0
QNetworkReply* NetworkAccessManager::createRequest(QNetworkAccessManager::Operation operation,
    const QNetworkRequest &request, QIODevice *device)
{

    qint64 time;
    if (isListener) {
        time = QDateTime::currentDateTime().toMSecsSinceEpoch();
    }

    QNetworkReply *reply = QNetworkAccessManager::createRequest(operation, request, device);
    reply->ignoreSslErrors();
    if (isListener) {
       // 触发请求开始的自定义信号
       emit requestStart(request.url().toString());

       // 不清除这个指针
       // TODO: 该类由 webview 接管处理
       CustomDownload* customDownload = new CustomDownload(reply, request,
                           QDateTime::currentDateTime().toMSecsSinceEpoch() - time,
                           time);

       connect(customDownload, SIGNAL(requestFinished(QString)),
               this, SLOT(onRequestFinished(QString)));
    }

    return reply;
}
Exemplo n.º 7
0
void MyWebView::initEvents()
{
    // 委托页面所有连接在当前视图中打开
    myPage->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
    connect(myPage, SIGNAL(linkClicked(QUrl)), this, SLOT(onOpenUrl(QUrl)));

    // 对所有事件添加信号槽
    connect(myFrame, SIGNAL(loadFinished(bool)), this, SLOT(onLoadFinished(bool)));
    connect(myFrame, SIGNAL(javaScriptWindowObjectCleared()), this, SLOT(onJavaScriptWindowObjectCleared()));
    connect(myFrame, SIGNAL(initialLayoutCompleted()), this, SLOT(onInitialLayoutCompleted()));
    connect(myFrame, SIGNAL(pageChanged()), this, SLOT(onPageChanged()));
    connect(myFrame, SIGNAL(contentsSizeChanged(const QSize)), this, SLOT(onContentsSizeChanged(const QSize)));
    connect(myFrame, SIGNAL(iconChanged()), this, SLOT(onIconChanged()));
    connect(myFrame, SIGNAL(loadStarted()), this, SLOT(onLoadStarted()));
    connect(myFrame, SIGNAL(titleChanged(const QString)), this, SLOT(onTitleChanged(const QString)));
    connect(myFrame, SIGNAL(urlChanged(const QUrl)), this, SLOT(onUrlChanged(const QUrl)));

    connect(myPage, SIGNAL(loadProgress(int)), this, SLOT(onLoadProgress(int)));
    connect(myPage, SIGNAL(repaintRequested(const QRect)), this, SLOT(onRepaintRequested(const QRect)));
    connect(myPage, SIGNAL(geometryChangeRequested(const QRect)), this, SLOT(onGeometryChangeRequested(const QRect)));

    connect(newManager, SIGNAL(requestFinished(QString)),
            this, SLOT(onRequestFinished(QString)));
    connect(newManager, SIGNAL(requestStart(QString)),
            this, SLOT(onRequestStart(QString)));
};
Exemplo n.º 8
0
/*!
 * \brief DocumentationViewer::processLinkClick
 * \param url
 * Slot activated when linkClicked signal of webview is raised.
 * Handles the link processing. Sends all the http starting links to the QDesktopServices and process all Modelica starting links.
 */
void DocumentationViewer::processLinkClick(QUrl url)
{
  // Send all http requests to desktop services for now.
  // if url contains http or mailto: send it to desktop services
  if ((url.toString().startsWith("http")) || (url.toString().startsWith("mailto:"))) {
    QDesktopServices::openUrl(url);
  } else if (url.scheme().compare("modelica") == 0) { // if the user has clicked on some Modelica Links like modelica://
    // remove modelica:/// from Qurl
    QString resourceLink = url.toString().mid(12);
    /* if the link is a resource e.g .html, .txt or .pdf */
    if (resourceLink.endsWith(".html") || resourceLink.endsWith(".txt") || resourceLink.endsWith(".pdf")) {
      QString resourceAbsoluteFileName = mpDocumentationWidget->getMainWindow()->getOMCProxy()->uriToFilename("modelica://" + resourceLink);
      QDesktopServices::openUrl("file:///" + resourceAbsoluteFileName);
    } else {
      LibraryTreeItem *pLibraryTreeItem = mpDocumentationWidget->getMainWindow()->getLibraryWidget()->getLibraryTreeModel()->findLibraryTreeItem(resourceLink);
      // send the new className to DocumentationWidget
      if (pLibraryTreeItem) {
        mpDocumentationWidget->showDocumentation(pLibraryTreeItem);
      }
    }
  } else { // if it is normal http request then check if its not redirected to https
    QNetworkAccessManager* accessManager = page()->networkAccessManager();
    QNetworkRequest request(url);
    QNetworkReply* reply = accessManager->get(request);
    connect(reply, SIGNAL(finished()), SLOT(requestFinished()));
  }
}
Exemplo n.º 9
0
void MusicCollector::loadList()
{
    if (playlistId == 0) {
        if (nextOperation == OperationNone) {
            nextOperation = OperationLoadPlaylist;
            operatingId.clear();
        }

        if (!currentReply || currentReply->property(KeyOperation).toInt() != OperationLoadPid) {
            refresh();
        }

        return;
    }

    if (currentReply && currentReply->isRunning())
        currentReply->abort();

    QUrl url(QString(ApiBaseUrl).append("/v2/playlist/detail"));
    url.addEncodedQueryItem("id", QByteArray::number(playlistId));
    url.addEncodedQueryItem("t", "-1");
    url.addEncodedQueryItem("n", "1000");
    url.addEncodedQueryItem("s", "0");

    checkNAM();

    currentReply = manager->get(QNetworkRequest(url));
    currentReply->setProperty(KeyOperation, OperationLoadPlaylist);
    connect(currentReply, SIGNAL(finished()), SLOT(requestFinished()), Qt::QueuedConnection);

    emit loadingChanged();
}
/*!
 * Uses Qt Highway to send 'addWidget' request to home screen application.
 * \a uri and \a preferences as in widget model.
 */
void HsHomescreenClient::doAddWidget(
    const QString &uri, 
    const QVariantHash &preferences)
{
    delete mAsyncRequest;
    mAsyncRequest = 0;
    mAsyncRequest = new XQServiceRequest(INTERFACE_NAME,
                       "addWidget(QString,QVariantHash)", false);
    
    XQRequestInfo requestInfo = mAsyncRequest->info();
    requestInfo.setBackground(true);
    mAsyncRequest->setInfo(requestInfo);
    
    *mAsyncRequest << uri;
    *mAsyncRequest << preferences;
    
    connect(mAsyncRequest, SIGNAL(requestCompleted(QVariant)), 
            SLOT(onRequestCompleted(QVariant)));
    connect(mAsyncRequest, SIGNAL(requestError(int)), 
            SLOT(onRequestError(int)));
       
    mRequestResult = false;
    if (!mAsyncRequest->send()) {
       emit requestFinished();
    }
}
Exemplo n.º 11
0
void MusicCollector::removeCollection(const QString &id)
{
    if (id.toInt() == 0) return;

    if (playlistId == 0) {
        nextOperation = OperationRemoveCollection;
        operatingId = id;

        if (!currentReply || currentReply->property(KeyOperation).toInt() != OperationLoadPid) {
            refresh();
        }

        return;
    }

    if (currentReply && currentReply->isRunning())
        currentReply->abort();

    QNetworkRequest req;
    req.setUrl(QString(ApiBaseUrl).append("/playlist/manipulate/tracks"));
    req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");

    QByteArray postData;
    postData.append("trackIds=").append(QString("[%1]").arg(id).toAscii().toPercentEncoding());
    postData.append("&pid=").append(QByteArray::number(playlistId));
    postData.append("&op=del");

    checkNAM();

    currentReply = manager->post(req, postData);
    currentReply->setProperty(KeyOperation, OperationRemoveCollection);
    connect(currentReply, SIGNAL(finished()), SLOT(requestFinished()), Qt::QueuedConnection);

    emit loadingChanged();
}
Exemplo n.º 12
0
void UpdateChecker::checkForUpdate() {
    QUrl url(QLatin1String(Constants::WEBSITE) + "-ws/release.xml");

    {
        QUrlQueryHelper urlHelper(url);
        urlHelper.addQueryItem("v", Constants::VERSION);

#ifdef APP_MAC
        urlHelper.addQueryItem("os", "mac");
#endif
#ifdef APP_WIN
        urlHelper.addQueryItem("os", "win");
#endif
#ifdef APP_ACTIVATION
        QString t = "demo";
        if (Activation::instance().isActivated()) t = "active";
        urlHelper.addQueryItem("t", t);
#endif
#ifdef APP_MAC_STORE
        urlHelper.addQueryItem("store", "mac");
#endif
    }

    QObject *reply = The::http()->get(url);
    connect(reply, SIGNAL(data(QByteArray)), SLOT(requestFinished(QByteArray)));

}
Exemplo n.º 13
0
void Cinema::initFromXml(const QDomElement& e)
{
	Q_ASSERT(e.tagName() == "cinema");
	clear();

	id_ = XMLHelper::subTagText(e, "id");
	name_ = XMLHelper::subTagText(e, "name");
	address_ = XMLHelper::subTagText(e, "address");
	metro_ = XMLHelper::subTagText(e, "metro");
	details_ = XMLHelper::subTagText(e, "details");
	ll_ = XMLHelper::subTagText(e, "ll");

	if (!e.attribute("detailed").isEmpty()) {
		hasDetailedInfo_ = true;
		finishedProgress_ = 50;

		if (!address_.isEmpty() && ll_.isEmpty() && !XMLHelper::hasSubTag(e, "ll")) {
			Geocoder* geocoder = new Geocoder(QString("%1_geocoder_%2")
			                                  .arg(AfishaHelpers::cinemaCacheDate())
			                                  .arg(id_), this);
			request_ = geocoder;
			connect(geocoder, SIGNAL(finished()), SLOT(requestFinished()));
			geocoder->request(address_);
		}
		else {
			finishedProgress_ = 100;
		}

		// if (!details_.isEmpty())
			// qWarning() << id_ << name_ << address_ << metro_;
	}

	emit dataChanged();
}
Exemplo n.º 14
0
void MediaDownloadTask::start(const QUrl &url, const QList<QNetworkCookie> &cookies, unsigned position,
                              unsigned size)
{
    Q_ASSERT(!m_reply);

    if (!threadNAM.hasLocalData())
    {
        threadNAM.setLocalData(new QNetworkAccessManager);
        /* XXX certificate validation */
    }

    threadNAM.localData()->cookieJar()->setCookiesFromUrl(cookies, url);
    if (threadNAM.localData()->cookieJar()->cookiesForUrl(url).isEmpty())
        qDebug() << "MediaDownload: No cookies for media URL, likely to fail authentication";

    QNetworkRequest req(url);
    if (position || size)
    {
        QByteArray range = "bytes=" + QByteArray::number(position) + "-";
        if (size)
            range += QByteArray::number(position + size);
        req.setRawHeader("Range", range);
    }

    m_writePos = position;

    m_reply = threadNAM.localData()->get(req);
    m_reply->ignoreSslErrors(); // XXX Do this properly!
    connect(m_reply, SIGNAL(metaDataChanged()), SLOT(metaDataReady()));
    connect(m_reply, SIGNAL(readyRead()), SLOT(read()));
    connect(m_reply, SIGNAL(finished()), SLOT(requestFinished()));
}
Exemplo n.º 15
0
void NewsFeedModel::getNews(int filters, quint8 count, int offset)
{
    if (m_newsFeed.isNull())
        return;

    auto reply = m_newsFeed.data()->getNews(static_cast<Vreen::NewsFeed::Filters>(filters), count, offset);
    connect(reply, SIGNAL(resultReady(QVariant)), SIGNAL(requestFinished()));
}
Exemplo n.º 16
0
void SM_QDropbox::networkReplyFinished(QNetworkReply *rply)
{
#ifdef SM_QTDROPBOX_DEBUG
    qDebug() << "reply finished" << endl;
#endif
    int reqnr = replynrMap[rply];
    requestFinished(reqnr, rply);
    rply->deleteLater(); // release memory
}
Exemplo n.º 17
0
CategoryInitReply::CategoryInitReply(QPlaceManagerEngineJsonDb *engine)
    : QPlaceReply(engine),
      m_engine(engine),
      m_traverser(new CategoryTraverser(m_engine->db(), this))
{
    Q_ASSERT(m_traverser);
    connect(m_traverser, SIGNAL(finished()),
            this, SLOT(requestFinished()));
}
Exemplo n.º 18
0
void QQuickImageBase::load()
{
    Q_D(QQuickImageBase);

    if (d->url.isEmpty()) {
        d->pix.clear(this);
        if (d->progress != 0.0) {
            d->progress = 0.0;
            emit progressChanged(d->progress);
        }
        pixmapChange();
        d->status = Null;
        emit statusChanged(d->status);

        if (sourceSize() != d->oldSourceSize) {
            d->oldSourceSize = sourceSize();
            emit sourceSizeChanged();
        }
        update();

    } else {
        QQuickPixmap::Options options;
        if (d->async)
            options |= QQuickPixmap::Asynchronous;
        if (d->cache)
            options |= QQuickPixmap::Cache;
        d->pix.clear(this);
        d->pix.load(qmlEngine(this), d->url, d->sourcesize, options);

        if (d->pix.isLoading()) {
            if (d->progress != 0.0) {
                d->progress = 0.0;
                emit progressChanged(d->progress);
            }
            if (d->status != Loading) {
                d->status = Loading;
                emit statusChanged(d->status);
            }

            static int thisRequestProgress = -1;
            static int thisRequestFinished = -1;
            if (thisRequestProgress == -1) {
                thisRequestProgress =
                    QQuickImageBase::staticMetaObject.indexOfSlot("requestProgress(qint64,qint64)");
                thisRequestFinished =
                    QQuickImageBase::staticMetaObject.indexOfSlot("requestFinished()");
            }

            d->pix.connectFinished(this, thisRequestFinished);
            d->pix.connectDownloadProgress(this, thisRequestProgress);
            update(); //pixmap may have invalidated texture, updatePaintNode needs to be called before the next repaint
        } else {
            requestFinished();
        }
    }
}
// Request methods
void CommunicationDescriptionGateway::setupRequestConnections() {
//    this->disconnect();
    connect(networkRequest, SIGNAL(responseDownloaded(QByteArray)), this, SLOT(requestReceived(QByteArray)));
    connect(networkRequest, SIGNAL(finished()), this, SLOT(requestFinished()));
    connect(networkRequest, SIGNAL(authenticationChallenge()), this, SLOT(authenticationChallenge()));
    // failed connections
    connect(networkRequest, SIGNAL(failedToSendRequest()), this, SLOT(requestFailed()));
    connect(networkRequest, SIGNAL(noNetworkConnection()), this, SLOT(requestFailed()));
    connect(networkRequest, SIGNAL(requestTimedOut()), this, SLOT(requestFailed()));
}
/*!
  \internal

  Executes the request.
*/
bool FacebookRequest::executeRequest()
{
    if (m_graphPath.isEmpty()) {
        FacebookReply *facebookReply =
                new FacebookReply(QByteArray(), true, FacebookReply::OAuthGeneralError,
                                  "Facebook error. Invalid graph path.", this);
        emit requestFinished(this, facebookReply);
        delete facebookReply;
        return false;
    }

    bool ret = true;

    QNetworkRequest request(Util::generateUrl(m_graphPath, m_parameters));
    qDebug() << "FacebookRequest::executeRequest - URL:" << request.url();

    switch (m_method) {
    case FacebookConnection::HTTPPost:
        request.setRawHeader("Content-Type",
                             QString("multipart/form-data; boundary=%1")
                             .arg(Boundary).toAscii());
        m_ongoingRequest = m_networkAccess->post(request, Util::generateBody(m_parameters));
        break;
    case FacebookConnection::HTTPGet:
        m_ongoingRequest = m_networkAccess->get(request);
        break;
    case FacebookConnection::HTTPDelete:
        m_ongoingRequest = m_networkAccess->deleteResource(request);
        break;
    default: {
        FacebookReply *facebookReply =
                new FacebookReply(QByteArray(), true,
                                  FacebookReply::OAuthGeneralError,
                                  "Facebook error. Invalid request method.",
                                  this);
        emit requestFinished(this, facebookReply);
        delete facebookReply;
        ret = false;
    }
    }

    return ret;
}
Exemplo n.º 21
0
void QQTMRequester::parsingFinished()
{
	m_totozes.append(m_xmlParser->totozes());

	if(m_xmlParser->numResults() > 0 &&
			m_totozes.size() < m_xmlParser->numResults())
		searchTotoz(m_currKey, m_totozes.size());
	else
		emit requestFinished();
}
Exemplo n.º 22
0
/*!
  Slot that starts initialization of the Document Gallery queries.
*/
void ImageScaler::init()
{
    m_documentGallery = new QDocumentGallery(this);
    m_galleryQuery = new QGalleryQueryRequest(m_documentGallery, this);
    connect(m_galleryQuery, SIGNAL(finished()),
            this, SLOT(requestFinished()));
    connect(m_galleryQuery, SIGNAL(error(int,QString)),
            this, SLOT(requestError()));

    qDebug() << "ImageScaler object constructed & initialized!";
}
Exemplo n.º 23
0
void GetById::exec()
{
  QMap<QString, QString> map;
  if( !d->token.isEmpty() )
  {
    map.insert("access_token", d->token);
    map.insert("audios", d->audios.join(","));
    m_request = new Vk::VkCustomRequest("audio.getById", map);
    connect(m_request, SIGNAL(result(QVariant)), this, SLOT(requestFinished(QVariant)));
    m_request->exec();    
  }
}
void CommandDownloadFile::reexecuteQuery()
{
    Q_D(CommandDownloadFile);
    QNetworkRequest request( d->downloadUrl );
    setRequestAccessToken(request, session()->accessToken());
    QNetworkReply* reply = session()->networkManager()->get(request);
    reply->setReadBufferSize(d->bufferSize);
    connect(reply, SIGNAL(finished()), SLOT(requestFinished()));
    connect(reply, SIGNAL(readyRead()), SLOT(readyRead()));
    connect(reply, SIGNAL(downloadProgress(qint64,qint64)), SIGNAL(progress(qint64,qint64)));
    reply->setParent(this);
}
/*!
    Adds new widget, with the given \a uri and \a preferences, 
    to the active home screen page.
    Note that \a preferences is dependent on the 
    widget implementation and it can be empty if widget does not have any preferences see @ref sssection_setpreferences. 
 */
bool HsHomescreenClient::addWidget(
    const QString &uri, 
    const QVariantHash &preferences)
{
    QEventLoop eventLoop;
    connect(this, SIGNAL(requestFinished()), &eventLoop, SLOT(quit()));
    QMetaObject::invokeMethod(this, "doAddWidget", Qt::QueuedConnection,
            Q_ARG(QString,uri),Q_ARG(QVariantHash,preferences));
    eventLoop.exec();
   
    return mRequestResult;
}
Exemplo n.º 26
0
void HttpGet::httpFinished(int id, bool error)
{
    qDebug() << "[HTTP] Request finished:" << id << "Error:" << error
             << "pending requests:" << http.hasPendingRequests();
    if(id == getRequest) {
        dataBuffer = http.readAll();
        emit requestFinished(id, error);
    }

    if(id == headRequest) {
        QHttpResponseHeader h = http.lastResponse();

        QString date = h.value("Last-Modified").simplified();
        if(date.isEmpty()) {
            m_serverTimestamp = QDateTime(); // no value = invalid
            emit headerFinished();
            return;
        }
        // to successfully parse the date strip weekday and timezone
        date.remove(0, date.indexOf(" ") + 1);
        if(date.endsWith("GMT"))
            date.truncate(date.indexOf(" GMT"));
        // distinguish input formats (see RFC1945)
        // RFC 850
        if(date.contains("-"))
            m_serverTimestamp = QLocale::c().toDateTime(date, "dd-MMM-yy hh:mm:ss");
        // asctime format
        else if(date.at(0).isLetter())
            m_serverTimestamp = QLocale::c().toDateTime(date, "MMM d hh:mm:ss yyyy");
        // RFC 822
        else
            m_serverTimestamp = QLocale::c().toDateTime(date, "dd MMM yyyy hh:mm:ss");
        qDebug() << "[HTTP] HEAD finished, server date:" << date << ", parsed:" << m_serverTimestamp;
        emit headerFinished();
        return;
    }
    if(id == getRequest)
        emit requestFinished(id, error);
}
/*!
   Sets wallpaper \a fileName. Filename should include full path to the image file.
 */
bool HsHomescreenClient::setWallpaper(const QString &fileName)
{
    QEventLoop eventLoop;
    connect(this, SIGNAL(requestFinished()), &eventLoop, SLOT(quit()));
    QMetaObject::invokeMethod(
            this, 
            "doSetWallpaper", 
            Qt::QueuedConnection,
            Q_ARG(QString,fileName));
    eventLoop.exec();
   
    return mRequestResult;
}
Exemplo n.º 28
0
void GetPocketApi::handleRequestAccessToken()
{
    emit requestFinished(true);

    auto reply = qobject_cast<QNetworkReply*> (sender());
    if (!reply)
    {
        qWarning() << "Invalid reply";
        emit error(tr("General error"), 503, ETGeneral);
        return;
    }
    reply->deleteLater();

    bool result = false;
    if (reply->error() != QNetworkReply::NoError &&
            reply->error() != QNetworkReply::UnknownContentError &&
            reply->error() != QNetworkReply::UnknownNetworkError &&
            reply->error() != m_InvalidRequestError &&
            reply->error() != m_AuthError &&
            reply->error() != m_PermissionsRateError &&
            reply->error() != m_MaintenanceError &&
            reply->error() != QNetworkReply::ContentOperationNotPermittedError)
    {
        qWarning() << Q_FUNC_INFO << "There is network error: "
                << reply->error() << reply->errorString();
        emit error(tr("Network error: %1").arg(reply->errorString()), reply->error(), ETGeneral);
    }
    else if (reply->error() != QNetworkReply::NoError)
    {
        const int errorCode = reply->rawHeader("X-Error-Code").toInt();
        const QString errorString = reply->rawHeader("X-Error");
        qWarning() << Q_FUNC_INFO << "There is getpocket error: "
                << errorCode << errorString;
        emit error(errorString, errorCode, ETGetPocket);
        emit logged(result, QString(), QString());
        return;
    }

    QJsonParseError err;
    QJsonDocument doc = QJsonDocument::fromJson(reply->readAll(), &err);
    if (err.error != QJsonParseError::NoError)
    {
        qWarning() << "Unable to generate json from reply";
        emit error(tr("Reply data is corrupted"), 503, ETGetPocket);
    }

    const auto& accessToken = doc.object()["access_token"].toString();
    const auto& userName = doc.object()["username"].toString();
    result = !accessToken.isEmpty() && !userName.isEmpty();
    emit logged(result, accessToken, userName);
}
Exemplo n.º 29
0
int qmapcontrol::MapNetwork::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QObject::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        switch (_id) {
        case 0: requestFinished((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< bool(*)>(_a[2]))); break;
        default: ;
        }
        _id -= 1;
    }
    return _id;
}
Exemplo n.º 30
0
void MainWindow::init()
{
    initQsettings();

    QVBoxLayout * layout  = new QVBoxLayout();

    // create MapControl
    mc = new MapControl(QSize(ui->tabWidget->width() - 25, ui->tabWidget->height() - 60));

    mc->showScale(true);

    // create MapAdapter to get maps from
    mapadapter = new OSMMapAdapter();

    // create a map layer with the mapadapter
    Layer* l = new MapLayer("Custom Layer", mapadapter);

    // add Layer to the MapControl
    mc->addLayer(l);
    layout->addWidget(mc);
    ui->tab->setLayout(layout);

    // Paris
    mc->setView(QPointF(2.3522219,48.856614));

    mc->setZoom(11);

    connect(mc, SIGNAL(mouseEventCoordinate(const QMouseEvent*,QPointF)),
            this, SLOT(clickInTheWorld(const QMouseEvent*,QPointF)));

    connect(&ws, SIGNAL(requestFinished()), this, SLOT(wsFinished()));

    connect(settingView, SIGNAL(newCategorie(QString)), this, SLOT(addCategorie(QString)));
    connect(ui->listView,SIGNAL(clicked(QModelIndex)),this,SLOT(filtrer(QModelIndex)));

    details->setParent(this);

    addZoomButton();
    drawTabWidgetContent();

    fillFiltre();

    ui->menuBar->setVisible(true);
    connect(ui->menuBar, SIGNAL(triggered(QAction*)),
            this, SLOT(languageChanged(QAction*)));

    connect(ui->menuAide,SIGNAL(triggered(QAction*)),this,SLOT(on_ActionModeEmploi(QAction*)));

}