Exemplo n.º 1
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();
}
Exemplo n.º 2
0
bool Editor::saveFile(const QUrl &targetUrl)
{
	QUrl url(targetUrl);
	bool result = false;
	if (url.isEmpty() && currentUrl().isEmpty()) {
		result = saveFileAs();
	} else {
		if (url.isEmpty()) url = currentUrl();
		QTemporaryFile tmp;  // only used for network export
		tmp.setAutoRemove(false);
		tmp.open();
		QString filename = url.isLocalFile() ? url.toLocalFile() : tmp.fileName();
	
		QSaveFile *savefile = new QSaveFile(filename);
		if (savefile->open(QIODevice::WriteOnly)) {
			QTextStream outputStream(savefile);
			// store commands in their generic @(...) notation format, to be translatable when reopened
			// this allows sharing of scripts written in different languages
			Tokenizer tokenizer;
			tokenizer.initialize(editor->document()->toPlainText());
			const QStringList localizedLooks(Translator::instance()->allLocalizedLooks());
			QString unstranslated;
			Token* t;
			bool pendingEOL = false;  // to avoid writing a final EOL token
			while ((t = tokenizer.getToken())->type() != Token::EndOfInput) {
				if (pendingEOL) {
					unstranslated.append('\n');
					pendingEOL = false;
				}
				if (localizedLooks.contains(t->look())) {
					QString defaultLook(Translator::instance()->defaultLook(t->look()));
					unstranslated.append(QString("@(%1)").arg(defaultLook));
				} else {
					if (t->type() == Token::EndOfLine) 
						pendingEOL = true;
					else
						unstranslated.append(t->look());
				}
			}
			outputStream << KTURTLE_MAGIC_1_0 << '\n';
			outputStream << unstranslated;
			outputStream.flush();
			savefile->commit();  // check for error here?
		}
		delete savefile;
        if (!url.isLocalFile())
           {
            KIO::StoredTransferJob *job = KIO::storedPut(savefile, url, -1, 0);
                 if(job->exec()){
                    setCurrentUrl(url);
                    editor->document()->setModified(false);
                    // MainWindow will add us to the recent file list
                    emit fileSaved(url);
                    result = true; // fix GUI for saveAs and saveExamples. TODO: check 5 lines above
                }
           }
    }
	return result;
}
Exemplo n.º 3
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;
}
Exemplo n.º 4
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"));
}
Exemplo n.º 5
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();
    }
}