Skip to content

Commit

Permalink
add a simple downloader with curl and qt
Browse files Browse the repository at this point in the history
  • Loading branch information
noisecode3 committed Jan 16, 2024
1 parent 631706a commit 318134f
Show file tree
Hide file tree
Showing 8 changed files with 263 additions and 175 deletions.
10 changes: 8 additions & 2 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,22 @@ set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_AUTOUIC ON)

find_package(Qt5 COMPONENTS Core Gui Widgets WebEngineWidgets Network Sql REQUIRED)
find_package(Qt5 COMPONENTS Core Gui Widgets WebEngineWidgets Sql REQUIRED)

set(CURL_LIBRARY "-lcurl")
find_package(CURL REQUIRED)

add_subdirectory(libs/quazip)

set(SOURCES
src/main.cpp
src/network.cpp
src/network.h
src/worker.h
src/controller.cpp
src/controller.h
src/fileop.h
src/fileop.cpp
src/TombRaiderLinuxLauncher.cpp
src/TombRaiderLinuxLauncher.h
src/TombRaiderLinuxLauncher.ui
Expand All @@ -29,9 +35,9 @@ target_link_libraries(${PROJECT_NAME}
Qt5::Gui
Qt5::Widgets
Qt5::WebEngineWidgets
Qt5::Network
Qt5::Sql
QuaZip
${CURL_LIBRARY}
)

target_include_directories(${PROJECT_NAME} PRIVATE ${CURL_INCLUDE_DIR} )
Expand Down
97 changes: 67 additions & 30 deletions src/TombRaiderLinuxLauncher.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

#include "ui_TombRaiderLinuxLauncher.h"


TombRaiderLinuxLauncher::TombRaiderLinuxLauncher(QWidget *parent)
:QMainWindow(parent),
poolData(QStandardPaths::writableLocation(QStandardPaths::HomeLocation)
Expand Down Expand Up @@ -122,7 +123,7 @@ void TombRaiderLinuxLauncher::checkCommonFiles()
generateList();
}
}
//TODO/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void TombRaiderLinuxLauncher::generateList()
{
ui->listWidgetModds->setIconSize(QSize(320, 240));
Expand Down Expand Up @@ -161,7 +162,7 @@ void TombRaiderLinuxLauncher::generateList()
ui->listWidgetModds->addItem(wi);
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void TombRaiderLinuxLauncher::readSavedSettings()
{
QString gamePathValue = settings.value("gamePath").toString();
Expand All @@ -186,7 +187,7 @@ void TombRaiderLinuxLauncher::setup()
ui->gamePathEdit->setText(homeDir + s);
ui->levelPathEdit->setText(homeDir + l);
}
//TODO////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void TombRaiderLinuxLauncher::onListItemSelected()
{
QString directoryPath = settings.value("levelPath").toString();
Expand All @@ -201,12 +202,15 @@ void TombRaiderLinuxLauncher::onListItemSelected()
QString id = selectedItem->data(Qt::UserRole).toString();
QString finalPath = directoryPath + "/" + id + ".TRLE";
QDir directory(finalPath);
if (directory.exists()) {
if (directory.exists())
{
qDebug() << "Directory exists.";
ui->pushButtonLink->setEnabled(true);
ui->pushButtonDownload->setEnabled(false);
ui->pushButtonInfo->setEnabled(false);
} else {
}
else
{
qDebug() << "Directory does not exist.";
ui->pushButtonLink->setEnabled(false);
ui->pushButtonDownload->setEnabled(true);
Expand All @@ -232,24 +236,10 @@ void TombRaiderLinuxLauncher::onListItemSelected()
ui->pushButtonDownload->setEnabled(false);
ui->pushButtonInfo->setEnabled(false);
}

}
/*
if (selectedItem->text() == "SomeCondition") {
ui->pushButtonLink->setEnabled(true);
ui->pushButtonInfo->setEnabled(true);
ui->pushButtonDownload->setEnabled(true);
}
else
{
ui->pushButtonLink->setEnabled(false);
ui->pushButtonInfo->setEnabled(false);
ui->pushButtonDownload->setEnabled(false);
}
*/
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void TombRaiderLinuxLauncher::setOptionsClicked()
{
QString gamePath = ui->gamePathEdit->text();
Expand All @@ -268,7 +258,7 @@ void TombRaiderLinuxLauncher::setOptionsClicked()

readSavedSettings();
}
//TODO///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void TombRaiderLinuxLauncher::linkClicked()
{
struct FolderNames folder;
Expand All @@ -282,36 +272,83 @@ void TombRaiderLinuxLauncher::linkClicked()
// Create a symbolic link
QString s = list.first()->text();
if (s == "Tomb Raider III Original")
{
s = "Original.TR3";
}
else if (s == "The Infada Cult\nby Jonson")
{
s = "1.TRLE";
}
const QString p = levelPath + "/" + s;
if (QFile::link(p, gamePath))
{
qDebug() << "Symbolic link created successfully.";
}
else
{
QFileInfo i(gamePath);
if (i.isSymLink())
QFileInfo i(gamePath);
if (i.isSymLink())
{
QFile::remove(gamePath);
if (QFile::link(p, gamePath))
{
QFile::remove(gamePath);
if (QFile::link(p, gamePath))
qDebug() << "Symbolic link created successfully.";
else
qDebug() << "Failed to create symbolic link.";
qDebug() << "Symbolic link created successfully.";
}
else
{
qDebug() << "Failed to create symbolic link.";
}
}
else
{
qDebug() << "Failed to create symbolic link.";
}
}
QApplication::quit();
QApplication::quit();
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void TombRaiderLinuxLauncher::downloadClicked()
{
struct FolderNames folder;
QString directoryPath = settings.value("levelPath").toString();
QListWidgetItem *selectedItem = ui->listWidgetModds->currentItem();

int retrievedIdentifier = selectedItem->data(Qt::UserRole).toInt();
if (retrievedIdentifier)
{
LevelData level = poolData.getData(retrievedIdentifier-1);
Downloader d;
//this should be in the pool
QUrl url("https://www.trle.net/levels/levels/2023/1123/Jonson-TheInfadaCult.zip");
QString path = directoryPath+"/"+level.zip.name;
QString levelDir = settings.value("levelPath").toString() + "/"+
QString::number(retrievedIdentifier)+".TRLE";
d.setUrl(url);
d.setSavePath(path);
d.run();
WorkerThread unpackLevel(1, false, path, levelDir);
unpackLevel.run();

if (ui->listWidgetModds->currentItem() == selectedItem)
{
ui->pushButtonLink->setEnabled(true);
ui->pushButtonDownload->setEnabled(false);
}
}
}

void TombRaiderLinuxLauncher::installTrle()
{
struct FolderNames folder;

WorkerThread unpackLevel(1, false, settings.value("gamePath").toString()
+ folder.TR3, settings.value("levelPath").toString() + "/" +"1"+".TRLE");
unpackLevel.run();

ui->pushButtonLink->setEnabled(true);
ui->pushButtonDownload->setEnabled(false);
}
TombRaiderLinuxLauncher::~TombRaiderLinuxLauncher()
{
delete ui;
Expand Down
5 changes: 5 additions & 0 deletions src/TombRaiderLinuxLauncher.h
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,11 @@ public slots:
*
*/
void onListItemSelected();
/**
*
*/
void installTrle();


private:
/**
Expand Down
75 changes: 75 additions & 0 deletions src/fileop.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
#include "fileop.h"
#include "quazip/quazip.h"
#include "quazip/quazipfile.h"

FileManager::FileManager(QObject *parent){}

const QString FileManager::calculateMD5(const QString& filename)
{
QFile file(filename);
if (!file.open(QIODevice::ReadOnly))
{
qDebug() << "Error opening file for reading: " << file.errorString();
return "";
}

QCryptographicHash md5(QCryptographicHash::Md5);

char buffer[1024];
qint64 bytesRead;

while ((bytesRead = file.read(buffer, sizeof(buffer))) > 0)
{
md5.addData(buffer, static_cast<int>(bytesRead));
}

file.close();
return QString(md5.result().toHex());
}
/**
*
*/
void FileManager::extractZip(const QString& zipFilename, const QString& extractPath)
{
QuaZip zip(zipFilename);
if (!zip.open(QuaZip::mdUnzip))
{
qDebug() << "Error opening ZIP file" << Qt::endl;
return;
}

QuaZipFileInfo info;
QuaZipFile file(&zip);

for (bool more = zip.goToFirstFile(); more; more = zip.goToNextFile())
{
if (zip.getCurrentFileInfo(&info) && file.open(QIODevice::ReadOnly))
{
QByteArray data = file.readAll();
file.close();

// Create directories if they don't exist
QString filePath = extractPath + QDir::separator() + info.name;
QString directory = filePath.left(filePath.lastIndexOf(QDir::separator()));

QDir().mkpath(directory);

// Create a new file on disk and write the data
QFile outFile(filePath);
if (outFile.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Unbuffered))
{
outFile.write(data);
outFile.close();
}
else if (!filePath.endsWith('/'))
{
qDebug() << "Error opening file for writing: " << filePath << Qt::endl;
}
}
else
{
qDebug() << "Error reading file info from ZIP archive" << Qt::endl;
}
}
zip.close();
}
21 changes: 21 additions & 0 deletions src/fileop.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#ifndef FILEOP_H
#define FILEOP_H

#include <QObject>
#include <QFile>
#include <QDir>
#include <QCryptographicHash>
#include <QDebug>

class FileManager : public QObject
{
Q_OBJECT
public:
explicit FileManager(QObject *parent = 0);
const QString calculateMD5(const QString& filename);
void extractZip(const QString& zipFilename, const QString& extractPath);

private:

};
#endif // FILEOP_H
59 changes: 59 additions & 0 deletions src/network.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
#include "network.h"

Downloader::Downloader(QObject *parent) :
QObject(parent){}

size_t write_callback(void* contents, size_t size, size_t nmemb, void* userp) {
size_t total_size = size * nmemb;
QByteArray* buffer = static_cast<QByteArray*>(userp);
buffer->append(static_cast<char*>(contents), total_size);
return total_size;
}
void Downloader::setUrl(QUrl url){ url_m=url; }
void Downloader::setSavePath(QString path){ path_m=path; }

void Downloader::saveToFile(const QByteArray& data, const QString& filePath) {
QFile file(filePath);
if (file.open(QIODevice::WriteOnly)) {
file.write(data);
file.close();
qDebug() << "Data saved to file:" << filePath;
} else {
qDebug() << "Error saving data to file:" << file.errorString();
}
}
void Downloader::run()
{
if (url_m.isEmpty()) {return;}
QString urlString = url_m.toString();
QByteArray byteArray = urlString.toUtf8();
const char* url_cstring = byteArray.constData();

if (path_m.isEmpty()) {return;}

// Initialize libcurl
curl_global_init(CURL_GLOBAL_DEFAULT);

// Initialize libcurl easy handle
CURL* curl = curl_easy_init();
if (curl) {
// Create a QByteArray to store the downloaded data
QByteArray data;

curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &data);
curl_easy_setopt(curl, CURLOPT_URL, url_cstring);

// Perform the download
CURLcode res = curl_easy_perform(curl);

if (res != CURLE_OK) {
qDebug() << "curl_easy_perform() failed:" << curl_easy_strerror(res);
} else {
qDebug() << "Downloaded successful\n";
saveToFile(data, path_m);
}
curl_easy_cleanup(curl);
}
curl_global_cleanup();
}
Loading

0 comments on commit 318134f

Please sign in to comment.