コード例 #1
0
bool tiBackupService::install(const QString &path)
{
    qDebug() << "tiBackupService::install()";

    QFile *tiServicePath = new QFile(path);
    if(!tiServicePath->open(QIODevice::WriteOnly | QIODevice::Text))
        return false;
    QTextStream out(tiServicePath);

    QFile *tiServiceTemplate = new QFile(":/init/tibackup");
    if(!tiServiceTemplate->open(QIODevice::ReadOnly | QIODevice::Text))
    {
        tiServicePath->close();
        tiServicePath->deleteLater();
        return false;
    }
    QTextStream in(tiServiceTemplate);

    out << in.readAll();
    out.flush();

    tiServicePath->setPermissions(QFile::ReadOwner | QFile::ExeOwner | QFile::ReadGroup | QFile::ExeGroup | QFile::ReadOther);
    tiServicePath->close();
    tiServiceTemplate->close();

    tiServicePath->deleteLater();
    tiServiceTemplate->deleteLater();

    emit serviceInstalled();
    return true;
}
コード例 #2
0
ファイル: FacebookWidget.cpp プロジェクト: spthaolt/facebook
void FacebookWidget::saveApplicationState() {
    QDir configDir = QDir::home();
    if(!configDir.cd(".config/Socializer")) {
        qDebug()<<"Making path "<<QDir::cleanPath(".config/Socializer");
        configDir.mkpath(QDir::cleanPath(".config/Socializer"));
        configDir.cd(".config/Socializer");
    }

    QFile *configFile = new QFile(configDir.absoluteFilePath("WindowState"));
    configFile->open(QIODevice::WriteOnly);
    QDataStream configFileDataStream(configFile);
    configFileDataStream << saveGeometry();
    configFileDataStream << windowSizeIndex;
    configFile->close();
    configFile->deleteLater();

    if(themeRefreshTimer->isActive()) {
        QFile *themeFile = new QFile(configDir.absoluteFilePath("ThemeState"));
        themeFile->open(QIODevice::WriteOnly);
        QDataStream themeFileDataStream(themeFile);
        themeFileDataStream << themeParams;
        themeFile->close();
        themeFile->deleteLater();
    } else {
        configDir.remove("ThemeState");
    }
}
コード例 #3
0
ファイル: HttpClient.cpp プロジェクト: xtuer/Qt
void HttpClient::download(const QString &destinationPath,
                          std::function<void (const QString &)> successHandler,
                          std::function<void (const QString &)> errorHandler) {
    bool  debug = d->debug;
    QFile *file = new QFile(destinationPath);

    if (file->open(QIODevice::WriteOnly)) {
        download([=](const QByteArray &data) {
            file->write(data);
        }, [=](const QString &) {
            // 请求结束后释放文件对象
            file->flush();
            file->close();
            file->deleteLater();

            if (debug) {
                qDebug().noquote() << QString("下载完成,保存到: %1").arg(destinationPath);
            }

            if (nullptr != successHandler) {
                successHandler(QString("下载完成,保存到: %1").arg(destinationPath));
            }
        }, errorHandler);
    } else {
        // 打开文件出错
        if (debug) {
            qDebug().noquote() << QString("打开文件出错: %1").arg(destinationPath);
        }

        if (nullptr != errorHandler) {
            errorHandler(QString("打开文件出错: %1").arg(destinationPath));
        }
    }
}
コード例 #4
0
 void shutDown()
 {
     disconnect(http, SIGNAL(finished()), q, SLOT(httpReqFinished()));
     http->deleteLater();
     http = 0;
     destination->close();
     destination->deleteLater();
     destination = 0;
     q->resetCheckSumData();
 }
コード例 #5
0
 void shutDown()
 {
     disconnect(http, &QNetworkReply::finished, q, &HttpDownloader::httpReqFinished);
     http->deleteLater();
     http = 0;
     destination->close();
     destination->deleteLater();
     destination = 0;
     q->resetCheckSumData();
 }
コード例 #6
0
ファイル: imguruploader.cpp プロジェクト: Neyoui/Lightscreen
void ImgurUploader::upload(const QString &fileName)
{
    QFile *file = new QFile(fileName);

    if (!file->open(QIODevice::ReadOnly)) {
        emit error(ImageUploader::FileError, tr("Unable to read screenshot file"), fileName);
        file->deleteLater();
        return;
    }

    QNetworkRequest request(QUrl("https://api.imgur.com/3/image"));
    request.setRawHeader("Authorization", QString("Client-ID %1").arg(clientId()).toLatin1());

    QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);

    if (!mSettings.value("anonymous", true).toBool()) {
        request.setRawHeader("Authorization", QByteArray("Bearer ") + mSettings.value("access_token").toByteArray());

        if (!mSettings.value("album").toString().isEmpty()) {
            QHttpPart albumPart;
            albumPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"album\""));
            albumPart.setBody(mSettings.value("album").toByteArray());
            multiPart->append(albumPart);
        }
    }

    QHttpPart imagePart;
    imagePart.setHeader(QNetworkRequest::ContentTypeHeader, QMimeDatabase().mimeTypeForFile(fileName, QMimeDatabase::MatchExtension).name());
    imagePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"image\""));

    imagePart.setBodyDevice(file);
    file->setParent(multiPart);
    multiPart->append(imagePart);

    QNetworkReply *reply = Uploader::network()->post(request, multiPart);
    reply->setProperty("fileName", fileName);
    this->setProperty("fileName", fileName);
    multiPart->setParent(reply);

#ifdef Q_OS_WIN
    connect(reply, &QNetworkReply::sslErrors, [reply](const QList<QSslError> &errors) {
        Q_UNUSED(errors);
        if (QSysInfo::WindowsVersion <= QSysInfo::WV_2003) {
            reply->ignoreSslErrors();
        }
    });
#endif

    connect(reply, &QNetworkReply::uploadProgress, this, &ImgurUploader::uploadProgress);
    connect(this , &ImgurUploader::cancelRequest, reply, &QNetworkReply::abort);
    connect(this , &ImgurUploader::cancelRequest, reply, &QNetworkReply::deleteLater);

    connect(reply, &QNetworkReply::finished, this, &ImgurUploader::finished);
}
コード例 #7
0
ファイル: main.cpp プロジェクト: Jeff-Lewis/quickanddirty
//! debug message handler
void message_handler(QtMsgType type, const char *msg) {
    QMutexLocker lock(&message_handler_lock);
    QString fileName = QString("%0//%1").arg(QApplication::applicationDirPath()).arg("debug.log");
    QFile* logFile = new QFile(fileName);
    if (logFile->open(QIODevice::Append|QIODevice::Text|QIODevice::Unbuffered)) {
        QString m = QString(msg).trimmed();
        logFile->write(QString("%0\n").arg(m).toAscii());
        logFile->close();
    }
    logFile->deleteLater();
}
コード例 #8
0
ファイル: localdiskrepo.cpp プロジェクト: robguthrie/dudley
void LocalDiskRepo::putFileFailed(QIODevice *device)
{
    qDebug() << "deleting a writable buffer - presumably a put file has failed";
    QFile* f;
    if (!device) {
        f = (QFile*) sender();
    } else {
        f = (QFile*) device;
    }

    f->remove();
    f->deleteLater();
}
コード例 #9
0
ファイル: textinfo.cpp プロジェクト: ytl13508111107/flowFree
bool TextInfo::openFile(QString fileDir){
    QFile *file = new QFile(fileDir);

    if (file->open(QFile::ReadOnly | QFile::Text))
    {
        file->deleteLater();
        QByteArray buff = file->readAll();
        QTextStream stream( &buff );
        stream.setCodec("UTF-8");

        stream>>gameFormat;
        for (int i=1;i<=gameFormat;i++)
            for (int j=1;j<=gameFormat;j++)
                stream>>map[i][j];
    }else
コード例 #10
0
bool ComicStripFileResource::save(QString id, QByteArray data)
{
    QFile* file = new QFile();
    file->setFileName(path(id));

    bool openResult = file->open(QIODevice::WriteOnly);

    if (!openResult)
        return false;

    qint64 writeResult = file->write(data);

    file->close();
    file->deleteLater();

    return writeResult > 0;
}
コード例 #11
0
FlowFree::FlowFree(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::FlowFree) {
    ui->setupUi(this);

    QFile *file = new QFile(":/stylesheets/button.qss");
        file->open(QFile::ReadOnly);
        setStyleSheet(file->readAll());
        file->deleteLater();

    quint32 gameSize = GameModel::instance()->size();
    connect(this, SIGNAL(loadLevel(quint32)),
            ui->gameScene, SLOT(onLoadLevel(quint32)));

    connect(ui->lastLevelButton, &QPushButton::clicked,
    [=]() {
        emit loadLevel(--currentLevelId);
        ui->resultButton->setEnabled(false);
        ui->lastLevelButton->setEnabled(currentLevelId != 1);
        ui->nextLevelButton->setEnabled(currentLevelId != gameSize);
    });

    connect(ui->reloadButton, &QPushButton::clicked,
    [=]() {
        emit loadLevel(currentLevelId);
        ui->resultButton->setEnabled(false);
    });

    connect(ui->nextLevelButton, &QPushButton::clicked,
    [=]() {
        emit loadLevel(++currentLevelId);
        ui->resultButton->setEnabled(false);
        ui->lastLevelButton->setEnabled(currentLevelId != 1);
        ui->nextLevelButton->setEnabled(currentLevelId != gameSize);
    });

    connect(ui->resultButton, &QPushButton::clicked,
            ui->gameScene, &GameScene::autoSolve);

    connect(ui->resultButton, &QPushButton::clicked,
    [=]() {
        ui->resultButton->setEnabled(false);
    });

    connect(ui->gameScene, &GameScene::nextLevel,
    [=]() {
        ui->nextLevelButton->click();
    });

    connect(ui->soundCheckBox, &QCheckBox::stateChanged,
            ui->gameScene, &GameScene::setSound);

    connect(ui->gameScene, SIGNAL(timeChanged(int)),
            ui->lcdNumber, SLOT(display(int)));

    connect(ui->gameScene, &GameScene::enableResultButton,
    [=]() {
        ui->resultButton->setEnabled(true);
    });

    currentLevelId = 0;
    ui->nextLevelButton->click();
}
コード例 #12
0
void PomfUploader::upload(const QString &fileName)
{
    QString pomfUrl = mSettings["pomf_url"].toString();

    if (pomfUrl.isEmpty()) {
        emit error(ImageUploader::HostError, tr("Invalid pomf uploader URL!"), fileName);
        return;
    }

    QUrl url = QUrl::fromUserInput(pomfUrl + "/upload.php");

    QFile *file = new QFile(fileName);

    if (!file->open(QIODevice::ReadOnly)) {
        emit error(ImageUploader::FileError, tr("Unable to read screenshot file"), fileName);
        file->deleteLater();
        return;
    }

    QNetworkRequest request(url);

    QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);

    QHttpPart imagePart;
    imagePart.setHeader(QNetworkRequest::ContentTypeHeader, QMimeDatabase().mimeTypeForFile(fileName, QMimeDatabase::MatchExtension).name());
    imagePart.setHeader(QNetworkRequest::ContentDispositionHeader, QString("form-data; name=\"files[]\"; filename=\"%1\"").arg(QFileInfo(fileName).fileName()));
    imagePart.setBodyDevice(file);

    file->setParent(multiPart);
    multiPart->append(imagePart);

    QNetworkReply *reply = Uploader::network()->post(request, multiPart);
    this->setProperty("fileName", fileName);
    multiPart->setParent(reply);

    connect(this , &PomfUploader::cancelRequest, reply, &QNetworkReply::abort);
    connect(this , &PomfUploader::cancelRequest, reply, &QNetworkReply::deleteLater);

    connect(reply, &QNetworkReply::uploadProgress, this, [&](qint64 bytesSent, qint64 bytesTotal) {
        float b = (float) bytesSent / bytesTotal;
        int p = qRound(b * 100);
        setProgress(p);
    });

    connect(reply, &QNetworkReply::finished, this, [&, reply, fileName] {
        const QJsonObject pomfResponse = QJsonDocument::fromJson(reply->readAll()).object();

        if (reply->error() != QNetworkReply::NoError && pomfResponse.isEmpty()) {
            emit error(ImageUploader::NetworkError, tr("Error reaching uploader"), fileName);
            return;
        }

        if (!pomfResponse.contains("success") || !pomfResponse.contains("files")) {
            emit error(ImageUploader::HostError, tr("Invalid response from uploader"), fileName);
            return;
        }

        if (pomfResponse["success"].toBool()) {
            emit uploaded(fileName, pomfResponse["files"].toArray().at(0).toObject()["url"].toString(), "");
        } else {
            QString description;

            if (pomfResponse.contains("description")) {
                description = pomfResponse["description"].toString();
            }

            if (description.isEmpty()) {
                description = tr("Host error");
            }

            emit error(ImageUploader::HostError, description, fileName);
        }
    });

    connect(reply, &QNetworkReply::sslErrors, [reply](const QList<QSslError> &errors) {
        Q_UNUSED(errors);
        if (QSysInfo::WindowsVersion == QSysInfo::WV_XP) {
            reply->ignoreSslErrors();
        }
    });
}
コード例 #13
0
ファイル: main.cpp プロジェクト: xtuer/Qt
int main(int argc, char *argv[]) {
    QApplication a(argc, argv);

    // 在代码块里执行网络访问,是为了测试 HttpClient 对象在被析构后,网络访问的回调函数仍然能正常执行
    {
        QString url("http://localhost:8080/rest");

        // [[1]] GET 请求无参数
        HttpClient(url).get([](const QString &response) {
            qDebug().noquote() << response;
        });

        // [[2]] GET 请求有参数,有自定义 header
        HttpClient(url).debug(true).param("name", "诸葛亮").header("token", "md5sum").get([](const QString &response) {
            qDebug().noquote() << response;
        });
        // 提示: 多个参数也可以传入 map: HttpClient(url).params({{"name", "诸葛亮"}, {"attackDamage", "99"}}).get(...);

        // [[3]] POST 请求,使用 param 添加参数,请求的参数使用 Form 格式
        HttpClient(url).debug(true).param("name", "卧龙")
                .post([](const QString &response) {
            qDebug().noquote() << response;
        });

        // [[4]] PUT 请求,使用 json 添加参数,请求的参数使用 Json 格式
        HttpClient(url).debug(true).json("{\"name\": \"孔明\"}").put([](const QString &response) {
            qDebug().noquote() << response;
        });

        // [[5]] DELETE 请求
        HttpClient(url).debug(true).remove([](const QString &response) {
            qDebug().noquote() << response;
        });
    }

    {
        // [[6]] 下载: 直接保存到文件
        HttpClient("http://xtuer.github.io/img/dog.png").debug(true).download("/Users/Biao/Desktop/dog-1.png");

        // [[7]] 下载: 自己处理下载得到的字节数据
        QFile *file = new QFile("/Users/Biao/Desktop/dog-2.png");
        if (file->open(QIODevice::WriteOnly)) {
            HttpClient("http://xtuer.github.io/img/dog.png").debug(true).download([=](const QByteArray &data) {
                file->write(data);
            }, [=](const QString &) {
                file->flush();
                file->close();
                file->deleteLater();

                qDebug().noquote() << "下载完成";
            });
        } else {
            file->deleteLater();
            file = nullptr;
        }
    }

    {
        // [[8]] 上传文件
        HttpClient("http://localhost:8080/upload").debug(true).upload(QString("/Users/Biao/Pictures/ade.jpg"));

        // [[9]] 上传文件: 也能同时传参数
        HttpClient("http://localhost:8080/upload").debug(true)
                .param("username", "Alice").param("password", "Passw0rd")
                .upload(QString("/Users/Biao/Pictures/ade.jpg"));

        // [[10]] 上传数据: 例如使用摄像头拍照后直接把图片数据传到服务器
        QFile dataFile("/Users/Biao/Pictures/ade.jpg");
        dataFile.open(QIODevice::ReadOnly);
        QByteArray data = dataFile.readAll();
        HttpClient("http://localhost:8080/upload").debug(true).upload(data);

        // [[11]] 上传多个文件文件
        QStringList paths;
        paths << "/Users/Biao/Desktop/photo.jpg" << "/Users/Biao/Desktop/project.numbers";
        HttpClient("http://localhost:8080/uploads").debug(true).upload(paths);
    }

    {
        // [[12]] 共享 QNetworkAccessManager
        // 每创建一个 QNetworkAccessManager 对象都会创建一个线程,当频繁的访问网络时,为了节省线程资源,调用 manager()
        // 使用共享的 QNetworkAccessManager,它不会被 HttpClient 删除,需要我们自己不用的时候删除它。
        // 如果下面的代码不传入 QNetworkAccessManager,从任务管理器里可以看到创建了几千个线程。
        QNetworkAccessManager *manager = new QNetworkAccessManager();
        for (int i = 0; i < 5000; ++i) {
            HttpClient("http://localhost:8080/rest").manager(manager).get([=](const QString &response) {
                qDebug().noquote() << response << ", " << i;
            });
        }
    }

    return a.exec();
}