-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathutil.cpp
More file actions
512 lines (425 loc) · 15.2 KB
/
util.cpp
File metadata and controls
512 lines (425 loc) · 15.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
#include "util.h"
#include "qdebug.h"
#include "qeventloop.h"
#include "qnetworkreply.h"
#include "qtcpsocket.h"
#include <sstream>
#include <QProcess>
#include <QFile>
#include <QTextStream>
#include <QTcpSocket>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QVector>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QUrl>
#include <QHttpMultiPart>
#include <QObject>
#include <QCoreApplication>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QRegularExpression>
#include <QRegularExpressionMatchIterator>
#include <QDebug>
#include <QEventLoop>
Util::Util()
{
}
QVector<QString> Util::removeDupWord(std::string str)
{
QVector<QString> words;
// Used to split string around spaces.
std::istringstream ss(str);
std::string word; // for storing each word
// Traverse through all wordsF
// while loop till we get
// strings to store in string word
while (ss >> word)
{
// print the read word
words.push_back(word.c_str());
}
return words;
}
QStringList Util::getAllImageSrc(const QString &url, const QString &gameName) {
QNetworkAccessManager manager;
QNetworkRequest request((QUrl(url)));
// Sending the GET request
QNetworkReply *reply = manager.get(request);
// Event loop to wait for the request to finish
QEventLoop loop;
QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
loop.exec();
// Check for errors
if (reply->error() != QNetworkReply::NoError) {
qDebug() << "Error fetching the URL:" << reply->errorString();
reply->deleteLater();
return {}; // Return an empty list on error
}
// Read the response data (HTML content)
QByteArray responseData = reply->readAll();
QString htmlContent = QString::fromUtf8(responseData);
// Regular expression to match the 'src' attribute of all <img> tags
// Construct the regular expression string with the gameName included
QString pattern = QString(R"(<img[^>]*\s+src\s*=\s*['\"]([^'\"]*%1[^'\"]+)['\"])").arg(gameName);
// Create the regular expression with the pattern
QRegularExpression regex(pattern, QRegularExpression::CaseInsensitiveOption);
QRegularExpressionMatchIterator i = regex.globalMatch(htmlContent);
// List to store all image src URLs
QStringList imageSrcList;
while (i.hasNext()) {
QRegularExpressionMatch match = i.next();
imageSrcList.append(match.captured(1)); // Add captured src URL to list
}
reply->deleteLater(); // Clean up the network reply object
return imageSrcList;
}
// Converts secons to hours and minutes
QString Util::secondsToTime(int time)
{
int h = time / 3600;
int m = time % 3600 / 60;
QString hours = QString::number(h);
QString minutes = QString::number(m);
return hours + "h " + minutes + "m";
}
// Finds game exe name (game.exe)
QString Util::findLastBackSlashWord(std::string path)
{
auto const pos = path.find_last_of("\\");
const auto leaf = path.substr(pos + 1);
return leaf.c_str();
}
// Removes last back slash
QString Util::removeDataFromLasBackSlash(QString filePath)
{
// Find the index of the last backslash
int lastIndex = filePath.lastIndexOf("\\");
if (lastIndex != -1)
{
// Extract the part of the string before the last backslash
QString newPath = filePath.left(lastIndex + 1);
return newPath;
}
return "Error";
}
// Creates .bat file containing game exe location
bool Util::createCronoRunnerBatFile(QString gameExePath, QString gameExe)
{
// Specify the file name/path
QString fileName = "crono_runner.bat";
// Create a QFile instance
QFile file(fileName);
// Open the file in write mode
if (file.open(QIODevice::WriteOnly | QIODevice::Text))
{
// Create a QTextStream to write to the file
QTextStream out(&file);
// Write text to the file
/*out << "start /d "
"\""
<< gameExePath << "\" " << gameExe << Qt::endl;*/
out << "start "
<< "\""
"\""
<< " /d "
"\""
<< gameExePath << "\" "
<< "\"" << gameExe << "\"" << Qt::endl;
// Close the file
file.close();
return true;
}
else
{
// Handle error if the file couldn't be opened
qDebug() << "Failed to open the file for writing.";
return false;
}
}
// Check if game is running
bool Util::isProcessRunning(const QString &processName)
{
QProcess process;
#ifdef Q_OS_WIN
process.start("tasklist");
#else
process.start("ps", QStringList() << "aux");
#endif
process.waitForFinished();
QByteArray output = process.readAllStandardOutput();
QString outputStr = QString::fromLocal8Bit(output);
process.deleteLater();
return outputStr.contains(processName, Qt::CaseInsensitive);
}
size_t Util::writeCallback(char *contents, size_t size, size_t nmemb, void *userp)
{
((std::string *)userp)->append((char *)contents, size * nmemb);
return size * nmemb;
}
size_t WriteCall(char *contents, size_t size, size_t nmemb, void *userp)
{
((std::string *)userp)->append((char *)contents, size * nmemb);
return size * nmemb;
}
// Checks internet connection making a ping to google.com
bool Util::checkInternetConn()
{
QTcpSocket *sock = new QTcpSocket();
sock->connectToHost("www.google.com", 80);
bool connected = sock->waitForConnected(30000); // ms
if (!connected)
{
sock->abort();
return false;
}
sock->close();
return true;
}
QString Util::getGameImage(QString gameName)
{
// Convert the input string to a QString
QString inputStr = QString::fromStdString(gameName.toStdString());
// Split the string into words based on spaces
QStringList words = inputStr.split(" ");
qDebug() << gameName.replace(' ', '+');
// URL to fetch
// https://store.steampowered.com/search/?snr=1_4_4__12&term=
//https://www.skidrowreloaded.com/?s=
// fetch skydrowreloaded web to get game image if found
//QString url = "https://www.skidrowreloaded.com/?s=" + gameName.replace(' ', '+');
// Get all image srcs
//QStringList imageSrcList = Util::getAllImageSrc(url,words[0]);
// Print out all image sources
/*if (!imageSrcList.isEmpty()) {
qDebug() << "Found" << imageSrcList.count() << "images:";
for (const QString &src : imageSrcList) {
qDebug() << src;
}
return imageSrcList[0];
} else {
qDebug() << "No images found or error fetching the page.";
return "";
}*/
/*QVector<QString> splitWords = Util::removeDupWord(gameName.toStdString());
// Build a JSON array of search terms
QJsonArray searchTermsArray;
for (const QString &word : splitWords)
{
searchTermsArray.append(word);
}
QJsonObject searchObject;
searchObject["searchType"] = "games";
searchObject["searchTerms"] = searchTermsArray;
searchObject["searchPage"] = 1;
searchObject["size"] = 20;
QJsonObject searchOptionsObject;
QJsonObject gamesObject;
gamesObject["userId"] = 0;
gamesObject["platform"] = "";
gamesObject["sortCategory"] = "popular";
gamesObject["rangeCategory"] = "main";
QJsonObject rangeTimeObject;
rangeTimeObject["min"] = 0;
rangeTimeObject["max"] = 0;
gamesObject["rangeTime"] = rangeTimeObject;
QJsonObject gameplayObject;
gameplayObject["perspective"] = "";
gameplayObject["flow"] = "";
gameplayObject["genre"] = "";
gamesObject["gameplay"] = gameplayObject;
gamesObject["modifier"] = "";
searchOptionsObject["games"] = gamesObject;
QJsonObject usersObject;
usersObject["sortCategory"] = "postcount";
searchOptionsObject["users"] = usersObject;
searchObject["searchOptions"] = searchOptionsObject;
searchObject["filter"] = "";
searchObject["sort"] = 0;
searchObject["randomizer"] = 0;
QJsonDocument jsonDocument(searchObject);
QString jsonstr = QString(jsonDocument.toJson(QJsonDocument::Compact));
QNetworkAccessManager manager;
QNetworkRequest request(QUrl("https://howlongtobeat.com/api/s/5b26492381a39f40"));
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
//request.setRawHeader("Accept", "*");
request.setRawHeader("Origin", "https://howlongtobeat.com");
request.setRawHeader("Referer", "https://howlongtobeat.com");
request.setRawHeader("User-Agent", "Mozilla/4.0 (Windows 7 6.1) Java/1.7.0_51");
QByteArray postData = jsonstr.toUtf8();
QNetworkReply *reply = manager.post(request, postData);
QEventLoop loop;
connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
QString imageUrl = "";
if (reply->error() == QNetworkReply::NoError)
{
QByteArray responseData = reply->readAll();
QJsonDocument jsonResponse = QJsonDocument::fromJson(responseData);
QJsonArray jsonArray = jsonResponse["data"].toArray();
if (jsonArray.count() > 0)
{
imageUrl = "https://howlongtobeat.com/games/" + jsonArray[0].toObject()["game_image"].toString();
}
}
else
{
qDebug() << "Error: " << reply->errorString();
qDebug() << "Response: " << reply->readAll();
}
reply->deleteLater();
return imageUrl;*/
QNetworkAccessManager manager;
QNetworkRequest request(QUrl("https://www.steamgriddb.com/api/public/search/main/games"));
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
request.setRawHeader("Origin", "https://www.steamgriddb.com");
request.setRawHeader("Referer", "https://www.steamgriddb.com");
request.setRawHeader("User-Agent", "Mozilla/4.0 (Windows 7 6.1) Java/1.7.0_51");
// Construct JSON body
QJsonObject filters;
filters["styles"] = QJsonArray{"all"};
filters["dimensions"] = QJsonArray{"all"};
filters["type"] = QJsonArray{"all"};
filters["order"] = "score_desc";
QJsonObject mainObj;
mainObj["asset_type"] = "grid";
mainObj["term"] = inputStr;
mainObj["offset"] = 0;
mainObj["filters"] = filters;
// Convert JSON to QByteArray
QJsonDocument jsonDoc(mainObj);
QByteArray postData = jsonDoc.toJson();
QNetworkReply *reply = manager.post(request, postData);
QEventLoop loop;
QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
loop.exec();
QString imageUrl = "";
if (reply->error() == QNetworkReply::NoError)
{
QByteArray responseData = reply->readAll();
QJsonDocument jsonResponse = QJsonDocument::fromJson(responseData);
QJsonObject rootObj = jsonResponse.object();
QJsonObject dataObj = rootObj["data"].toObject();
QJsonArray gamesArray = dataObj["games"].toArray();
if (!gamesArray.isEmpty())
{
QJsonObject firstGame = gamesArray[0].toObject();
QJsonArray assetsArray = firstGame["assets"].toArray();
if (!assetsArray.isEmpty())
{
QJsonObject firstAsset = assetsArray[0].toObject();
imageUrl = firstAsset["url"].toString();
}
}
}
else
{
qDebug() << "Error: " << reply->errorString();
qDebug() << "Response: " << reply->readAll();
}
reply->deleteLater();
return imageUrl;
}
QString Util::dayNumberToWeekDay(int day)
{
switch (day)
{
case 0:
return "SUNDAY";
break;
case 1:
return "MONDAY";
break;
case 2:
return "TUESDAY";
break;
case 3:
return "WEDNESDAY";
break;
case 4:
return "THURSDAY";
break;
case 5:
return "FRIDAY";
break;
case 6:
return "SATURDAY";
break;
default:
return "NO DAY";
break;
}
}
/*QString Util::getGameImage(QString gameName)
{
QVector<QString> splitWords = Util::removeDupWord(gameName.toStdString());
// build a string by sequentially adding data to it.
std::stringstream ss;
for (int i = 0; i < splitWords.size(); ++i)
{
if (i > 0)
{
ss << ", ";
}
ss << "\"" << splitWords[i].toStdString() << "\""; // Include the " symbols around each element
}
std::string searchTerms = ss.str();
// qDebug() << splitWords.data()->toStdString();
// ui->lineEdit->text().toStdString()
CURL *curl;
CURLcode res;
struct curl_slist *header;
std::string readBuffer;
std::string jsonstr = "{\"searchType\": \"games\",\"searchTerms\": [" + searchTerms + "],\"searchPage\": 1,\"size\": 20,\"searchOptions\": { \"games\": {\"userId\": 0,\"platform\": \"\",\"sortCategory\": \"popular\",\"rangeCategory\": \"main\",\"rangeTime\": { \"min\": 0, \"max\": 0},\"gameplay\": { \"perspective\": \"\", \"flow\": \"\", \"genre\": \"\"},\"modifier\": \"\" }, \"users\": {\"sortCategory\": \"postcount\" }, \"filter\": \"\", \"sort\": 0, \"randomizer\": 0} }";
// qDebug() << jsonstr;
// In windows, this will init the winsock stuff
curl_global_init(CURL_GLOBAL_ALL);
// get a curl handle
curl = curl_easy_init();
if (curl)
{
header = NULL;
header = curl_slist_append(header, "Content-Type: application/json");
header = curl_slist_append(header, "Accept: **");
header = curl_slist_append(header, "Origin: https://howlongtobeat.com");
header = curl_slist_append(header, "Referer: https://howlongtobeat.com");
header = curl_slist_append(header, "User-Agent: Mozilla/4.0 (Windows 7 6.1) Java/1.7.0_51");
// First set the URL that is about to receive our POST. This URL can
//just as well be an https:// URL if that is what should receive the
// data.
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_easy_setopt(curl, CURLOPT_URL, "https://www.howlongtobeat.com/api/search");
// Now specify the POST data
// curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, jsonstr.c_str());
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, jsonstr.length());
curl_easy_setopt(curl, CURLOPT_POST, 1);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCall);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
// Perform the request, res will get the return code
res = curl_easy_perform(curl);
// Check for errors
if (res == CURLE_OK)
qDebug() << "Good";
else
qDebug() << curl_easy_strerror((CURLcode)res);
// always cleanup
curl_easy_cleanup(curl);
}
curl_global_cleanup();
// Parse JSON object
QJsonDocument jsonResponse = QJsonDocument::fromJson(readBuffer.c_str());
QString imageUrl = "";
QJsonArray jsonArray = jsonResponse["data"].toArray();
// Check if theres data
if (jsonResponse["data"].toArray().count() > 0)
{
imageUrl = "https://howlongtobeat.com/games/" + jsonArray[0].toObject()["game_image"].toString();
}
return imageUrl;
}*/