Пример #1
0
void Posterous::slotUpload(KJob *job)
{
    QUrl localUrl = mUrlMap.take(job);
    if (job->error()) {
        qCritical() << "Job Error:" << job->errorString();
        Q_EMIT uploadingFailed(localUrl, job->errorString());
        return;
    } else {
        KIO::StoredTransferJob *stj = qobject_cast<KIO::StoredTransferJob *>(job);
        //qDebug() << stj->data();
        const QJsonDocument json = QJsonDocument::fromJson(stj->data());
        if (!json.isNull()) {
            const QVariantMap map = json.toVariant().toMap();
            if (map.contains(QLatin1String("error"))) {
                Q_EMIT uploadingFailed(localUrl, map.value(QLatin1String("error")).toString());
            } else {
                if (PosterousSettings::oauth()) {
                    Q_EMIT mediumUploaded(localUrl, map.value(QLatin1String("url")).toString());
                }
                if (PosterousSettings::basic()) {
                    Q_EMIT mediumUploaded(localUrl, map.value(QLatin1String("full_url")).toString());
                }
            }
        } else {
            Q_EMIT uploadingFailed(localUrl, i18n("Malformed response"));
            qWarning() << "Parse error:" << stj->data();
        }
    }
}
Пример #2
0
void LaconicaSearch::searchResultsReturned(KJob* job)
{
    kDebug();
    if( job == 0 ) {
        kDebug() << "job is a null pointer";
        emit error( i18n( "Unable to fetch search results." ) );
        return;
    }

    SearchInfo info = mSearchJobs.take(job);

    if( job->error() ) {
        kError() << "Error: " << job->errorString();
        emit error( i18n( "Unable to fetch search results: %1", job->errorString() ) );
        return;
    }
    KIO::StoredTransferJob *jj = qobject_cast<KIO::StoredTransferJob *>( job );
    QList<Choqok::Post*> postsList;
    if(info.option == ReferenceHashtag)
        postsList = parseAtom( jj->data() );
    else
        postsList = parseRss( jj->data() );

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

    return QString();
}
Пример #4
0
void TwitterMicroBlog::slotFetchUserLists(KJob *job)
{
    qCDebug(CHOQOK);
    if (!job) {
        qCWarning(CHOQOK) << "NULL Job returned";
        return;
    }
    QString username = mFetchUsersListMap.take(job);
    Choqok::Account *theAccount = mJobsAccount.take(job);
    if (job->error()) {
        qCDebug(CHOQOK) << "Job Error:" << job->errorString();
        Q_EMIT error(theAccount, Choqok::MicroBlog::CommunicationError,
                     i18n("Fetching %1's lists failed. %2", username, job->errorString()), Critical);
    } else {
        KIO::StoredTransferJob *stj = qobject_cast<KIO::StoredTransferJob *> (job);
        QByteArray buffer = stj->data();
        QList<Twitter::List> list = readUserListsFromJson(theAccount, buffer);
        if (list.isEmpty()) {
            qCDebug(CHOQOK) << buffer;
            QString errorMsg;
            errorMsg = checkForError(buffer);
            if (errorMsg.isEmpty()) {
                KMessageBox::information(choqokMainWindow, i18n("There is no list record for user %1", username));
            } else {
                Q_EMIT error(theAccount, ServerError, errorMsg, Critical);
            }
        } else {
            Q_EMIT userLists(theAccount, username, list);
        }
    }
}
Пример #5
0
void ArchiveOrg::slotParseResults(KJob* job)
{
    KIO::StoredTransferJob* storedQueryJob = static_cast<KIO::StoredTransferJob*>( job );
    QDomDocument doc;
    doc.setContent(QString::fromUtf8(storedQueryJob->data()));
    QDomNodeList links = doc.elementsByTagName(QStringLiteral("a"));
    QString html = QStringLiteral("<style type=\"text/css\">tr.cellone {background-color: %1;}").arg(qApp->palette().alternateBase().color().name());
    html += QLatin1String("</style><table width=\"100%\" cellspacing=\"0\" cellpadding=\"2\">");
    QString link;
    int ct = 0;
    m_thumbsPath.clear();
    for (int i = 0; i < links.count(); ++i) {
        QString href = links.at(i).toElement().attribute(QStringLiteral("href"));
        if (href.endsWith(QLatin1String(".thumbs/"))) {
            // sub folder contains image thumbs, display one.
            m_thumbsPath = m_metaInfo.value(QStringLiteral("url")) + '/' + href;
            KJob* thumbJob = KIO::storedGet( QUrl(m_thumbsPath), KIO::NoReload, KIO::HideProgressInfo );
            thumbJob->setProperty("id", m_metaInfo.value(QStringLiteral("id")));
            connect(thumbJob, &KJob::result, this, &ArchiveOrg::slotParseThumbs);
        }
        else if (!href.contains('/') && !href.endsWith(QLatin1String(".xml"))) {
            link = m_metaInfo.value(QStringLiteral("url")) + '/' + href;
            ct++;
            if (ct %2 == 0) {
                html += QLatin1String("<tr class=\"cellone\">");
            }
            else html += QLatin1String("<tr>");
            html += "<td>" + QUrl(link).fileName() + QStringLiteral("</td><td><a href=\"%1\">%2</a></td><td><a href=\"%3\">%4</a></td></tr>").arg(link).arg(i18n("Preview")).arg(link + "_import").arg(i18n("Import"));
        }
    }
    html += QLatin1String("</table>");
    if (m_metaInfo.value(QStringLiteral("id")) == job->property("id").toString()) emit gotMetaInfo(html);
}
Пример #6
0
    void Core::downloadFinished(KJob* job)
    {
        KIO::StoredTransferJob* j = (KIO::StoredTransferJob*)job;
        int err = j->error();
        if (err == KIO::ERR_USER_CANCELED)
            return;

        if (err)
        {
            gui->errorMsg(j);
        }
        else
        {
            // load in the file (target is always local)
            QString group;
            QMap<KUrl, QString>::iterator i = add_to_groups.find(j->url());
            if (i != add_to_groups.end())
            {
                group = i.value();
                add_to_groups.erase(i);
            }

            QString dir = locationHint(group);
            if (dir != QString::null)
                loadFromData(j->data(), dir, group, false, j->url());
        }
    }
Пример #7
0
void OpenClipArt::slotShowResults(KJob* job)
{
    if (job->error() != 0 ) return;
    m_listWidget->blockSignals(true);    
    KIO::StoredTransferJob* storedQueryJob = static_cast<KIO::StoredTransferJob*>( job );
    
    QDomDocument doc;
    doc.setContent(QString::fromLatin1(storedQueryJob->data()));
    QDomNodeList items = doc.documentElement().elementsByTagName("item");
    for (int i = 0; i < items.count(); ++i) {
        QDomElement currentClip = items.at(i).toElement();
        QDomElement title = currentClip.firstChildElement("title");
        QListWidgetItem *item = new QListWidgetItem(title.firstChild().nodeValue(), m_listWidget);
        QDomElement thumb = currentClip.firstChildElement("media:thumbnail");
        item->setData(imageRole, thumb.attribute("url"));
        QDomElement enclosure = currentClip.firstChildElement("enclosure");
        item->setData(downloadRole, enclosure.attribute("url"));
        QDomElement link = currentClip.firstChildElement("link");
        item->setData(infoUrl, link.firstChild().nodeValue());
        QDomElement license = currentClip.firstChildElement("cc:license");
        item->setData(licenseRole, license.firstChild().nodeValue());
        QDomElement desc = currentClip.firstChildElement("description");
        item->setData(descriptionRole, desc.firstChild().nodeValue());
        QDomElement author = currentClip.firstChildElement("dc:creator");
        item->setData(authorRole, author.firstChild().nodeValue());
        item->setData(authorUrl, QString("http://openclipart.org/user-detail/") + author.firstChild().nodeValue());
    }        
    m_listWidget->blockSignals(false);
    m_listWidget->setCurrentRow(0);
    emit searchDone();
}
Пример #8
0
void ManPageDocumentation::finished(KJob* j)
{
    KIO::StoredTransferJob* job = qobject_cast<KIO::StoredTransferJob*>(j);
    if(job && job->error()==0) {
        m_description = QString::fromUtf8(job->data());
    } else {
        m_description.clear();
    }
    emit descriptionChanged();
}
Пример #9
0
	void HTTPTracker::onScrapeResult(KJob* j)
	{
		if (j->error())
		{
			Out(SYS_TRK | LOG_IMPORTANT) << "Scrape failed : " << j->errorString() << endl;
			return;
		}

		KIO::StoredTransferJob* st = (KIO::StoredTransferJob*)j;
		BDecoder dec(st->data(), false, 0);
		BNode* n = 0;

		try
		{
			n = dec.decode();
		}
		catch (bt::Error & err)
		{
			Out(SYS_TRK | LOG_IMPORTANT) << "Invalid scrape data " << err.toString() << endl;
			return;
		}

		if (n && n->getType() == BNode::DICT)
		{
			BDictNode* d = (BDictNode*)n;
			d = d->getDict(QString("files"));
			if (d)
			{
				d = d->getDict(tds->infoHash().toByteArray());
				if (d)
				{
					try
					{
						seeders = d->getInt("complete");
						leechers = d->getInt("incomplete");
						total_downloaded = d->getInt("downloaded");
						supports_partial_seed_extension = d->getValue("downloaders") != 0;
						Out(SYS_TRK | LOG_DEBUG) << "Scrape : leechers = " << leechers
						<< ", seeders = " << seeders << ", downloaded = " << total_downloaded << endl;
					}
					catch (...)
						{}
					scrapeDone();
					if (status == bt::TRACKER_ERROR)
					{
						status = bt::TRACKER_OK;
						failures = 0;
					}
				}
			}
		}

		delete n;
	}
Пример #10
0
void ArchiveOrg::slotShowResults(KJob* job)
{
    if (job->error() != 0 ) return;
    m_listWidget->blockSignals(true);
    KIO::StoredTransferJob* storedQueryJob = static_cast<KIO::StoredTransferJob*>( job );
    QJsonParseError jsonError;
    QJsonDocument doc = QJsonDocument::fromJson(storedQueryJob->data(), &jsonError);
    if (jsonError.error != QJsonParseError::NoError) {
        // There was an error parsing data
        KMessageBox::sorry(m_listWidget, jsonError.errorString(), i18n("Error Loading Data"));
    }
    QVariant data = doc.toVariant();
    
    QVariant sounds;
    if (data.canConvert(QVariant::Map)) {
        QMap <QString, QVariant> map = data.toMap();
        QMap<QString, QVariant>::const_iterator i = map.constBegin();
        while (i != map.constEnd()) {
            if (i.key() == QLatin1String("response")) {
                sounds = i.value();
                if (sounds.canConvert(QVariant::Map)) {
                    QMap <QString, QVariant> soundsList = sounds.toMap();
                    if (soundsList.contains(QStringLiteral("numFound"))) emit searchInfo(i18np("Found %1 result", "Found %1 results", soundsList.value("numFound").toInt()));
                    QList <QVariant> resultsList;
                    if (soundsList.contains(QStringLiteral("docs"))) {
                        resultsList = soundsList.value(QStringLiteral("docs")).toList();
                    }
                    
                    for (int j = 0; j < resultsList.count(); ++j) {
                        if (resultsList.at(j).canConvert(QVariant::Map)) {
                            QMap <QString, QVariant> soundmap = resultsList.at(j).toMap();
                            if (soundmap.contains(QStringLiteral("title"))) {
                                QListWidgetItem *item = new   QListWidgetItem(soundmap.value(QStringLiteral("title")).toString(), m_listWidget);
                                item->setData(descriptionRole, soundmap.value(QStringLiteral("description")).toString());
                                item->setData(idRole, soundmap.value(QStringLiteral("identifier")).toString());
                                QString author = soundmap.value(QStringLiteral("creator")).toString();
                                item->setData(authorRole, author);
                                if (author.startsWith(QLatin1String("http"))) item->setData(authorUrl, author);
                                item->setData(infoUrl, "http://archive.org/details/" + soundmap.value(QStringLiteral("identifier")).toString());
                                item->setData(downloadRole, "http://archive.org/download/" + soundmap.value(QStringLiteral("identifier")).toString());
                                item->setData(licenseRole, soundmap.value(QStringLiteral("licenseurl")).toString());                        
                            }
                        }
                    }
                }
            }
            ++i;
        }
    }
    m_listWidget->blockSignals(false);
    m_listWidget->setCurrentRow(0);
    emit searchDone();
}
Пример #11
0
void HTTPTracker::onAnnounceResult(KIO::Job* j)
{
    if (j->error())
    {
        KIO::StoredTransferJob* st = (KIO::StoredTransferJob*)j;
        KURL u = st->url();
        active_job = 0;

        Out(SYS_TRK|LOG_IMPORTANT) << "Error : " << st->errorString() << endl;
        if (u.queryItem("event") != "stopped")
        {
            failures++;
            requestFailed(j->errorString());
        }
        else
        {
            stopDone();
        }
    }
    else
    {
        KIO::StoredTransferJob* st = (KIO::StoredTransferJob*)j;
        KURL u = st->url();
        active_job = 0;

        if (u.queryItem("event") != "stopped")
        {
            try
            {
                if (updateData(st->data()))
                {
                    failures = 0;
                    peersReady(this);
                    requestOK();
                    if (u.queryItem("event") == "started")
                        started = true;
                }
            }
            catch (bt::Error & err)
            {
                failures++;
                requestFailed(i18n("Invalid response from tracker"));
            }
            event = QString::null;
        }
        else
        {
            failures = 0;
            stopDone();
        }
    }
    doAnnounceQueue();
}
Пример #12
0
void HTTPTracker::onScrapeResult(KIO::Job* j)
{
    if (j->error())
    {
        Out(SYS_TRK|LOG_IMPORTANT) << "Scrape failed : " << j->errorString() << endl;
        return;
    }

    KIO::StoredTransferJob* st = (KIO::StoredTransferJob*)j;
    BDecoder dec(st->data(),false,0);
    BNode* n = 0;

    try
    {
        n = dec.decode();
    }
    catch (bt::Error & err)
    {
        Out(SYS_TRK|LOG_IMPORTANT) << "Invalid scrape data " << err.toString() << endl;
        return;
    }

    if (n && n->getType() == BNode::DICT)
    {
        BDictNode* d = (BDictNode*)n;
        d = d->getDict("files");
        if (d)
        {
            d = d->getDict(tor->getInfoHash().toByteArray());
            if (d)
            {
                BValueNode* vn = d->getValue("complete");
                if (vn && vn->data().getType() == Value::INT)
                {
                    seeders = vn->data().toInt();
                }


                vn = d->getValue("incomplete");
                if (vn && vn->data().getType() == Value::INT)
                {
                    leechers = vn->data().toInt();
                }

                Out(SYS_TRK|LOG_DEBUG) << "Scrape : leechers = " << leechers
                                       << ", seeders = " << seeders << endl;
            }
        }
    }

    delete n;
}
Пример #13
0
void MediaManager::slotImageFetched( KJob * job )
{
    KIO::StoredTransferJob *baseJob = qobject_cast<KIO::StoredTransferJob *>( job );
    QString remote = d->queue.value(job);
    d->queue.remove( job );
    if ( job->error() ) {
        kDebug() << "Job error: " << job->error() << "\t" << job->errorString();
        QString errMsg = i18n( "Cannot download image from %1.",
                               job->errorString() );
        emit fetchError( remote, errMsg );
    } else {
        QPixmap p;
        if( !baseJob->data().startsWith(QByteArray("<?xml version=\"")) &&
            p.loadFromData( baseJob->data() ) ) {
            d->cache.insert( remote, p );
            emit imageFetched( remote, p );
        } else {
            kDebug()<<"Parse Error: \nBase Url:"<<baseJob->url()<<"\ndata:"<<baseJob->data();
            emit fetchError( remote, i18n( "The download failed. The returned file is corrupted." ) );
        }
    }
}
void LoadWaiter::setImageData(KJob *job)
{
    if (m_vectorShape) {
        KIO::StoredTransferJob *transferJob = qobject_cast<KIO::StoredTransferJob*>(job);
        Q_ASSERT(transferJob);

        const QByteArray contents = transferJob->data();
        const VectorShape::VectorType vectorType = VectorShape::vectorType(contents);

        m_vectorShape->setCompressedContents(qCompress(contents), vectorType);
    }

    deleteLater();
}
Пример #15
0
void KexiUserFeedbackAgent::sendDataFinished(KFakeJob* job)
{
    if (job->error()) {
        //! @todo error...
        return;
    }
    KIO::StoredTransferJob* sendJob = qobject_cast<KIO::StoredTransferJob*>(job);
    QByteArray result = sendJob->data();
    result.chop(1); // remove \n
    kDebug() << result;
    if (result == "ok") {
        d->sentDataInThisSession = d->areas;
    }
}
Пример #16
0
void ArchiveOrg::slotParseThumbs(KJob* job)
{
    KIO::StoredTransferJob* storedQueryJob = static_cast<KIO::StoredTransferJob*>( job );
    QDomDocument doc;
    doc.setContent(QString::fromUtf8(storedQueryJob->data()));
    QDomNodeList links = doc.elementsByTagName(QStringLiteral("a"));
    if (links.isEmpty()) return;
    for (int i = 0; i < links.count(); ++i) {
        QString href = links.at(i).toElement().attribute(QStringLiteral("href"));
        if (!href.contains('/') && i >= links.count() / 2) {
            QString thumbUrl = m_thumbsPath + href;
            if (m_metaInfo.value(QStringLiteral("id")) == job->property("id").toString())
                emit gotThumb(thumbUrl);
            break;
        }
    }
}
Пример #17
0
    void Core::downloadFinishedSilently(KJob* job)
    {
        KIO::StoredTransferJob* j = (KIO::StoredTransferJob*)job;
        int err = j->error();
        if (err == KIO::ERR_USER_CANCELED)
        {
            // do nothing
        }
        else if (err)
        {
            canNotLoadSilently(j->errorString());
        }
        else
        {
            QString dir;
            if (custom_save_locations.contains(j))
            {
                // we have a custom save location so save to that
                dir = custom_save_locations[j].toLocalFile();
                custom_save_locations.remove(j);
            }
            else if (!Settings::useSaveDir())
            {
                // incase save dir is not set, use home director
                Out(SYS_GEN | LOG_NOTICE) << "Cannot load " << j->url() << " silently, default save location not set !" << endl;
                Out(SYS_GEN | LOG_NOTICE) << "Using home directory instead !" << endl;
                dir = QDir::homePath();
            }
            else
            {
                dir = Settings::saveDir().toLocalFile();
            }

            QString group;
            QMap<KUrl, QString>::iterator i = add_to_groups.find(j->url());
            if (i != add_to_groups.end())
            {
                group = i.value();
                add_to_groups.erase(i);
            }


            if (dir != QString::null)
                loadFromData(j->data(), dir, group, true, j->url());
        }
    }
Пример #18
0
bool Editor::openFile(const QUrl &_url)
{
	QUrl url = _url;
	if (maybeSave()) {
		if (url.isEmpty()) {
            url = QFileDialog::getOpenFileUrl(this, 
                                              i18n("Open"), 
                                              QUrl(), 
                                              QString("%1 (*.turtle);;%2 (*)").arg(i18n("Turtle code files")).arg(i18n("All files"))
                    );
		}
		if (!url.isEmpty()) {
			KIO::StoredTransferJob *job = KIO::storedGet(url);
			if (job->exec()) {
				QByteArray data = job->data();
				QBuffer buffer(&data);
				if (!buffer.open(QIODevice::ReadOnly | QIODevice::Text)) {
					return false; // can't happen
				}
				QTextStream in(&buffer);
				// check for our magic identifier
				QString s;
				s = in.readLine();
				if (s != KTURTLE_MAGIC_1_0) {
					KMessageBox::error(this, i18n("The file you try to open is not a valid KTurtle script, or is incompatible with this version of KTurtle.\nCannot open %1", url.toDisplayString(QUrl::PreferLocalFile)));
					return false;
				}
				QString localizedScript = Translator::instance()->localizeScript(in.readAll());
				setContent(localizedScript);
				setCurrentUrl(url);
				editor->document()->setModified(false);
				emit fileOpened(url);
				return true;
			} else {
				KMessageBox::error(this, job->errorString());
				return false;
			}
		}
	}
//	statusbar "Nothing opened"
	return false;
}
Пример #19
0
        void UPnPRouter::downloadFinished(KJob* j)
        {
            if (j->error())
            {
                error = i18n("Failed to download %1: %2",location.url(),j->errorString());
                qDebug() << error << endl;
                return;
            }

            KIO::StoredTransferJob* st = (KIO::StoredTransferJob*)j;
            // load in the file (target is always local)
            UPnPDescriptionParser desc_parse;
            bool ret = desc_parse.parse(st->data(),this);
            if (!ret)
            {
                error = i18n("Error parsing router description.");
            }

            emit xmlFileDownloaded(this,ret);
        }
Пример #20
0
void Bit_ly_Config::slotValidate()
{
    ui.validate_button->setEnabled(false);
    ui.validate_button->setText(i18n("Checking..."));
    QString login = QLatin1String("choqok");
    QString apiKey = QLatin1String("R_bdd1ae8b6191dd36e13fc77ca1d4f27f");
    QUrl reqUrl(QLatin1String("http://api.bit.ly/v3/validate"));
    QUrlQuery reqQuery;

    reqQuery.addQueryItem(QLatin1String("x_login"), ui.kcfg_login->text());
    reqQuery.addQueryItem(QLatin1String("x_apiKey"), ui.kcfg_api_key->text());

    if (Bit_ly_Settings::domain() == QLatin1String("j.mp")) {   //bit.ly is default domain
        reqQuery.addQueryItem(QLatin1String("domain"), QLatin1String("j.mp"));
    }

    reqQuery.addQueryItem(QLatin1String("login"), QLatin1String(login.toUtf8()));
    reqQuery.addQueryItem(QLatin1String("apiKey"), QLatin1String(apiKey.toUtf8()));
    reqQuery.addQueryItem(QLatin1String("format"), QLatin1String("txt"));
    reqUrl.setQuery(reqQuery);

    KIO::StoredTransferJob *job = KIO::storedGet(reqUrl, KIO::Reload, KIO::HideProgressInfo);
    job->exec();

    if (!job->error()) {
        QString output(QLatin1String(job->data()));
        if (output.startsWith(QLatin1Char('0')))
            KMessageBox::error(this, i18nc("The your_api_key part of the URL is a fixed part of the URL "
                                           "and should probably not be changed in localization.",
                                           "Provided data is invalid. Try another login or API key.\n"
                                           "You can find it on http://bit.ly/a/your_api_key"));
        if (output.startsWith(QLatin1Char('1'))) {
            KMessageBox::information(this, i18n("You entered valid information."));
        }
    } else {
        Choqok::NotifyManager::error(job->errorString(), i18n("bit.ly Config Error"));
    }

    ui.validate_button->setEnabled(true);
    ui.validate_button->setText(i18n("Validate"));
}
Пример #21
0
    void UPnPRouter::downloadFinished(KJob* j)
    {
        if(j->error())
        {
            d->error = i18n("Failed to download %1: %2", d->location.toDisplayString(), j->errorString());
            Out(SYS_PNP | LOG_IMPORTANT) << d->error << endl;
            return;
        }

        KIO::StoredTransferJob* st = (KIO::StoredTransferJob*)j;
        // load in the file (target is always local)
        UPnPDescriptionParser desc_parse;
        bool ret = desc_parse.parse(st->data(), this);
        if(!ret)
        {
            d->error = i18n("Error parsing router description.");
        }

        xmlFileDownloaded(this, ret);
        d->getExternalIP();
    }
Пример #22
0
void KexiUserFeedbackAgent::sendRedirectQuestionFinished(KFakeJob* job)
{
    if (job->error()) {
        //! @todo error...
        kDebug() << "Error, no URL Redirect";
    }
    else {
        KIO::StoredTransferJob* sendJob = qobject_cast<KIO::StoredTransferJob*>(job);
        QByteArray result = sendJob->data();
        result.chop(1); // remove \n
        kDebug() << result;
        if (result.isEmpty()) {
            kDebug() << "No URL Redirect";
        }
        else {
            d->url = QString::fromUtf8(result);
            kDebug() << "URL Redirect to" << d->url;
        }
    }
    d->redirectChecked = true;
    emit redirectLoaded();
    sendData();
}
Пример #23
0
void TwitterSearch::searchResultsReturned(KJob *job)
{
    qCDebug(CHOQOK);
    if (!job) {
        qCDebug(CHOQOK) << "job is a null pointer";
        Q_EMIT error(i18n("Unable to fetch search results."));
        return;
    }

    const SearchInfo info = mSearchJobs.take(job);
    QList<Choqok::Post *> postsList;
    if (job->error()) {
        qCCritical(CHOQOK) << "Error:" << job->errorString();
        Q_EMIT error(i18n("Unable to fetch search results: %1", job->errorString()));
    } else {
        KIO::StoredTransferJob *jj = qobject_cast<KIO::StoredTransferJob *>(job);
        const QJsonDocument json = QJsonDocument::fromJson(jj->data());

        if (!json.isNull()) {
            if (info.option == TwitterSearch::FromUser) {
                for (const QVariant elem: json.toVariant().toList()) {
                    postsList.prepend(readStatusesFromJsonMap(elem.toMap()));
                }
            } else {
                const QVariantMap map = json.toVariant().toMap();

                if (map.contains(QLatin1String("statuses"))) {
                    for (const QVariant elem: map[QLatin1String("statuses")].toList()) {
                        postsList.prepend(readStatusesFromJsonMap(elem.toMap()));
                    }
                }
            }
        }
    }

    Q_EMIT searchResultsReceived(info, postsList);
}
Пример #24
0
void ThumbnailPicker::slotJobResult( KJob *job ) {
    KIO::StoredTransferJob *stjob = (KIO::StoredTransferJob*)job;

    //Update Progressbar
    if ( ! ui->SearchProgress->isHidden() ) {
        ui->SearchProgress->setValue(ui->SearchProgress->value()+1);
        if ( ui->SearchProgress->value() == ui->SearchProgress->maximum() ) {
            ui->SearchProgress->hide();
            ui->SearchLabel->setText( i18n( "Search results:" ) );
        }
    }

    //If there was a problem, just return silently without adding image to list.
    if ( job->error() ) {
        qDebug() << " error=" << job->error();
        job->kill();
        return;
    }

    QPixmap *pm = new QPixmap();
    pm->loadFromData( stjob->data() );

    uint w = pm->width();
    uint h = pm->height();
    uint pad = 0; /*FIXME LATER 4* QDialogBase::marginHint() + 2*ui->SearchLabel->height() + QDialogBase::actionButton( QDialogBase::Ok )->height() + 25;*/
    uint hDesk = QApplication::desktop()->availableGeometry().height() - pad;

    if ( h > hDesk )
        *pm = pm->scaled( w*hDesk/h, hDesk, Qt::IgnoreAspectRatio, Qt::SmoothTransformation );

    PixList.append( pm );

    //Add 50x50 image and URL to listbox
    //ui->ImageList->insertItem( shrinkImage( PixList.last(), 50 ),
    //		cjob->srcURLs().first().prettyUrl() );
    ui->ImageList->addItem( new QListWidgetItem ( QIcon(shrinkImage( PixList.last(), 50 )), stjob->url().url()));
}
Пример #25
0
void TwitterMicroBlog::createPostWithAttachment(Choqok::Account *theAccount, Choqok::Post *post,
        const QString &mediumToAttach)
{
    if (mediumToAttach.isEmpty()) {
        TwitterApiMicroBlog::createPost(theAccount, post);
    } else {
        const QUrl picUrl = QUrl::fromUserInput(mediumToAttach);
        KIO::StoredTransferJob *picJob = KIO::storedGet(picUrl, KIO::Reload, KIO::HideProgressInfo);
        picJob->exec();
        if (picJob->error()) {
            qCCritical(CHOQOK) << "Job error:" << picJob->errorString();
            KMessageBox::detailedError(Choqok::UI::Global::mainWindow(),
                                       i18n("Uploading medium failed: cannot read the medium file."),
                                       picJob->errorString());
            return;
        }
        const QByteArray picData = picJob->data();
        if (picData.count() == 0) {
            qCCritical(CHOQOK) << "Cannot read the media file, please check if it exists.";
            KMessageBox::error(Choqok::UI::Global::mainWindow(),
                               i18n("Uploading medium failed: cannot read the medium file."));
            return;
        }

        TwitterAccount *account = qobject_cast<TwitterAccount *>(theAccount);
        QUrl url = account->uploadUrl();
        url.setPath(url.path() + QStringLiteral("/statuses/update_with_media.%1").arg(format));
        const QMimeDatabase db;
        QByteArray fileContentType = db.mimeTypeForUrl(picUrl).name().toUtf8();

        QMap<QString, QByteArray> formdata;
        formdata[QLatin1String("status")] = post->content.toUtf8();
        if (!post->replyToPostId.isEmpty()) {
            formdata[QLatin1String("in_reply_to_status_id")] = post->replyToPostId.toLatin1();
        }
        formdata[QLatin1String("source")] = QCoreApplication::applicationName().toLatin1();

        QMap<QString, QByteArray> mediafile;
        mediafile[QLatin1String("name")] = "media[]";
        mediafile[QLatin1String("filename")] = picUrl.fileName().toUtf8();
        mediafile[QLatin1String("mediumType")] = fileContentType;
        mediafile[QLatin1String("medium")] = picData;
        QList< QMap<QString, QByteArray> > listMediafiles;
        listMediafiles.append(mediafile);

        QByteArray data = Choqok::MediaManager::createMultipartFormData(formdata, listMediafiles);

        KIO::StoredTransferJob *job = KIO::storedHttpPost(data, url, KIO::HideProgressInfo) ;
        if (!job) {
            qCCritical(CHOQOK) << "Cannot create a http POST request!";
            return;
        }
        job->addMetaData(QStringLiteral("content-type"),
                         QStringLiteral("Content-Type: multipart/form-data; boundary=AaB03x"));
        job->addMetaData(QStringLiteral("customHTTPHeader"),
                         QStringLiteral("Authorization: ") +
                         QLatin1String(authorizationHeader(account, url, QOAuth::POST)));
        mCreatePostMap[ job ] = post;
        mJobsAccount[job] = theAccount;
        connect(job, SIGNAL(result(KJob*)),
                SLOT(slotCreatePost(KJob*)));
        job->start();
    }
}
Пример #26
0
void KPrPicturesImport::pictureImported(KJob *job)
{
    KoShape *shape = m_factory->createDefaultShape();
    if (shape) {
        KIO::StoredTransferJob *transferJob = qobject_cast<KIO::StoredTransferJob*>(job);
        Q_ASSERT(transferJob);
        KoImageData *imageData = m_doc->resourceManager()->imageCollection()->createImageData(transferJob->data());
        if (imageData->isValid()) {
            shape->setUserData(imageData);

            // make sure the picture fits on the page
            QSizeF imageSize = imageData->imageSize();
            QSizeF pageSize = m_masterPage->size();
            qreal zoom = 1;
            if (imageSize.width() > pageSize.width() || imageSize.height() > pageSize.height()) {
                zoom = pageSize.width() / imageSize.width();
                zoom = qMin(zoom, pageSize.height() / imageSize.height());
            }
            imageSize *= zoom;
            shape->setSize(imageSize);

            // center the picture on the page
            QPointF pos( pageSize.width() / 2- imageSize.width() / 2, pageSize.height() / 2 - imageSize.height() / 2 );
            shape->setPosition(pos);

            KoPAPageBase *page = m_doc->newPage(m_masterPage);
            KoShapeLayer *layer = dynamic_cast<KoShapeLayer *>(page->shapes().first());
            if (layer) {
                layer->addShape(shape);
                new KoPAPageInsertCommand(m_doc, page, m_currentPage, m_cmd);
                m_currentPage = page;
            }
            else {
                delete page;
                delete shape;
            }
        }
        else {
            kWarning(33001) << "imageData not valid";
            delete shape;
        }
    }
    else {
        kWarning(33001) << "shape not created";
    }
    import();
}
Пример #27
0
void TwitterApiWhoisWidget::userInfoReceived(KJob* job)
{
    kDebug();
    if(job->error()){
        kError()<<"Job Error: "<<job->errorString();
        if( Choqok::UI::Global::mainWindow()->statusBar() )
            Choqok::UI::Global::mainWindow()->statusBar()->showMessage(job->errorString());
        slotCancel();
        return;
    }
    KIO::StoredTransferJob *stj = qobject_cast<KIO::StoredTransferJob *>(job);
//     kDebug()<<stj->data();
    QJson::Parser parser;
    bool ok;
    QVariantMap map = parser.parse(stj->data(), &ok).toMap();

    Choqok::Post post;
    if ( !ok ){
        kDebug()<<"JSON parsing failed! Data is:\n\t"<<stj->data();
        d->errorMessage = i18n("Cannot load user information.");
        updateHtml();
        showForm();
        return;
    }

    QString timeStr;
    d->errorMessage = map["error"].toString();
    if( d->errorMessage.isEmpty() ) { //No Error
        post.author.realName = map["name"].toString();
        post.author.userName = map["screen_name"].toString();
        post.author.location = map["location"].toString();
        post.author.description = map["description"].toString();
        post.author.profileImageUrl = map["profile_image_url"].toString();
        post.author.homePageUrl = map["url"].toString();
        d->timeZone = map["time_zone"].toString();
        d->followersCount = map["followers_count"].toString();
        d->friendsCount = map["friends_count"].toString();
        d->statusesCount = map["statuses_count"].toString();
        QVariantMap var = map["status"].toMap();
        post.content = var["text"].toString();
        post.creationDateTime = d->mBlog->dateFromString(var["created_at"].toString());
        post.isFavorited = var["favorited"].toBool();
        post.postId = var["id"].toString();
        post.replyToPostId = var["in_reply_to_status_id"].toString();
        post.replyToUserId = var["in_reply_to_user_id"].toString();
        post.replyToUserName = var["in_reply_to_screen_name"].toString();
        post.source = var["source"].toString();
        d->currentPost = post;
    }

    updateHtml();
    showForm();

    QPixmap *userAvatar = Choqok::MediaManager::self()->fetchImage( post.author.profileImageUrl,
                                                                    Choqok::MediaManager::Async );

    if(userAvatar) {
        d->wid->document()->addResource( QTextDocument::ImageResource, QUrl("img://profileImage"),
                                         *(userAvatar) );
    } else {
        connect( Choqok::MediaManager::self(), SIGNAL( imageFetched(QString,QPixmap)),
                this, SLOT(avatarFetched(QString, QPixmap) ) );
        connect( Choqok::MediaManager::self(), SIGNAL(fetchError(QString,QString)),
                this, SLOT(avatarFetchError(QString,QString)) );
    }
}