Example #1
0
void LoginManager::onUploadReply(QNetworkReply* reply, int code, const QJsonObject& obj)
      {
      qDebug() << "onUploadReply" << code << reply->errorString();
      if (code == HTTP_OK) {
            if (obj.value("permalink") != QJsonValue::Undefined) {
                  emit uploadSuccess(obj.value("permalink").toString(), obj.value("id").toString(), obj.value("vid").toString());
                  }
            else {
                  emit uploadError(tr("An error occurred during the file transfer. Please try again"));
                  }
            }
      else
            emit uploadError(tr("Cannot upload: %1").arg(getErrorString(reply, obj)));
      }
Example #2
0
void TabWidget::startUpload() {
    QString uri;
    m_ui->label_progress->setText(tr("Uploading..."));

    QNetworkRequest request;
    if (script_value.property("premium").toBoolean() == true)
        uri = QString("/premium/files");
    else
        uri = QString("/files");

    request.setUrl(QUrl(QString("http://") + script_value.property("upload_host").toString() + uri));
    request.setRawHeader("Host", script_value.property("upload_host").toString().toUtf8());
    request.setRawHeader("Accept-Language","en");
    request.setRawHeader("User-Agent", USER_AGENT);
    request.setRawHeader("Cookie", session.toUtf8());
    request.setRawHeader("Content-type", QString("multipart/form-data; boundary=" + Payload::boundary).toUtf8());
    if (settings.value("api_key_enabled").toBool() && settings.value("api_key").toString().size() > 10)
        request.setRawHeader("X-API-Key", settings.value("api_key").toString().toUtf8());

    request.setAttribute(QNetworkRequest::DoNotBufferUploadDataAttribute, true);
    payload = new Payload(upload_file, script_value);

    start_date = last_date = QDateTime::currentDateTime();
    reply = network_manager.post(request, payload);
    connect(reply, SIGNAL(finished()), this, SLOT(uploadRequestFinished()));
    connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(uploadError(QNetworkReply::NetworkError)));
    connect(reply, SIGNAL(uploadProgress(qint64, qint64) ), this, SLOT(updateDataSendProgress(qint64,qint64)));

    //_cprintf("uploading...\n");
}
Example #3
0
void Uploader::uploadFile(const QString & fileName)
{
    if (fileName.isEmpty())
        return;

    // Pack the file into a base-64 encoded byte array
    QFile file(fileName);

    if (!file.open(QIODevice::ReadOnly)) {
        emit uploadError(tr("Unable to open image file for reading"));
        return;
    }

    QByteArray fileData = file.readAll().toBase64();
    file.close();

    // Create the request body
    QByteArray requestBody;

    requestBody.append(QString("key=").toUtf8());
    requestBody.append(QUrl::toPercentEncoding(m_apiKey));
    requestBody.append(QString("&image=").toUtf8());
    requestBody.append(QUrl::toPercentEncoding(fileData));

    // Start network access
    QNetworkReply * reply = m_manager->post(
                                QNetworkRequest(QUrl("http://api.imgur.com/2/upload.xml")),
                                requestBody);

    connect(reply, SIGNAL(uploadProgress(qint64, qint64)),
            this, SIGNAL(uploadProgress(qint64, qint64)));

}
/**
* @brief slot handling time out
*/
void ImageShackUploader::handleTimeOut()
{
    if(uploadAborted==false)
    {
        emit uploadError(ImageShackError::TimeoutError);
        this->abortUploads();
    }
}
Example #5
0
// Upload a file to a connected account
int ShareOnline::Imgur::upload(QString filename) {

    if(imgurClientID == "" || imgurClientSecret == "") {
        int ret = obtainClientIdSecret();
        if(ret != IMGUR_NOERROR) {
            emit abortAllRequests();
            emit uploadError(QNetworkReply::UnknownServerError);
            return ret;
        }
    }

    // Ensure an access token is set
    if(access_token == "") {
        if(debug)
            LOG << CURDATE << "ERROR! Unable to upload image, no access_token set... Did you connect to an account?" << NL;
        return IMGUR_ACCESS_TOKEN_ERROR;
    }

    // Ensure that filename is not empty and that the file exists
    if(filename.trimmed() == "" || !QFileInfo(filename).exists()) {
        if(debug)
            LOG << CURDATE << QString("ERROR! Filename '%1' for uploading to imgur.com is invalid").arg(filename).toStdString() << NL;
        return IMGUR_FILENAME_ERROR;
    }

    // Initiate file and open for reading
    QFile file(filename);
    if(!file.open(QIODevice::ReadOnly)) {
        if(debug)
            LOG << CURDATE << QString("ERROR! Can't open file '%1' for reading to upload to imgur.com").arg(filename).toStdString() << NL;
        return IMGUR_FILE_OPEN_ERROR;
    }

    // Read binary data of file to bytearray
    QByteArray byteArray = file.readAll();
    file.close();

    // Setup network request, use XML format
    QNetworkRequest req(QUrl("https://api.imgur.com/3/image.xml"));
    // the following is not necessary (it's the default), but avoids an error message on standard output
    req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    // Set access_token to prove authorisation to connect to account
    req.setRawHeader("Authorization", QByteArray("Bearer ") + access_token.toLatin1());

    // Send upload request and connect to feedback signals
    QNetworkReply *reply = networkManager->post(req, byteArray);
    connect(reply, &QNetworkReply::finished, this, &ShareOnline::Imgur::uploadFinished);
    connect(reply, &QNetworkReply::uploadProgress, this, &ShareOnline::Imgur::uploadProgress);
    // The following has to use the old syntax, as there is also a accessor member (not a signal) to access the error with the same name
    connect(reply, static_cast<void (QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error), this, &Imgur::uploadError);
    connect(this, &ShareOnline::Imgur::abortAllRequests, reply, &QNetworkReply::abort);

    // Phew, no error occured!
    return IMGUR_NOERROR;

}
void LoginManager::onUploadRequestReady(QByteArray ba)
      {
      disconnect(_oauthManager, SIGNAL(requestReady(QByteArray)),
            this, SLOT(onUploadRequestReady(QByteArray)));
      //qDebug() << "onUploadRequestReady" << ba;
      if (_oauthManager->lastError() == KQOAuthManager::NoError) {
            QJsonDocument jsonResponse = QJsonDocument::fromJson(ba);
            QJsonObject score = jsonResponse.object();
            if (score.value("permalink") != QJsonValue::Undefined) {
                  emit uploadSuccess(score.value("permalink").toString());
                  }
            else {
                  emit uploadError(tr("An error occurred during the file transfer. Please try again"));
                  }
            }
      else {
            emit uploadError(tr("Cannot upload: %1").arg(_oauthManager->lastError()));
            }
      }
Example #7
0
/**
*	Constructor
*
*	@param QWidget parent	The parent Widget
**/
Window::Window()
{
	this->secondUpload = false;
    //QList<ImageShackObject *>  listeImages ;
	QNetworkProxy * proxy = new QNetworkProxy(QNetworkProxy::HttpProxy,QString("proxy.rennes.enst-bretagne.fr"),3128);

    ImageShackObject * pc = new ImageShackObject("/Users/supm4n/Documents/Projects/ImageShackUploader/Argentina.gif","mc,notmac,pub",true);
    ImageShackObject * biere   = new ImageShackObject("/Users/supm4n/Documents/Projects/ImageShackUploader/Australia.gif","biere,pub",true);
    ImageShackObject * plus  = new ImageShackObject("/Users/supm4n/Documents/Projects/ImageShackUploader/Austria.gif","plus,priv",false);
    //ImageShackObject * cpu      = new ImageShackObject("/Users/supm4n/Documents/Projects/ImageShackUploader/","cpu,priv",false);

    listeImages << pc;
    listeImages << biere;
    listeImages << plus;
    //listeImages2 << biere;
    //listeImages2 << plus;
    //listeImages2 << cpu;
    //listeImages << fire;
    //listeImages << a;

    //ImageShackObject * basket = new ImageShackObject("/home/christ/Images/Basket/basket.jpg","basket,fire,pub",true);
    //ImageShackObject * dunk   = new ImageShackObject("/home/christ/Images/Basket/test.jpg","dunk,nba,priv",false);

	//basket->setResizeOption("200x200");
	//dunk->setResizeOption("50x300");

    //listeImages << dunk;
   // listeImages << basket;

    uploader = new ImageShackUploader(QString("EFI0O4JZd1897eb3d86758fa0ee582a34385405e"));
    //uploader->setProxy(proxy);

	//uploader->checkUserPassword(QString("kwentakill"),QString("rousseau"));

   //uploader->anonymousUploadImages(listeImage);
	qDebug() << "Window.cpp : Nombre de fichiers =" << listeImages.size();
    //uploader->uploadImages(listeImages,"kwentakill","rousseau");

	//QTimer::singleShot(500, this, SLOT(oneUploadDone()));

    //uploader->anonymousUploadImage(fichier,"basket");
	//uploader->setRemoveInformationBar(false);	
    //uploader->userUploadImage(fichier,"kwentakill","rousseau","dunk");
    //uploader->userUploadImage(fichier,"kwentakill","rousea","dunk","150x150");

    uploader->checkUserPassword("*****@*****.**","rousseau");
    connect(uploader,SIGNAL(authentificationResponse(bool)),this,SLOT(manageResponse(bool)));
	connect(uploader,SIGNAL(uploadDone(ImageShackResponse *)),this,SLOT(oneUploadDone(ImageShackResponse *)));
    connect(uploader,SIGNAL(endOfUploads()),this,SLOT(manageEndUpload()));
	connect(uploader,SIGNAL(uploadError(ImageShackError::UploadError)),this,SLOT(handleErrors(ImageShackError::UploadError)));
	connect(uploader,SIGNAL(uploadProgress(ImageShackObject *,qint64,qint64)),this,SLOT(handleProgressions(ImageShackObject *,qint64,qint64)));


}
Example #8
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    connect(&screenshot, SIGNAL(newImageCaptured(QPixmapSharedPtr)), this, SLOT(screenshotCaptured(QPixmapSharedPtr)));
    connect(&areaCapture, SIGNAL(newImageCaptured(QPixmapSharedPtr)), this, SLOT(screenshotCaptured(QPixmapSharedPtr)));
    connect(&imgurUploader, SIGNAL(error(QString)), this, SLOT(uploadError(QString)));
    connect(&imgurUploader, SIGNAL(imageUploaded(QUrl)), this, SLOT(fileUploaded(QUrl)));
    connect(ui->buttonScreenshot, SIGNAL(clicked()), this, SLOT(captureScreen()));
    connect(ui->buttonCaptureArea, SIGNAL(clicked()), this, SLOT(captureArea()));
    connect(&tray, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(show()));
    tray.show();
}
Example #9
0
	void DriveManager::handleUploadError (QNetworkReply::NetworkError error)
	{
		QNetworkReply *reply = qobject_cast<QNetworkReply*> (sender ());
		if (!reply)
			return;

		reply->deleteLater ();

		emit uploadError ("Error", Reply2FilePath_.take (reply));
		if (error == QNetworkReply::ProtocolUnknownError)
		{
			//TODO resume upload
		}
	}
/**
*	Manage replies after the image is uploaded
*
*	@access private
*/
void ImageShackUploader::imageUploaded()
{
    QHash<QString, QString> usableResponse;
    ImageShackError::UploadError error;

    if(uploadsProcessing)
    {
        usableResponse = ImageShackResponse::makeResponseUsable(this->networkReply);

        //qDebug() << usableResponse;

        if(usableResponse.contains(QString("error")))
        {
            //qDebug() << "* Error in response";
            //this->uploadsProcessing	   = false;

            if(uploadAborted==false)
            {
                error = ImageShackError::getErrorCode(usableResponse);

                if(error != ImageShackError::NoError)
                {
                    emit uploadError(error);
                }
                this->abortUploads();
            }
        }
        else
        {
            //qDebug() << "* Image uploadé avec succès : \n " << usableResponse;


            if(uploadAborted==false)
            {
                emit uploadDone(new ImageShackResponse(this->fileBeingUploaded,usableResponse));
                this->nbFilesUploaded ++;
            }

            //qDebug() << "* Nombre de fichiers restant " << filesToUpload.size();

            if(nbFilesUploaded == nbFilesToUploads && uploadAborted == false)
            {
                this->uploadsProcessing	   = false;
                timeoutTimer->stop();
                emit endOfUploads();
            }
        }
    }
}
/**
*	Manage upload errors
*
*	@access private
*/
void ImageShackUploader::manageUploadError(QNetworkReply::NetworkError errorCode)
{
    //qDebug() << "Error : " << errorCode;
    ImageShackError::UploadError error;

    if(uploadAborted==false)
    {
        error = ImageShackError::getErrorCode(errorCode);

        if(error != ImageShackError::NoError)
        {
            emit uploadError(error);
            this->abortUploads();
        }
    }
}
Example #12
0
int ShareOnline::Imgur::anonymousUpload(QString filename) {

    if(imgurClientID == "" || imgurClientSecret == "") {
        int ret = obtainClientIdSecret();
        if(ret != IMGUR_NOERROR) {
            emit uploadError(QNetworkReply::NetworkSessionFailedError);
            return ret;
        }
    }

    // Ensure that filename is not empty and that the file exists
    if(filename.trimmed() == "" || !QFileInfo(filename).exists()) {
        if(debug)
            LOG << CURDATE << QString("ERROR! Filename '%1' for uploading to imgur.com is invalid").arg(filename).toStdString() << NL;
        return IMGUR_FILENAME_ERROR;
    }

    // Initiate file and open for reading
    QFile file(filename);
    if(!file.open(QIODevice::ReadOnly)) {
        if(debug)
            LOG << CURDATE << QString("ERROR! Can't open file '%1' for reading to upload to imgur.com").arg(filename).toStdString() << NL;
        return IMGUR_FILE_OPEN_ERROR;
    }

    // Read binary data of file to bytearray
    QByteArray byteArray = file.readAll();

    // Setup network request (XML format)
    QNetworkRequest request(QUrl("https://api.imgur.com/3/image.xml"));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    request.setRawHeader("Authorization", QString("Client-ID " + imgurClientID).toLatin1());

    // Send upload request and connect to feedback signals
    QNetworkReply *reply = networkManager->post(request, byteArray);
    connect(reply, &QNetworkReply::finished, this, &ShareOnline::Imgur::uploadFinished);
    connect(reply, &QNetworkReply::uploadProgress, this, &ShareOnline::Imgur::uploadProgress);
    connect(reply, static_cast<void (QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error), this, &Imgur::uploadError);
    connect(this, &ShareOnline::Imgur::abortAllRequests, reply, &QNetworkReply::abort);

    // Phew, no error occured!
    return IMGUR_NOERROR;

}
Example #13
0
void TabWidget::prepareUpload() {
    if (UploadList::current_uploading != NULL)
        return;

    if (UploadList::new_current_uploading() == NULL)
        return;

    if (!QFile::exists(UploadList::current_uploading->at(0))) {
        UploadList::current_uploading->descr(tr("Error: file does not exist"));
        UploadList::current_uploading->state(tr("error"));
        UploadList::current_uploading = NULL;
        return;
    }
    upload_file = new QFile(UploadList::current_uploading->path());
    if ( !upload_file->open(QIODevice::ReadOnly) ) {
        UploadList::current_uploading->descr(tr("Unable to open the file %1: %2.").arg(
                UploadList::current_uploading->path()).arg(upload_file->errorString()));
        UploadList::current_uploading->state(tr("error"));
        UploadList::current_uploading = NULL;
        return;
    }

    m_ui->progressBar->setValue(0);
    UploadList::current_uploading->state(tr("uploading"));
    UploadList::current_uploading->descr(tr("Uploading..."));

    QNetworkRequest request;
    request.setUrl(QUrl("http://rghost.net/multiple/upload_host"));
    request.setRawHeader("Host", "rghost.net");
    request.setRawHeader("Accept-Language","en");
    request.setRawHeader("User-Agent", USER_AGENT);
    if (settings.value("api_key_enabled").toBool() && settings.value("api_key").toString().size() > 10)
        request.setRawHeader("X-API-Key", settings.value("api_key").toString().toUtf8());

    reply = network_manager.get(request);
    connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(uploadError(QNetworkReply::NetworkError)));
    connect(reply, SIGNAL(finished()), this, SLOT(jsonRequestFinished()));

}
Example #14
0
File: utils.cpp Project: mkiol/Ubi
void Utils::uploadFinished()
{
    //qDebug() << "uploadFinished";
    isFinished = true;
    if (cur_reply->error() == QNetworkReply::NoError)
    {
        emit fileUploaded(cur_filename);
    }
    else if (cur_reply->error() == QNetworkReply::OperationCanceledError)
    {
        emit operationCanceled(cur_filename);
    }
    else
    {
        int httpStatus = cur_reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();

        //QString httpStatusMessage = cur_reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString();
        //QByteArray bytes = cur_reply->readAll();
        //qDebug() << "status: " << httpStatus << " " << httpStatusMessage;
        //qDebug() << "bytes: " << bytes;

        if(httpStatus==503)
        {
            emit fileUploaded(cur_filename);
        } else {
            //qDebug() << "upload error: " << httpStatus << " " << cur_reply->error() << " " << cur_reply->errorString();
            emit uploadError(cur_filename);
        }
    }

    cur_file->close();
    delete cur_file;
    cur_reply->close();
    cur_reply->deleteLater();

    start();
}
/**
*	Upload an image. This method is called by
*	userUploadImage and anonymousUploadImage
*	methods
*
*	@access public
*/
void ImageShackUploader::sendImage(ImageShackObject * imageToUpload ,
                                   QHash<QString, QString>   headers)
{
    QString   imagePath = imageToUpload->getObjectPath();
    QFile     image(imagePath);
    QFileInfo imageInfos(imagePath);

    QNetworkAccessManager * manager = new QNetworkAccessManager;
    QNetworkRequest         request(this->imageUploadUrl);

    QByteArray boundary   = "IMAGESHACKUPLOADER";
    QByteArray cr         = "\r\n";

    QByteArray data;

    if(!image.open(QIODevice::ReadOnly))
    {
        if(uploadAborted==false)
        {
            emit uploadError(ImageShackError::FailedOpeningTheFile);
            this->abortUploads();
        }

        return;
    }

    // build of the header
    data.append("--" + boundary + cr);
    data.append("Content-Disposition: form-data; ");
    data.append( "name=\"fileupload\"; filename=\"" + imageInfos.absoluteFilePath() + "\";" + cr);
    data.append("Content-Type: " + this->mimeType(imagePath) + cr + cr);

    // insertion of the image
    data.append(image.readAll() + cr);

    image.close();

    // build the footer
    QHashIterator<QString, QString> h(headers);
    while (h.hasNext())
    {
        h.next();

        data.append("--" + boundary + cr);
        data.append("Content-Disposition: form-data; ");
        data.append("name=\"" + h.key() + "\"" + cr + cr);
        data.append(h.value() + cr);
    }

    data.append("--" + boundary + "--" + cr);

    request.setHeader(QNetworkRequest::ContentTypeHeader, "multipart/form-data; boundary=" + boundary);
    request.setHeader(QNetworkRequest::ContentLengthHeader, QString::number(data.size()).toAscii());

    // manage proxy
    if(this->proxy != NULL)
        manager->setProxy(*this->proxy);

    this->fileBeingUploaded = imageToUpload;

    //this->uploadsProcessing	   = true;

    timeoutTimer->start(TIMEOUT);

    this->networkReply = manager->post(request, data);

    connect(this->networkReply, SIGNAL(finished())      ,
            this        , SLOT  (imageUploaded()));

    connect(this->networkReply, SIGNAL(error(QNetworkReply::NetworkError))       ,
            this        , SLOT  (manageUploadError(QNetworkReply::NetworkError)));

    connect(this->networkReply, SIGNAL(uploadProgress(qint64,qint64)),
            this	    , SLOT  (manageUploadProgress(qint64,qint64)));

    connect(manager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)),
            this   , SLOT  (manageAuthentificationRequired(QNetworkReply*,QAuthenticator*)));

    connect(manager, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)),
            this   , SLOT  (manageProxyAuthentificationRequired(QNetworkProxy,QAuthenticator*)));
}
Example #16
0
void Uploader::requestFinished(QNetworkReply * reply)
{
    // Did we have a network error?
    if (reply->error() != QNetworkReply::NoError) {
        emit uploadError(tr("Network error: %1").arg(reply->error()));

        reply->deleteLater();
        return;
    }

    // Parse the reply
    QHash<int, QString> linksMap;
    QDomDocument doc;
    QString error;

    if (!doc.setContent(reply->readAll(), false, &error)) {
        emit uploadError(tr("Parse error: %1").arg(error));

        reply->deleteLater();
        return;
    }

    // See if we have an upload reply, or an error
    QDomElement rootElem = doc.documentElement();
    error = "";

    if (rootElem.tagName() == "upload") {
        // Skip all elements until we reach the <links> tag
        QDomNode n = rootElem.firstChild();

        while (!n.isNull()) {
            if (n.isElement() && n.toElement().tagName() == "links") {
                QDomNode innerNode = n.firstChild();

                while (!innerNode.isNull()) {
                    if (innerNode.isElement()) {
                        QDomElement e = innerNode.toElement();

                        if (e.tagName() == "original") {
                            linksMap.insert(OriginalImage, e.text());
                        }
                        else if (e.tagName() == "small_square") {
                            linksMap.insert(SmallSquare, e.text());
                        }
                        else if (e.tagName() == "large_thumbnail") {
                            linksMap.insert(LargeThumbnail, e.text());
                        }
                        else if (e.tagName() == "imgur_page") {
                            linksMap.insert(ImgurPage, e.text());
                        }
                        else if (e.tagName() == "delete_page") {
                            linksMap.insert(DeletePage, e.text());
                        }
                    }
                    innerNode = innerNode.nextSibling();
                }
            }
            n = n.nextSibling();
        }
    }
    else if (rootElem.tagName() == "error") {
        // Skip all elements until we reach the <message> tag
        QDomNode n = rootElem.firstChild();

        while (!n.isNull()) {
            if (n.isElement() && n.toElement().tagName() == "message") {
                    error = n.toElement().text();
            }
            n = n.nextSibling();
        }
    }
    else {
        error = tr("Reccived unexpected reply from web service");
    }

    if (!error.isEmpty()) {
        emit uploadError(error);
    }
    else {
        emit uploadDone(linksMap);
    }
    reply->deleteLater();
}
void CReporterHttpClient::emitUploadError(const QString &file, const QString &errorString)
{
    emit uploadError(file, errorString);
}
void UploadWaitForm::SlotBoardError(const QString &error)
{
    uploadError(error, QPixmap("./resource/images/upload/error.png"));
}