1 Star 0 Fork 10

return0 / qtbase

forked from TKG / QtBase 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
base.cpp 11.69 KB
一键复制 编辑 原始数据 按行查看 历史
#include <QString>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QThread>
#include <QEventLoop>
#include <QCoreApplication>
#include <QAbstractEventDispatcher>
#include <QMessageBox>
#include <QPushButton>
#include <QNetworkInterface>
#include <QUuid>
#include <QDir>
#include <QFile>
#include <QTextStream>
#include <QTextCodec>
#include <QDateTime>
#include <QSharedMemory>
#include "base.h"
#ifdef Q_OS_WIN
#include <Windows.h>
#endif
QString getTime(){
//js 返回unix毫秒数
#if 0
QDateTime now = QDateTime::currentDateTime();
QDateTime _1970 = QDateTime(QDate(1970,1,1),QTime(8,0));
qint64 base = _1970.msecsTo(now);
#endif
// or
qint64 base = QDateTime::currentMSecsSinceEpoch();
return QString::number(base);
}
QString getUnixTime(int expires_s){
//返回unix秒数,参数为增加的秒数,未来的expires_s秒数
QDateTime time;
if(expires_s == 0)
time = QDateTime::currentDateTime();
else{
time = QDateTime::currentDateTime().addSecs(expires_s);
}
QDateTime _1970 = QDateTime(QDate(1970,1,1),QTime(0,0,0));
qint64 base = _1970.msecsTo(time)/1000;
return QString::number(base);
}
QByteArray gAccessResult(QNetworkAccessManager *manager, const QString &url, const Header &refer, const QByteArray &array){
QNetworkReply * reply;
if(array.isEmpty()){
reply = gAccessReply(manager,url,refer);
int status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
if(status == 302 || status == 301){
QString url = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toString();
reply->deleteLater();
return gAccessResult(manager,url,refer);
}
}else{
reply = gAccessReply(manager,url,refer,array);
}
QByteArray result = reply->readAll();
reply->deleteLater();
return result;
}
QNetworkReply * gAccessReply(QNetworkAccessManager *manager, const QString & url, const Header &refer, const QByteArray & array){
QNetworkRequest logrequest;
QNetworkReply * reply;
QEventLoop loop;
QObject::connect(manager,SIGNAL(finished(QNetworkReply*)),&loop,SLOT(quit()));
logrequest.setUrl(QUrl(url));
if(array.isEmpty())
logrequest.setRawHeader("Content-Type","text/html;charset=UTF-8");
else
logrequest.setRawHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");//必须为这种content
logrequest.setRawHeader("Accept","text/html,application/xhtml+xml,*/*");
logrequest.setRawHeader("Connection","keep-alive");
if(!refer.isEmpty()){
for(Header::const_iterator it = refer.begin(); it != refer.end(); ++it){
logrequest.setRawHeader(it.key().toUtf8(),it.value().toUtf8());
}
}
logrequest.setRawHeader("User-Agent",HTTP_USER_AGENT);
if(array.isEmpty())
reply = manager->get(logrequest);
else
reply = manager->post(logrequest,array);
loop.exec();
QObject::disconnect(manager,SIGNAL(finished(QNetworkReply*)),&loop,SLOT(quit()));
return reply;
}
int showMessagebox(const QString &title, const QString &text, int icon){
static QMessageBox * box = nullptr;
if(!box){
box = new QMessageBox(0);
QPushButton * ok = box->addButton(QMessageBox::Ok);
ok->setText("确定");
QPushButton * cancel = box->addButton(QMessageBox::Cancel);
cancel->setText("取消");
}
box->setWindowTitle(title);
box->setIcon(QMessageBox::Icon(icon));
box->setText(text);
return box->exec();
}
void showMessageWithUnmode(const QString &title, const QString &text, int icon,QWidget *parent){
QMessageBox * box = new QMessageBox(parent);
box->setModal(false);
box->setAttribute(Qt::WA_DeleteOnClose);//关闭对话框自动析构
box->setWindowTitle(title);
box->setIcon(QMessageBox::Icon(icon));
box->setText(text);
QPushButton * ok = box->addButton(QMessageBox::Ok);
ok->setText("关闭");
QObject::connect(ok,&QPushButton::clicked,[box](){box->close();});
box->activateWindow();
box->showNormal();
box->raise();
}
void g_mySleep(float sec){
QTime t;
t.start();
sec *= 1000;
QAbstractEventDispatcher * dispatcher = QThread::currentThread()->eventDispatcher();
if(dispatcher == NULL){
tkgDebug("休眠无效");
}
/*关于误差:很小,因t.elapsed()是一直在走的,产生的时差是当无限接近于sec,然后休眠100ms,此时将产生±100ms
*关于休眠:1.是为了让出cpu,使线程可以执行其他线程。2:分配事件派发的时间。
*/
while(t.elapsed() < sec){
dispatcher->processEvents(QEventLoop::AllEvents);
QThread::currentThread()->usleep(100);
}
}
QString getAbsoluteFileName(const QString &path,const QString fileName){
QString myPath = createDirWithName(path);
if(myPath.isEmpty())
return "";
#ifdef Q_OS_WIN32
return myPath + "\\" +fileName;
#else
return myPath + "/" + fileName;
#endif
}
QString createDirWithName(const QString &dir_name){
//QDir默认构造为当前路径,当创建是以当前路径为开始创建的
//macos的运行方式和windows是有区别的。
#ifdef Q_OS_WIN32
QDir dir = QDir::currentPath() + "\\" +dir_name;
QStringList list = dir.absolutePath().split("\\");
QString mid = "\\";
#else
QDir dir = QDir::currentPath() + "/" +dir_name;
QStringList list = dir.absolutePath().split("/");
QString mid = "/";
#endif
if(dir.exists()){
return dir.absolutePath();
}
QString path;
for(QStringList::const_iterator it = list.begin(); it != list.end(); ++it){
path += *it;
path += mid;
if(!dir.exists(path))
if(!dir.mkdir(path)){
showMessagebox("错误","创建文件夹失败"+dir.absolutePath(),QMessageBox::Critical);
return "";
}
}
return dir.absolutePath();
}
bool downFile(const QString &url,const QString &absolutePathAndName){
QFile file(absolutePathAndName);
if(file.exists()){
return true;
} else {
if(!file.open(QIODevice::WriteOnly)){
return false;
}else{
QNetworkAccessManager manager;
QByteArray result = gAccessResult(&manager,url);
file.write(result);
file.close();
return true;
}
}
}
QString hmacSha1(QByteArray key, QByteArray baseString){
int blockSize = 64; // HMAC-SHA-1 block size, defined in SHA-1 standard
if (key.length() > blockSize) { // if key is longer than block size (64), reduce key length with SHA-1 compression
key = QCryptographicHash::hash(key, QCryptographicHash::Sha1);
}
QByteArray innerPadding(blockSize, char(0x36)); // initialize inner padding with char "6"
QByteArray outerPadding(blockSize, char(0x5c)); // initialize outer padding with char "quot;
for (int i = 0; i < key.length(); i++) {
innerPadding[i] = innerPadding[i] ^ key.at(i); // XOR operation between every byte in key and innerpadding, of key length
outerPadding[i] = outerPadding[i] ^ key.at(i); // XOR operation between every byte in key and outerpadding, of key length
}
QByteArray total = outerPadding;
QByteArray part = innerPadding;
part.append(baseString);
total.append(QCryptographicHash::hash(part, QCryptographicHash::Sha1));
QByteArray hashed = QCryptographicHash::hash(total, QCryptographicHash::Sha1);
return hashed.toBase64();
}
QString getHashMd5(const QByteArray &data)
{
QString md5;
QByteArray array = QCryptographicHash::hash(data,QCryptographicHash::Md5);
md5 = QString(array.toHex());
return md5;
}
QString getHashMd5(const QString &filePath){
QString md5;
QFile file(filePath);
if(file.open(QIODevice::ReadOnly)){
return getHashMd5(file.readAll());//file为栈变量,函数结束自动关闭
}
file.close();
return md5;
}
bool assumeSingleInstance(const char* program){
static QSharedMemory shm(program);
if(shm.create(2) == false){
return true;
}
return false;
}
/*
* 参数:@path:根路径 @isLink:是否统计快捷方式
* 返回<字节总数、文件总数、目录总数>
*/
QStringList calc_ByteCount_FileCount_DirCount(const QString &path,bool isLink)
{
QList<QString> paths;
long long sum = 0;
long long dirs = 0;
long long files = 0;
QSet<QString> links;/* 防止循环引用导致的统计错误 */
paths << path;
while (paths.size() > 0) {
QDir dir(paths.first());
if (isLink) {
dir.setFilter(QDir::NoDotAndDotDot | QDir::Hidden | QDir::AllDirs | QDir::Files);
} else {
dir.setFilter(QDir::NoDotAndDotDot | QDir::Hidden | QDir::AllDirs | QDir::Files | QDir::NoSymLinks);
}
QFileInfoList list = dir.entryInfoList();
for (int i = 0;i < list.size(); ++i) {
QFileInfo fileInfo = list.at(i);
if (fileInfo.isDir()) {
if (isLink) {
if (fileInfo.suffix() == "lnk") {
if (links.contains(fileInfo.canonicalFilePath())) {
continue;
} else {
links.insert(fileInfo.canonicalFilePath());
++dirs;
paths << fileInfo.absoluteFilePath();
}
} else {
paths << fileInfo.absoluteFilePath();
++dirs;
}
} else {
paths << fileInfo.absoluteFilePath();
++dirs;
}
} else {
sum += fileInfo.size();
++files;
}
}
paths.removeFirst();
}
QStringList list;
list << QString::number(sum) << QString::number(files) << QString::number(dirs);
return list;
}
bool createHideDir(const QString &path)
{
QDir dir(path);
bool flag = false;
if (!dir.exists())
flag = dir.mkdir(path);
#ifdef Q_OS_WIN
flag = SetFileAttributes((LPCWSTR)path.unicode(),FILE_ATTRIBUTE_HIDDEN);
#endif
return flag;
}
bool createDirLink(const QString &path,QString dstFullPath)
{
#ifdef Q_OS_WIN32
if (!dstFullPath.endsWith(".lnk"))
dstFullPath += ".lnk";
#endif
return QFile::link(path,dstFullPath);
}
/*
* 注:查找包含文件夹的快捷方式,返回真实路径
* TODO 优化,这个可以使用多线程来进行优化,如果文件特别多,查找非常耗时
*/
QStringList findFile(const QString &path,const QString &fileName)
{
QStringList ret;
QList<QString> paths;
paths << path;
QSet<QString> links;/* 防止循环引用导致的统计错误 */
while (paths.size() > 0) {
QDir dir(paths.first());
dir.setFilter(QDir::NoDotAndDotDot | QDir::Hidden | QDir::AllDirs | QDir::Files);
QFileInfoList list = dir.entryInfoList();
for (int i = 0;i < list.size(); ++i) {
QFileInfo fileInfo = list.at(i);
if (fileInfo.isDir()) {
if (fileInfo.suffix() == "lnk") {
if (links.contains(fileInfo.canonicalFilePath())) {
continue;
} else {
links.insert(fileInfo.canonicalFilePath());
paths << fileInfo.absoluteFilePath();
}
} else {
paths << fileInfo.absoluteFilePath();
}
} else {
if (fileInfo.fileName() == fileName) {
ret << fileInfo.canonicalFilePath();
}
}
}
paths.removeFirst();
}
return ret;
}
C++
1
https://gitee.com/zengfanbin/base.git
git@gitee.com:zengfanbin/base.git
zengfanbin
base
qtbase
master

搜索帮助

53164aa7 5694891 3bd8fe86 5694891