This commit is contained in:
朱子楚\zhuzi
2024-03-27 09:45:56 +08:00
parent e81a2cc849
commit c52439ac39
15 changed files with 396 additions and 481 deletions

View File

@ -13,7 +13,7 @@ set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
#设置版本号
add_definitions(-DFLUENTUI_VERSION=1,7,3,0)
add_definitions(-DFLUENTUI_VERSION=1,7,4,0)
if (FLUENTUI_BUILD_STATIC_LIB)
add_definitions(-DFLUENTUI_BUILD_STATIC_LIB)

View File

@ -4,17 +4,6 @@
#include <QObject>
#include <QtQml/qqml.h>
namespace FluNetworkType {
Q_NAMESPACE
enum CacheMode {
NoCache = 0x0000,
RequestFailedReadCache = 0x0001,
IfNoneCacheRequest = 0x0002,
FirstCacheThenRequest = 0x0004,
};
Q_ENUM_NS(CacheMode)
QML_NAMED_ELEMENT(FluNetworkType)
}
namespace FluThemeType {
Q_NAMESPACE

View File

@ -1,676 +0,0 @@
#include "FluNetwork.h"
#include <QUrlQuery>
#include <QBuffer>
#include <QHttpMultiPart>
#include <QJsonDocument>
#include <QNetworkReply>
#include <QJsonObject>
#include <QNetworkDiskCache>
#include <QQmlEngine>
#include <QQmlContext>
#include <QJSEngine>
#include <QJsonArray>
#include <QStandardPaths>
#include <QThreadPool>
#include <QDir>
#include <QCryptographicHash>
#include <QEventLoop>
#include <QGuiApplication>
FluNetworkCallable::FluNetworkCallable(QObject *parent):QObject{parent}{
}
QString FluNetworkParams::method2String(){
switch (_method) {
case METHOD_GET:
return "GET";
case METHOD_HEAD:
return "HEAD";
case METHOD_POST:
return "POST";
case METHOD_PUT:
return "PUT";
case METHOD_PATCH:
return "PATCH";
case METHOD_DELETE:
return "DELETE";
default:
return "";
}
}
int FluNetworkParams::getTimeout(){
if(_timeout != -1){
return _timeout;
}
return FluNetwork::getInstance()->timeout();
}
int FluNetworkParams::getRetry(){
if(_retry != -1){
return _retry;
}
return FluNetwork::getInstance()->retry();
}
bool FluNetworkParams::getOpenLog(){
if(!_openLog.isNull()){
return _openLog.toBool();
}
return FluNetwork::getInstance()->openLog();
}
FluDownloadParam::FluDownloadParam(QObject *parent)
: QObject{parent}
{
}
FluDownloadParam::FluDownloadParam(QString destPath,bool append,QObject *parent)
: QObject{parent}
{
this->_destPath = destPath;
this->_append = append;
}
FluNetworkParams::FluNetworkParams(QObject *parent)
: QObject{parent}
{
}
FluNetworkParams::FluNetworkParams(QString url,Type type,Method method,QObject *parent)
: QObject{parent}
{
this->_method = method;
this->_url = url;
this->_type = type;
}
FluNetworkParams* FluNetworkParams::add(QString key,QVariant val){
_paramMap.insert(key,val);
return this;
}
FluNetworkParams* FluNetworkParams::addFile(QString key,QVariant val){
_fileMap.insert(key,val);
return this;
}
FluNetworkParams* FluNetworkParams::addHeader(QString key,QVariant val){
_headerMap.insert(key,val);
return this;
}
FluNetworkParams* FluNetworkParams::addQuery(QString key,QVariant val){
_queryMap.insert(key,val);
return this;
}
FluNetworkParams* FluNetworkParams::setBody(QString val){
_body = val;
return this;
}
FluNetworkParams* FluNetworkParams::setTimeout(int val){
_timeout = val;
return this;
}
FluNetworkParams* FluNetworkParams::setRetry(int val){
_retry = val;
return this;
}
FluNetworkParams* FluNetworkParams::setCacheMode(int val){
_cacheMode = val;
return this;
}
FluNetworkParams* FluNetworkParams::toDownload(QString destPath,bool append){
_downloadParam = new FluDownloadParam(destPath,append,this);
return this;
}
FluNetworkParams* FluNetworkParams::bind(QObject* target){
_target = target;
return this;
}
FluNetworkParams* FluNetworkParams::openLog(QVariant val){
_openLog = val;
return this;
}
QString FluNetworkParams::buildCacheKey(){
QJsonObject obj;
obj.insert("url",_url);
obj.insert("method",method2String());
obj.insert("body",_body);
obj.insert("query",QJsonDocument::fromVariant(_queryMap).object());
obj.insert("param",QJsonDocument::fromVariant(_paramMap).object());
obj.insert("header",QJsonDocument::fromVariant(_headerMap).object());
obj.insert("file",QJsonDocument::fromVariant(_fileMap).object());
if(_downloadParam){
QJsonObject downObj;
downObj.insert("destPath",_downloadParam->_destPath);
downObj.insert("append",_downloadParam->_append);
obj.insert("download",downObj);
}
QByteArray data = QJsonDocument(obj).toJson(QJsonDocument::Compact);
return QCryptographicHash::hash(data, QCryptographicHash::Sha256).toHex();
}
void FluNetworkParams::go(FluNetworkCallable* callable){
QJSValueList data;
data<<qjsEngine(callable)->newQObject(this);
FluNetwork::getInstance()->_interceptor.call(data);
if(_downloadParam){
FluNetwork::getInstance()->handleDownload(this,callable);
}else{
FluNetwork::getInstance()->handle(this,callable);
}
}
void FluNetwork::handle(FluNetworkParams* params,FluNetworkCallable* c){
QPointer<FluNetworkCallable> callable(c);
QThreadPool::globalInstance()->start([=](){
if(!callable.isNull()){
callable->start();
}
QString cacheKey = params->buildCacheKey();
if(params->_cacheMode == FluNetworkType::CacheMode::FirstCacheThenRequest && cacheExists(cacheKey)){
if(!callable.isNull()){
callable->cache(readCache(cacheKey));
}
}
if(params->_cacheMode == FluNetworkType::CacheMode::IfNoneCacheRequest && cacheExists(cacheKey)){
if(!callable.isNull()){
callable->cache(readCache(cacheKey));
callable->finish();
params->deleteLater();
}
return;
}
QNetworkAccessManager manager;
manager.setTransferTimeout(params->getTimeout());
QEventLoop loop;
connect(&manager,&QNetworkAccessManager::finished,&manager,[&loop](QNetworkReply *reply){loop.quit();});
for (int i = 0; i < params->getRetry(); ++i) {
QUrl url(params->_url);
addQueryParam(&url,params->_queryMap);
QNetworkRequest request(url);
addHeaders(&request,params->_headerMap);
QNetworkReply* reply;
sendRequest(&manager,request,params,reply,i==0,callable);
if(!QPointer<QGuiApplication>(qApp)){
reply->deleteLater();
reply = nullptr;
return;
}
auto abortCallable = [&loop,reply,&i,params]{
if(reply){
i = params->getRetry();
reply->abort();
}
};
QMetaObject::Connection conn_destroyed = {};
QMetaObject::Connection conn_quit = {};
if(params->_target){
conn_destroyed = connect(params->_target,&QObject::destroyed,&manager,abortCallable);
}
conn_quit = connect(qApp,&QGuiApplication::aboutToQuit,&manager, abortCallable);
loop.exec();
if(conn_destroyed){
disconnect(conn_destroyed);
}
if(conn_quit){
disconnect(conn_quit);
}
QString response;
if(params->_method == FluNetworkParams::METHOD_HEAD){
response = headerList2String(reply->rawHeaderPairs());
}else{
if(reply->isOpen()){
response = QString::fromUtf8(reply->readAll());
}
}
int httpStatus = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
if(httpStatus == 200){
if(!callable.isNull()){
if(params->_cacheMode != FluNetworkType::CacheMode::NoCache){
saveResponse(cacheKey,response);
}
callable->success(response);
}
printRequestEndLog(request,params,reply,response);
break;
}else{
if(i == params->getRetry()-1){
if(!callable.isNull()){
if(params->_cacheMode == FluNetworkType::CacheMode::RequestFailedReadCache && cacheExists(cacheKey)){
if(!callable.isNull()){
callable->cache(readCache(cacheKey));
}
}
callable->error(httpStatus,reply->errorString(),response);
}
printRequestEndLog(request,params,reply,response);
}
}
reply->deleteLater();
}
params->deleteLater();
if(!callable.isNull()){
callable->finish();
}
});
}
void FluNetwork::handleDownload(FluNetworkParams* params,FluNetworkCallable* c){
QPointer<FluNetworkCallable> callable(c);
QThreadPool::globalInstance()->start([=](){
if(!callable.isNull()){
callable->start();
}
QString cacheKey = params->buildCacheKey();
QUrl url(params->_url);
QNetworkAccessManager manager;
manager.setTransferTimeout(params->getTimeout());
addQueryParam(&url,params->_queryMap);
QNetworkRequest request(url);
addHeaders(&request,params->_headerMap);
QString cachePath = getCacheFilePath(cacheKey);
QString destPath = params->_downloadParam->_destPath;
QFile* destFile = new QFile(destPath);
QFile* cacheFile = new QFile(cachePath);
bool isOpen = false;
qint64 seek = 0;
if(cacheFile->exists() && destFile->exists() && params->_downloadParam->_append){
QJsonObject cacheInfo = QJsonDocument::fromJson(readCache(cacheKey).toUtf8()).object();
qint64 fileSize = cacheInfo.value("fileSize").toDouble();
qint64 contentLength = cacheInfo.value("contentLength").toDouble();
if(fileSize == contentLength && destFile->size() == contentLength){
if(!callable.isNull()){
callable->downloadProgress(fileSize,contentLength);
callable->success(destPath);
callable->finish();
}
return;
}
if(fileSize==destFile->size()){
request.setRawHeader("Range", QString("bytes=%1-").arg(fileSize).toUtf8());
seek = fileSize;
isOpen = destFile->open(QIODevice::WriteOnly|QIODevice::Append);
}else{
isOpen = destFile->open(QIODevice::WriteOnly|QIODevice::Truncate);
}
}else{
isOpen = destFile->open(QIODevice::WriteOnly|QIODevice::Truncate);
}
if(!isOpen){
if(!callable.isNull()){
callable->error(-1,"device not open","");
callable->finish();
}
return;
}
if(params->_downloadParam->_append){
if (!cacheFile->open(QIODevice::WriteOnly|QIODevice::Truncate))
{
if(!callable.isNull()){
callable->error(-1,"cache file device not open","");
callable->finish();
}
return;
}
}
QEventLoop loop;
QNetworkReply *reply = manager.get(request);
destFile->setParent(reply);
cacheFile->setParent(reply);
auto abortCallable = [&loop,reply,params]{
if(reply){
reply->abort();
}
};
connect(&manager,&QNetworkAccessManager::finished,&manager,[&loop](QNetworkReply *reply){loop.quit();});
connect(qApp,&QGuiApplication::aboutToQuit,&manager, [&loop,reply](){reply->abort(),loop.quit();});
QMetaObject::Connection conn_destroyed = {};
QMetaObject::Connection conn_quit = {};
if(params->_target){
conn_destroyed = connect(params->_target,&QObject::destroyed,&manager,abortCallable);
}
conn_quit = connect(qApp,&QGuiApplication::aboutToQuit,&manager, abortCallable);
connect(reply,&QNetworkReply::readyRead,reply,[reply,seek,destFile,cacheFile,callable]{
if (!reply || !destFile || reply->error() != QNetworkReply::NoError)
{
return;
}
QMap<QString, QVariant> downInfo;
qint64 contentLength = reply->header(QNetworkRequest::ContentLengthHeader).toLongLong()+seek;
downInfo.insert("contentLength",contentLength);
QString eTag = reply->header(QNetworkRequest::ETagHeader).toString();
downInfo.insert("eTag",eTag);
destFile->write(reply->readAll());
destFile->flush();
downInfo.insert("fileSize",destFile->size());
if(cacheFile->isOpen()){
cacheFile->resize(0);
cacheFile->write(QJsonDocument::fromVariant(QVariant(downInfo)).toJson().toBase64());
cacheFile->flush();
}
if(!callable.isNull()){
callable->downloadProgress(destFile->size(),contentLength);
}
});
loop.exec();
int httpStatus = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
if(httpStatus == 200){
if(!callable.isNull()){
callable->success(destPath);
}
printRequestEndLog(request,params,reply,destPath);
}else{
if(!callable.isNull()){
callable->error(httpStatus,reply->errorString(),destPath);
}
printRequestEndLog(request,params,reply,destPath);
}
if(conn_destroyed){
disconnect(conn_destroyed);
}
if(conn_quit){
disconnect(conn_quit);
}
params->deleteLater();
reply->deleteLater();
if(!callable.isNull()){
callable->finish();
}
});
}
QString FluNetwork::readCache(const QString& key){
auto filePath = getCacheFilePath(key);
QString result;
QFile file(filePath);
if(!file.exists()){
return result;
}
if (file.open(QIODevice::ReadOnly)) {
QTextStream stream(&file);
result = QString(QByteArray::fromBase64(stream.readAll().toUtf8()));
}
return result;
}
bool FluNetwork::cacheExists(const QString& key){
return QFile(getCacheFilePath(key)).exists();
}
QString FluNetwork::getCacheFilePath(const QString& key){
QDir cacheDir(_cacheDir);
if(!cacheDir.exists()){
cacheDir.mkpath(_cacheDir);
}
return cacheDir.absoluteFilePath(key);
}
QString FluNetwork::headerList2String(const QList<QNetworkReply::RawHeaderPair>& data){
QJsonObject object;
for (auto it = data.constBegin(); it != data.constEnd(); ++it) {
object.insert(QString(it->first),QString(it->second));
}
return QJsonDocument(object).toJson(QJsonDocument::Compact);
}
QString FluNetwork::map2String(const QMap<QString, QVariant>& map){
QStringList parameters;
for (auto it = map.constBegin(); it != map.constEnd(); ++it) {
parameters << QString("%1=%2").arg(it.key(), it.value().toString());
}
return parameters.join(" ");
}
void FluNetwork::sendRequest(QNetworkAccessManager* manager,QNetworkRequest request,FluNetworkParams* params,QNetworkReply*& reply,bool isFirst,QPointer<FluNetworkCallable> callable){
QByteArray verb = params->method2String().toUtf8();
switch (params->_type) {
case FluNetworkParams::TYPE_FORM:{
bool isFormData = !params->_fileMap.isEmpty();
if(isFormData){
QHttpMultiPart *multiPart = new QHttpMultiPart();
multiPart->setContentType(QHttpMultiPart::FormDataType);
for (const auto& each : params->_paramMap.toStdMap())
{
QHttpPart part;
part.setHeader(QNetworkRequest::ContentDispositionHeader, QString("form-data; name=\"%1\"").arg(each.first));
part.setBody(each.second.toByteArray());
multiPart->append(part);
}
for (const auto& each : params->_fileMap.toStdMap())
{
QString filePath = each.second.toString();
QString name = each.first;
QFile *file = new QFile(filePath);
QString fileName = QFileInfo(filePath).fileName();
file->open(QIODevice::ReadOnly);
file->setParent(multiPart);
QHttpPart part;
part.setHeader(QNetworkRequest::ContentDispositionHeader, QString("form-data; name=\"%1\"; filename=\"%2\"").arg(name,fileName));
part.setBodyDevice(file);
multiPart->append(part);
}
reply = manager->sendCustomRequest(request,verb,multiPart);
multiPart->setParent(reply);
connect(reply,&QNetworkReply::uploadProgress,reply,[callable](qint64 bytesSent, qint64 bytesTotal){
if(!callable.isNull() && bytesSent!=0 && bytesTotal!=0){
Q_EMIT callable->uploadProgress(bytesSent,bytesTotal);
}
});
}else{
request.setHeader(QNetworkRequest::ContentTypeHeader, QString("application/x-www-form-urlencoded"));
QString value;
for (const auto& each : params->_paramMap.toStdMap())
{
value += QString("%1=%2").arg(each.first,each.second.toString());
value += "&";
}
if(!params->_paramMap.isEmpty()){
value.chop(1);
}
QByteArray data = value.toUtf8();
reply = manager->sendCustomRequest(request,verb,data);
}
break;
}
case FluNetworkParams::TYPE_JSON:{
request.setHeader(QNetworkRequest::ContentTypeHeader, QString("application/json;charset=utf-8"));
QJsonObject json;
for (const auto& each : params->_paramMap.toStdMap())
{
json.insert(each.first,each.second.toJsonValue());
}
QByteArray data = QJsonDocument(json).toJson(QJsonDocument::Compact);
reply = manager->sendCustomRequest(request,verb,data);
break;
}
case FluNetworkParams::TYPE_JSONARRAY:{
request.setHeader(QNetworkRequest::ContentTypeHeader, QString("application/json;charset=utf-8"));
QJsonArray jsonArray;
for (const auto& each : params->_paramMap.toStdMap())
{
QJsonObject json;
json.insert(each.first,each.second.toJsonValue());
jsonArray.append(json);
}
QByteArray data = QJsonDocument(jsonArray).toJson(QJsonDocument::Compact);
reply = manager->sendCustomRequest(request,params->method2String().toUtf8(),data);
break;
}
case FluNetworkParams::TYPE_BODY:{
request.setHeader(QNetworkRequest::ContentTypeHeader, QString("text/plain;charset=utf-8"));
QByteArray data = params->_body.toUtf8();
reply = manager->sendCustomRequest(request,verb,data);
break;
}
default:
reply = manager->sendCustomRequest(request,verb);
break;
}
if(isFirst){
printRequestStartLog(request,params);
}
}
void FluNetwork::printRequestStartLog(QNetworkRequest request,FluNetworkParams* params){
if(!params->getOpenLog()){
return;
}
qDebug()<<"<------"<<qUtf8Printable(request.header(QNetworkRequest::UserAgentHeader).toString())<<"Request Start ------>";
qDebug()<<qUtf8Printable(QString::fromStdString("<%1>").arg(params->method2String()))<<qUtf8Printable(params->_url);
auto contentType = request.header(QNetworkRequest::ContentTypeHeader).toString();
if(!contentType.isEmpty()){
qDebug()<<qUtf8Printable(QString::fromStdString("<Header> %1=%2").arg("Content-Type",contentType));
}
QList<QByteArray> headers = request.rawHeaderList();
for(const QByteArray& header:headers){
qDebug()<<qUtf8Printable(QString::fromStdString("<Header> %1=%2").arg(header,request.rawHeader(header)));
}
if(!params->_queryMap.isEmpty()){
qDebug()<<"<Query>"<<qUtf8Printable(map2String(params->_queryMap));
}
if(!params->_paramMap.isEmpty()){
qDebug()<<"<Param>"<<qUtf8Printable(map2String(params->_paramMap));
}
if(!params->_fileMap.isEmpty()){
qDebug()<<"<File>"<<qUtf8Printable(map2String(params->_fileMap));
}
if(!params->_body.isEmpty()){
qDebug()<<"<Body>"<<qUtf8Printable(params->_body);
}
}
void FluNetwork::printRequestEndLog(QNetworkRequest request,FluNetworkParams* params,QNetworkReply*& reply,const QString& response){
if(!params->getOpenLog()){
return;
}
qDebug()<<"<------"<<qUtf8Printable(request.header(QNetworkRequest::UserAgentHeader).toString())<<"Request End ------>";
qDebug()<<qUtf8Printable(QString::fromStdString("<%1>").arg(params->method2String()))<<qUtf8Printable(params->_url);
qDebug()<<"<Result>"<<qUtf8Printable(response);
}
void FluNetwork::saveResponse(QString key,QString response){
QSharedPointer<QFile> file(new QFile(getCacheFilePath(key)));
QIODevice::OpenMode mode = QIODevice::WriteOnly|QIODevice::Truncate;
if (!file->open(mode))
{
return;
}
file->write(response.toUtf8().toBase64());
}
void FluNetwork::addHeaders(QNetworkRequest* request,const QMap<QString, QVariant>& headers){
request->setHeader(QNetworkRequest::UserAgentHeader,QString::fromStdString("Mozilla/5.0 %1/%2").arg(QGuiApplication::applicationName(),QGuiApplication::applicationVersion()));
QMapIterator<QString, QVariant> iter(headers);
while (iter.hasNext())
{
iter.next();
request->setRawHeader(iter.key().toUtf8(), iter.value().toString().toUtf8());
}
}
void FluNetwork::addQueryParam(QUrl* url,const QMap<QString, QVariant>& params){
QMapIterator<QString, QVariant> iter(params);
QUrlQuery urlQuery(*url);
while (iter.hasNext())
{
iter.next();
urlQuery.addQueryItem(iter.key(), iter.value().toString());
}
url->setQuery(urlQuery);
}
FluNetwork::FluNetwork(QObject *parent): QObject{parent}
{
timeout(5000);
retry(3);
openLog(false);
cacheDir(QStandardPaths::writableLocation(QStandardPaths::CacheLocation).append(QDir::separator()).append("network"));
}
FluNetworkParams* FluNetwork::get(const QString& url){
return new FluNetworkParams(url,FluNetworkParams::TYPE_NONE,FluNetworkParams::METHOD_GET,this);
}
FluNetworkParams* FluNetwork::head(const QString& url){
return new FluNetworkParams(url,FluNetworkParams::TYPE_NONE,FluNetworkParams::METHOD_HEAD,this);
}
FluNetworkParams* FluNetwork::postBody(const QString& url){
return new FluNetworkParams(url,FluNetworkParams::TYPE_BODY,FluNetworkParams::METHOD_POST,this);
}
FluNetworkParams* FluNetwork::putBody(const QString& url){
return new FluNetworkParams(url,FluNetworkParams::TYPE_BODY,FluNetworkParams::METHOD_PUT,this);
}
FluNetworkParams* FluNetwork::patchBody(const QString& url){
return new FluNetworkParams(url,FluNetworkParams::TYPE_BODY,FluNetworkParams::METHOD_PATCH,this);
}
FluNetworkParams* FluNetwork::deleteBody(const QString& url){
return new FluNetworkParams(url,FluNetworkParams::TYPE_BODY,FluNetworkParams::METHOD_DELETE,this);
}
FluNetworkParams* FluNetwork::postForm(const QString& url){
return new FluNetworkParams(url,FluNetworkParams::TYPE_FORM,FluNetworkParams::METHOD_POST,this);
}
FluNetworkParams* FluNetwork::putForm(const QString& url){
return new FluNetworkParams(url,FluNetworkParams::TYPE_FORM,FluNetworkParams::METHOD_PUT,this);
}
FluNetworkParams* FluNetwork::patchForm(const QString& url){
return new FluNetworkParams(url,FluNetworkParams::TYPE_FORM,FluNetworkParams::METHOD_PATCH,this);
}
FluNetworkParams* FluNetwork::deleteForm(const QString& url){
return new FluNetworkParams(url,FluNetworkParams::TYPE_FORM,FluNetworkParams::METHOD_DELETE,this);
}
FluNetworkParams* FluNetwork::postJson(const QString& url){
return new FluNetworkParams(url,FluNetworkParams::TYPE_JSON,FluNetworkParams::METHOD_POST,this);
}
FluNetworkParams* FluNetwork::putJson(const QString& url){
return new FluNetworkParams(url,FluNetworkParams::TYPE_JSON,FluNetworkParams::METHOD_PUT,this);
}
FluNetworkParams* FluNetwork::patchJson(const QString& url){
return new FluNetworkParams(url,FluNetworkParams::TYPE_JSON,FluNetworkParams::METHOD_PATCH,this);
}
FluNetworkParams* FluNetwork::deleteJson(const QString& url){
return new FluNetworkParams(url,FluNetworkParams::TYPE_JSON,FluNetworkParams::METHOD_DELETE,this);
}
FluNetworkParams* FluNetwork::postJsonArray(const QString& url){
return new FluNetworkParams(url,FluNetworkParams::TYPE_JSONARRAY,FluNetworkParams::METHOD_POST,this);
}
FluNetworkParams* FluNetwork::putJsonArray(const QString& url){
return new FluNetworkParams(url,FluNetworkParams::TYPE_JSONARRAY,FluNetworkParams::METHOD_PUT,this);
}
FluNetworkParams* FluNetwork::patchJsonArray(const QString& url){
return new FluNetworkParams(url,FluNetworkParams::TYPE_JSONARRAY,FluNetworkParams::METHOD_PATCH,this);
}
FluNetworkParams* FluNetwork::deleteJsonArray(const QString& url){
return new FluNetworkParams(url,FluNetworkParams::TYPE_JSONARRAY,FluNetworkParams::METHOD_DELETE,this);
}
void FluNetwork::setInterceptor(QJSValue interceptor){
this->_interceptor = interceptor;
}

View File

@ -1,158 +0,0 @@
#ifndef FLUNETWORK_H
#define FLUNETWORK_H
#include <QObject>
#include <QtQml/qqml.h>
#include <QFile>
#include <QJsonValue>
#include <QJSValue>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include "Def.h"
#include "stdafx.h"
#include "singleton.h"
/**
* @brief The NetworkCallable class
*/
class FluNetworkCallable : public QObject{
Q_OBJECT
QML_NAMED_ELEMENT(FluNetworkCallable)
public:
explicit FluNetworkCallable(QObject *parent = nullptr);
Q_SIGNAL void start();
Q_SIGNAL void finish();
Q_SIGNAL void error(int status,QString errorString,QString result);
Q_SIGNAL void success(QString result);
Q_SIGNAL void cache(QString result);
Q_SIGNAL void uploadProgress(qint64 sent, qint64 total);
Q_SIGNAL void downloadProgress(qint64 recv, qint64 total);
};
/**
* @brief The FluDownloadParam class
*/
class FluDownloadParam : public QObject{
Q_OBJECT
public:
explicit FluDownloadParam(QObject *parent = nullptr);
FluDownloadParam(QString destPath,bool append,QObject *parent = nullptr);
public:
QString _destPath;
bool _append;
};
/**
* @brief The FluNetworkParams class
*/
class FluNetworkParams : public QObject
{
Q_OBJECT
QML_NAMED_ELEMENT(FluNetworkParams)
public:
enum Method{
METHOD_GET,
METHOD_HEAD,
METHOD_POST,
METHOD_PUT,
METHOD_PATCH,
METHOD_DELETE
};
enum Type{
TYPE_NONE,
TYPE_FORM,
TYPE_JSON,
TYPE_JSONARRAY,
TYPE_BODY
};
explicit FluNetworkParams(QObject *parent = nullptr);
FluNetworkParams(QString url,Type type,Method method,QObject *parent = nullptr);
Q_INVOKABLE FluNetworkParams* addQuery(QString key,QVariant val);
Q_INVOKABLE FluNetworkParams* addHeader(QString key,QVariant val);
Q_INVOKABLE FluNetworkParams* add(QString key,QVariant val);
Q_INVOKABLE FluNetworkParams* addFile(QString key,QVariant val);
Q_INVOKABLE FluNetworkParams* setBody(QString val);
Q_INVOKABLE FluNetworkParams* setTimeout(int val);
Q_INVOKABLE FluNetworkParams* setRetry(int val);
Q_INVOKABLE FluNetworkParams* setCacheMode(int val);
Q_INVOKABLE FluNetworkParams* toDownload(QString destPath,bool append = false);
Q_INVOKABLE FluNetworkParams* bind(QObject* target);
Q_INVOKABLE FluNetworkParams* openLog(QVariant val);
Q_INVOKABLE void go(FluNetworkCallable* result);
QString buildCacheKey();
QString method2String();
int getTimeout();
int getRetry();
bool getOpenLog();
public:
FluDownloadParam* _downloadParam = nullptr;
QObject* _target = nullptr;
Method _method;
Type _type;
QString _url;
QString _body;
QMap<QString, QVariant> _queryMap;
QMap<QString, QVariant> _headerMap;
QMap<QString, QVariant> _paramMap;
QMap<QString, QVariant> _fileMap;
int _timeout = -1;
int _retry = -1;
QVariant _openLog;
int _cacheMode = FluNetworkType::CacheMode::NoCache;
};
/**
* @brief The FluNetwork class
*/
class FluNetwork : public QObject
{
Q_OBJECT
Q_PROPERTY_AUTO(int,timeout)
Q_PROPERTY_AUTO(int,retry)
Q_PROPERTY_AUTO(QString,cacheDir)
Q_PROPERTY_AUTO(bool,openLog)
QML_NAMED_ELEMENT(FluNetwork)
QML_SINGLETON
private:
explicit FluNetwork(QObject *parent = nullptr);
public:
SINGLETON(FluNetwork)
static FluNetwork *create(QQmlEngine *qmlEngine, QJSEngine *jsEngine){return getInstance();}
Q_INVOKABLE FluNetworkParams* get(const QString& url);
Q_INVOKABLE FluNetworkParams* head(const QString& url);
Q_INVOKABLE FluNetworkParams* postBody(const QString& url);
Q_INVOKABLE FluNetworkParams* putBody(const QString& url);
Q_INVOKABLE FluNetworkParams* patchBody(const QString& url);
Q_INVOKABLE FluNetworkParams* deleteBody(const QString& url);
Q_INVOKABLE FluNetworkParams* postForm(const QString& url);
Q_INVOKABLE FluNetworkParams* putForm(const QString& url);
Q_INVOKABLE FluNetworkParams* patchForm(const QString& url);
Q_INVOKABLE FluNetworkParams* deleteForm(const QString& url);
Q_INVOKABLE FluNetworkParams* postJson(const QString& url);
Q_INVOKABLE FluNetworkParams* putJson(const QString& url);
Q_INVOKABLE FluNetworkParams* patchJson(const QString& url);
Q_INVOKABLE FluNetworkParams* deleteJson(const QString& url);
Q_INVOKABLE FluNetworkParams* postJsonArray(const QString& url);
Q_INVOKABLE FluNetworkParams* putJsonArray(const QString& url);
Q_INVOKABLE FluNetworkParams* patchJsonArray(const QString& url);
Q_INVOKABLE FluNetworkParams* deleteJsonArray(const QString& url);
Q_INVOKABLE void setInterceptor(QJSValue interceptor);
void handle(FluNetworkParams* params,FluNetworkCallable* result);
void handleDownload(FluNetworkParams* params,FluNetworkCallable* result);
private:
void sendRequest(QNetworkAccessManager* manager,QNetworkRequest request,FluNetworkParams* params,QNetworkReply*& reply,bool isFirst,QPointer<FluNetworkCallable> callable);
void addQueryParam(QUrl* url,const QMap<QString, QVariant>& params);
void addHeaders(QNetworkRequest* request,const QMap<QString, QVariant>& headers);
void saveResponse(QString key,QString response);
QString readCache(const QString& key);
bool cacheExists(const QString& key);
QString getCacheFilePath(const QString& key);
QString map2String(const QMap<QString, QVariant>& map);
QString headerList2String(const QList<QNetworkReply::RawHeaderPair>& data);
void printRequestStartLog(QNetworkRequest request,FluNetworkParams* params);
void printRequestEndLog(QNetworkRequest request,FluNetworkParams* params,QNetworkReply*& reply,const QString& response);
public:
QJSValue _interceptor;
};
#endif // FLUNETWORK_H

View File

@ -12,7 +12,6 @@
#include "FluEventBus.h"
#include "FluTreeModel.h"
#include "FluRectangle.h"
#include "FluNetwork.h"
#include "FluFramelessHelper.h"
#include "FluQrCodeItem.h"
#include "FluTableSortProxyModel.h"
@ -32,8 +31,6 @@ void FluentUI::registerTypes(const char *uri){
qmlRegisterType<FluEvent>(uri,major,minor,"FluEvent");
qmlRegisterType<FluTreeModel>(uri,major,minor,"FluTreeModel");
qmlRegisterType<FluRectangle>(uri,major,minor,"FluRectangle");
qmlRegisterType<FluNetworkCallable>(uri,major,minor,"FluNetworkCallable");
qmlRegisterType<FluNetworkParams>(uri,major,minor,"FluNetworkParams");
qmlRegisterType<FluFramelessHelper>(uri,major,minor,"FluFramelessHelper");
qmlRegisterType<FluTableSortProxyModel>(uri,major,minor,"FluTableSortProxyModel");
@ -140,7 +137,6 @@ void FluentUI::registerTypes(const char *uri){
qmlRegisterUncreatableMetaObject(FluTabViewType::staticMetaObject, uri,major,minor,"FluTabViewType", "Access to enums & flags only");
qmlRegisterUncreatableMetaObject(FluNavigationViewType::staticMetaObject, uri,major,minor,"FluNavigationViewType", "Access to enums & flags only");
qmlRegisterUncreatableMetaObject(FluTimelineType::staticMetaObject, uri,major,minor,"FluTimelineType", "Access to enums & flags only");
qmlRegisterUncreatableMetaObject(FluNetworkType::staticMetaObject, uri,major,minor,"FluNetworkType", "Access to enums & flags only");
qmlRegisterModule(uri,major,minor);
#endif
@ -158,5 +154,4 @@ void FluentUI::initializeEngine(QQmlEngine *engine, const char *uri){
engine->rootContext()->setContextProperty("FluTools",FluTools::getInstance());
engine->rootContext()->setContextProperty("FluTextStyle",FluTextStyle::getInstance());
engine->rootContext()->setContextProperty("FluEventBus",FluEventBus::getInstance());
engine->rootContext()->setContextProperty("FluNetwork",FluNetwork::getInstance());
}

View File

@ -109,128 +109,6 @@ Module {
}
}
}
Component {
name: "FluNetworkCallable"
prototype: "QObject"
exports: ["FluentUI/FluNetworkCallable 1.0"]
exportMetaObjectRevisions: [0]
Signal { name: "start" }
Signal { name: "finish" }
Signal {
name: "error"
Parameter { name: "status"; type: "int" }
Parameter { name: "errorString"; type: "string" }
Parameter { name: "result"; type: "string" }
}
Signal {
name: "success"
Parameter { name: "result"; type: "string" }
}
Signal {
name: "cache"
Parameter { name: "result"; type: "string" }
}
Signal {
name: "uploadProgress"
Parameter { name: "sent"; type: "qlonglong" }
Parameter { name: "total"; type: "qlonglong" }
}
Signal {
name: "downloadProgress"
Parameter { name: "recv"; type: "qlonglong" }
Parameter { name: "total"; type: "qlonglong" }
}
}
Component {
name: "FluNetworkParams"
prototype: "QObject"
exports: ["FluentUI/FluNetworkParams 1.0"]
exportMetaObjectRevisions: [0]
Method {
name: "addQuery"
type: "FluNetworkParams*"
Parameter { name: "key"; type: "string" }
Parameter { name: "val"; type: "QVariant" }
}
Method {
name: "addHeader"
type: "FluNetworkParams*"
Parameter { name: "key"; type: "string" }
Parameter { name: "val"; type: "QVariant" }
}
Method {
name: "add"
type: "FluNetworkParams*"
Parameter { name: "key"; type: "string" }
Parameter { name: "val"; type: "QVariant" }
}
Method {
name: "addFile"
type: "FluNetworkParams*"
Parameter { name: "key"; type: "string" }
Parameter { name: "val"; type: "QVariant" }
}
Method {
name: "setBody"
type: "FluNetworkParams*"
Parameter { name: "val"; type: "string" }
}
Method {
name: "setTimeout"
type: "FluNetworkParams*"
Parameter { name: "val"; type: "int" }
}
Method {
name: "setRetry"
type: "FluNetworkParams*"
Parameter { name: "val"; type: "int" }
}
Method {
name: "setCacheMode"
type: "FluNetworkParams*"
Parameter { name: "val"; type: "int" }
}
Method {
name: "toDownload"
type: "FluNetworkParams*"
Parameter { name: "destPath"; type: "string" }
Parameter { name: "append"; type: "bool" }
}
Method {
name: "toDownload"
type: "FluNetworkParams*"
Parameter { name: "destPath"; type: "string" }
}
Method {
name: "bind"
type: "FluNetworkParams*"
Parameter { name: "target"; type: "QObject"; isPointer: true }
}
Method {
name: "openLog"
type: "FluNetworkParams*"
Parameter { name: "val"; type: "QVariant" }
}
Method {
name: "go"
Parameter { name: "result"; type: "FluNetworkCallable"; isPointer: true }
}
}
Component {
name: "FluNetworkType"
exports: ["FluentUI/FluNetworkType 1.0"]
isCreatable: false
exportMetaObjectRevisions: [0]
Enum {
name: "CacheMode"
values: {
"NoCache": 0,
"RequestFailedReadCache": 1,
"IfNoneCacheRequest": 2,
"FirstCacheThenRequest": 4
}
}
}
Component {
name: "FluPageType"
exports: ["FluentUI/FluPageType 1.0"]
@ -454,27 +332,6 @@ Module {
}
}
}
Component {
name: "FluViewModel"
prototype: "QObject"
exports: ["FluentUI/FluViewModel 1.0"]
exportMetaObjectRevisions: [0]
Property { name: "scope"; type: "int" }
Signal { name: "initData" }
}
Component {
name: "FluViewModelType"
exports: ["FluentUI/FluViewModelType 1.0"]
isCreatable: false
exportMetaObjectRevisions: [0]
Enum {
name: "Scope"
values: {
"Window": 0,
"Application": 1
}
}
}
Component {
name: "FluWatermark"
defaultProperty: "data"
@ -488,22 +345,6 @@ Module {
Property { name: "rotate"; type: "int" }
Property { name: "textSize"; type: "int" }
}
Component {
name: "FluWindowLifecycle"
prototype: "QObject"
exports: ["FluentUI/FluWindowLifecycle 1.0"]
exportMetaObjectRevisions: [0]
Method {
name: "onCompleted"
Parameter { name: "window"; type: "QQuickWindow"; isPointer: true }
}
Method { name: "onDestruction" }
Method {
name: "onVisible"
Parameter { name: "visible"; type: "bool" }
}
Method { name: "onDestoryOnClose" }
}
Component {
name: "FluWindowType"
exports: ["FluentUI/FluWindowType 1.0"]
@ -2401,12 +2242,12 @@ Module {
exportMetaObjectRevisions: [0]
isComposite: true
defaultProperty: "contentData"
Property { name: "contentData"; type: "QObject"; isList: true; isReadonly: true }
Property { name: "paddings"; type: "int" }
Property { name: "leftPadding"; type: "int" }
Property { name: "rightPadding"; type: "int" }
Property { name: "topPadding"; type: "int" }
Property { name: "bottomPadding"; type: "int" }
Property { name: "contentData"; type: "QObject"; isList: true; isReadonly: true }
}
Component {
prototype: "QQuickTextField"
@ -2423,6 +2264,11 @@ Module {
name: "itemClicked"
Parameter { name: "data"; type: "QVariant" }
}
Method {
name: "updateText"
type: "QVariant"
Parameter { name: "text"; type: "QVariant" }
}
Property { name: "disabled"; type: "bool" }
Property { name: "iconSource"; type: "int" }
Property { name: "normalColor"; type: "QColor" }
@ -2903,6 +2749,15 @@ Module {
isComposite: true
defaultProperty: "data"
}
Component {
prototype: "QObject"
name: "FluentUI/FluLauncher 1.0"
exports: ["FluentUI/FluLauncher 1.0"]
exportMetaObjectRevisions: [0]
isComposite: true
defaultProperty: "children"
Property { name: "children"; type: "QObject"; isList: true; isReadonly: true }
}
Component {
prototype: "QQuickLoader"
name: "FluentUI/FluLoader 1.0"
@ -3002,15 +2857,15 @@ Module {
defaultProperty: "data"
Property { name: "logo"; type: "QUrl" }
Property { name: "title"; type: "string" }
Property { name: "items"; type: "FluObject_QMLTYPE_166"; isPointer: true }
Property { name: "footerItems"; type: "FluObject_QMLTYPE_166"; isPointer: true }
Property { name: "items"; type: "FluObject_QMLTYPE_126"; isPointer: true }
Property { name: "footerItems"; type: "FluObject_QMLTYPE_126"; isPointer: true }
Property { name: "displayMode"; type: "int" }
Property { name: "autoSuggestBox"; type: "QQmlComponent"; isPointer: true }
Property { name: "actionItem"; type: "QQmlComponent"; isPointer: true }
Property { name: "topPadding"; type: "int" }
Property { name: "pageMode"; type: "int" }
Property { name: "navItemRightMenu"; type: "FluMenu_QMLTYPE_40"; isPointer: true }
Property { name: "navItemExpanderRightMenu"; type: "FluMenu_QMLTYPE_40"; isPointer: true }
Property { name: "navItemRightMenu"; type: "FluMenu_QMLTYPE_39"; isPointer: true }
Property { name: "navItemExpanderRightMenu"; type: "FluMenu_QMLTYPE_39"; isPointer: true }
Property { name: "navCompactWidth"; type: "int" }
Property { name: "navTopMargin"; type: "int" }
Property { name: "cellHeight"; type: "int" }
@ -3367,6 +3222,39 @@ Module {
Method { name: "showEmptyView"; type: "QVariant" }
Method { name: "showErrorView"; type: "QVariant" }
}
Component {
prototype: "QObject"
name: "FluentUI/FluRouter 1.0"
exports: ["FluentUI/FluRouter 1.0"]
exportMetaObjectRevisions: [0]
isComposite: true
isCreatable: false
isSingleton: true
Property { name: "routes"; type: "QVariant" }
Property { name: "windows"; type: "QVariant" }
Method {
name: "addWindow"
type: "QVariant"
Parameter { name: "window"; type: "QVariant" }
}
Method {
name: "removeWindow"
type: "QVariant"
Parameter { name: "window"; type: "QVariant" }
}
Method {
name: "exit"
type: "QVariant"
Parameter { name: "retCode"; type: "QVariant" }
}
Method {
name: "navigate"
type: "QVariant"
Parameter { name: "route"; type: "QVariant" }
Parameter { name: "argument"; type: "QVariant" }
Parameter { name: "windowRegister"; type: "QVariant" }
}
}
Component {
prototype: "QQuickScrollBar"
name: "FluentUI/FluScrollBar 1.0"
@ -3825,7 +3713,6 @@ Module {
exportMetaObjectRevisions: [0]
isComposite: true
defaultProperty: "contentData"
Property { name: "contentData"; type: "QObject"; isList: true; isReadonly: true }
Property { name: "windowIcon"; type: "string" }
Property { name: "launchMode"; type: "int" }
Property { name: "argument"; type: "QVariant" }
@ -3844,7 +3731,7 @@ Module {
Property { name: "autoMaximize"; type: "bool" }
Property { name: "autoVisible"; type: "bool" }
Property { name: "autoCenter"; type: "bool" }
Property { name: "autoDestory"; type: "bool" }
Property { name: "autoDestroy"; type: "bool" }
Property { name: "useSystemAppBar"; type: "bool" }
Property { name: "resizeBorderColor"; type: "QColor" }
Property { name: "resizeBorderWidth"; type: "int" }
@ -3854,13 +3741,13 @@ Module {
Property { name: "_appBarHeight"; type: "int" }
Property { name: "_windowRegister"; type: "QVariant" }
Property { name: "_route"; type: "string" }
Property { name: "contentData"; type: "QObject"; isList: true; isReadonly: true }
Signal { name: "showSystemMenu" }
Signal {
name: "initArgument"
Parameter { name: "argument"; type: "QVariant" }
}
Signal { name: "firstVisible" }
Method { name: "destoryOnClose"; type: "QVariant" }
Method {
name: "showLoading"
type: "QVariant"
@ -3904,7 +3791,7 @@ Module {
Parameter { name: "path"; type: "QVariant" }
}
Method {
name: "onResult"
name: "setResult"
type: "QVariant"
Parameter { name: "data"; type: "QVariant" }
}
@ -3919,7 +3806,6 @@ Module {
defaultProperty: "contentData"
Property { name: "contentDelegate"; type: "QQmlComponent"; isPointer: true }
Method { name: "showDialog"; type: "QVariant" }
Property { name: "contentData"; type: "QObject"; isList: true; isReadonly: true }
Property { name: "windowIcon"; type: "string" }
Property { name: "launchMode"; type: "int" }
Property { name: "argument"; type: "QVariant" }
@ -3938,7 +3824,7 @@ Module {
Property { name: "autoMaximize"; type: "bool" }
Property { name: "autoVisible"; type: "bool" }
Property { name: "autoCenter"; type: "bool" }
Property { name: "autoDestory"; type: "bool" }
Property { name: "autoDestroy"; type: "bool" }
Property { name: "useSystemAppBar"; type: "bool" }
Property { name: "resizeBorderColor"; type: "QColor" }
Property { name: "resizeBorderWidth"; type: "int" }
@ -3948,13 +3834,13 @@ Module {
Property { name: "_appBarHeight"; type: "int" }
Property { name: "_windowRegister"; type: "QVariant" }
Property { name: "_route"; type: "string" }
Property { name: "contentData"; type: "QObject"; isList: true; isReadonly: true }
Signal { name: "showSystemMenu" }
Signal {
name: "initArgument"
Parameter { name: "argument"; type: "QVariant" }
}
Signal { name: "firstVisible" }
Method { name: "destoryOnClose"; type: "QVariant" }
Method {
name: "showLoading"
type: "QVariant"
@ -3998,10 +3884,35 @@ Module {
Parameter { name: "path"; type: "QVariant" }
}
Method {
name: "onResult"
name: "setResult"
type: "QVariant"
Parameter { name: "data"; type: "QVariant" }
}
Method { name: "showMaximized"; type: "QVariant" }
}
Component {
prototype: "QQuickItem"
name: "FluentUI/FluWindowResultLauncher 1.0"
exports: ["FluentUI/FluWindowResultLauncher 1.0"]
exportMetaObjectRevisions: [0]
isComposite: true
defaultProperty: "data"
Property { name: "_from"; type: "QVariant" }
Property { name: "_to"; type: "QVariant" }
Property { name: "path"; type: "QVariant" }
Signal {
name: "result"
Parameter { name: "data"; type: "QVariant" }
}
Method {
name: "launch"
type: "QVariant"
Parameter { name: "argument"; type: "QVariant" }
}
Method {
name: "setResult"
type: "QVariant"
Parameter { name: "data"; type: "QVariant" }
}
}
}

View File

@ -34,6 +34,7 @@ FluImage 1.0 Controls/FluImage.qml
FluImageButton 1.0 Controls/FluImageButton.qml
FluInfoBar 1.0 Controls/FluInfoBar.qml
FluItemDelegate 1.0 Controls/FluItemDelegate.qml
FluLauncher 1.0 Controls/FluLauncher.qml
FluLoader 1.0 Controls/FluLoader.qml
FluLoadingButton 1.0 Controls/FluLoadingButton.qml
FluMenu 1.0 Controls/FluMenu.qml
@ -64,6 +65,7 @@ FluRadioButtons 1.0 Controls/FluRadioButtons.qml
FluRangeSlider 1.0 Controls/FluRangeSlider.qml
FluRatingControl 1.0 Controls/FluRatingControl.qml
FluRemoteLoader 1.0 Controls/FluRemoteLoader.qml
FluRouter 1.0 Controls/FluRouter.qml
FluScrollBar 1.0 Controls/FluScrollBar.qml
FluScrollIndicator 1.0 Controls/FluScrollIndicator.qml
FluScrollablePage 1.0 Controls/FluScrollablePage.qml
@ -91,6 +93,5 @@ FluTreeView 1.0 Controls/FluTreeView.qml
FluWindow 1.0 Controls/FluWindow.qml
FluWindowDialog 1.0 Controls/FluWindowDialog.qml
FluWindowResultLauncher 1.0 Controls/FluWindowResultLauncher.qml
FluLauncher 1.0 Controls/FluLauncher.qml
plugin fluentuiplugin

View File

@ -104,7 +104,6 @@
<file>FluentUI/Controls/FluLauncher.qml</file>
<file>FluentUI/Controls/FluRouter.qml</file>
<file>FluentUI/Controls/FluWindowResultLauncher.qml</file>
<file>FluentUI/JS/Global.js</file>
<file>FluentUI/Controls/qmldir</file>
</qresource>
</RCC>