-
Notifications
You must be signed in to change notification settings - Fork 15
/
mainwindow.cpp
executable file
·2593 lines (2064 loc) · 98.2 KB
/
mainwindow.cpp
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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
*
Copyright (C) 2017-2019 Fábio Bento (fabiobento512)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "about.h"
#include "preferences.h"
#include "utilfrequest.h"
#include "Widgets/frequesttreewidgetprojectitem.h"
#include "HttpRequests/posthttprequest.h"
#include "HttpRequests/puthttprequest.h"
#include "HttpRequests/gethttprequest.h"
#include "HttpRequests/deletehttprequest.h"
#include "HttpRequests/patchhttprequest.h"
#include "HttpRequests/headhttprequest.h"
#include "HttpRequests/tracehttprequest.h"
#include "HttpRequests/optionshttprequest.h"
#include "XmlParsers/configfilefrequest.h"
#include <QNetworkAccessManager>
#include <QTreeWidgetItem>
#include <QStringBuilder>
#include <QUrlQuery>
#include <QScreen>
#include <QUrl>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QTimer>
#include <QClipboard>
#include <QUuid>
#include <QPainter>
#include <QMap>
#include <QStyleFactory>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
operatingSystemDefaultStyle(QApplication::style()->objectName())
{
// We use this appender because it is the native way to have \r\n in windows in plog library
// example: https://github.com/SergiusTheBest/plog/blob/master/samples/NativeEOL/Main.cpp
static plog::RollingFileAppender<plog::TxtFormatter, plog::NativeEOLConverter<>> fileAppender
(QSTR_TO_TEMPORARY_CSTR(Util::FileSystem::getAppPath() + "/" + GlobalVars::AppLogFileName), 1024*5 /* 5 Mb max log size */, 3);
plog::init(plog::info, &fileAppender);
this->currentSettings = this->configFileManager.getCurrentSettings();
this->ignoreAnyChangesToProject.SetCondition();
ui->setupUi(this);
// We aren't using this yet, so close it
ui->mainToolBar->close();
// show request types icons or not?
ui->actionShow_Request_Types_Icons->setChecked(this->currentSettings.showRequestTypesIcons);
// Disable drop of items outside of the project folder
// Thanks to "p.i.g.": http://stackoverflow.com/a/30580654
ui->treeWidget->invisibleRootItem()->setFlags(
ui->treeWidget->invisibleRootItem()->flags() ^ Qt::ItemIsDropEnabled
);
// Set max icon size in tree widget
ui->treeWidget->setIconSize(QSize(48,16));
setNewProject();
// Set our desired proportion for the projects tree widget and remaining interface
// this->width() expands the second widget as much as possible
ui->splitter->setSizes(QList<int>() << ui->treeWidget->minimumWidth() << this->width());
setTheme();
#ifdef Q_OS_MAC
ui->pbSendRequest->setToolTip(ui->pbSendRequest->toolTip() + " (⌘ + Enter)");
#else
ui->pbSendRequest->setToolTip(ui->pbSendRequest->toolTip() + " (Ctrl + Enter)");
#endif
loadRecentProjects();
// Hide response warning messages and icons for now
ui->lbResponseBodyWarningIcon->hide();
ui->lbResponseBodyWarningMessage->hide();
ui->lbResponseBodyWarningIcon->setMaximumSize(0,0);
ui->lbResponseBodyWarningMessage->setMaximumSize(0,0);
// Hide key value table for now (the raw textedit is displayed by default)
ui->twRequestBodyKeyValue->setMaximumSize(0,0);
ui->tbRequestBodyKeyValueAdd->setMaximumSize(0,0);
ui->tbRequestBodyFile->setMaximumSize(0,0);
ui->tbRequestBodyKeyValueRemove->setMaximumSize(0,0);
ui->twRequestBodyKeyValue->hide();
ui->tbRequestBodyKeyValueAdd->hide();
ui->tbRequestBodyFile->hide();
ui->tbRequestBodyKeyValueRemove->hide();
// We will also set their size to the normal size (we start with size 0 so vertical splitter divide the area in equal space (for header and response), kinda hacky)
ui->twRequestBodyKeyValue->setMaximumSize(this->auxMaximumSize);
ui->tbRequestBodyKeyValueAdd->setMaximumSize(this->auxMaximumSize);
ui->tbRequestBodyFile->setMaximumSize(this->auxMaximumSize);
ui->tbRequestBodyKeyValueRemove->setMaximumSize(this->auxMaximumSize);
ui->lbResponseBodyWarningIcon->setMaximumSize(16, 16);
ui->lbResponseBodyWarningMessage->setMaximumSize(this->auxMaximumSize);
// Scretch middle column (value one) for form key value request body
QHeaderView *twRequestBodyKeyValueHeaderView = ui->twRequestBodyKeyValue->horizontalHeader();
twRequestBodyKeyValueHeaderView->setSectionResizeMode(1, QHeaderView::Stretch);
// Progress indicator and abort button (for the request being made)
this->pbRequestProgress.setTextVisible(false); //hides text
this->pbRequestProgress.setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Fixed);
this->pbRequestProgress.setMinimumWidth(150);
this->pbRequestProgress.setMaximum(0);
ui->statusBar->addWidget(&this->lbProjectInfo);
ui->statusBar->addPermanentWidget(&this->lbRequestInfo);
ui->statusBar->addPermanentWidget(&this->pbRequestProgress); //this adds automatically in right
this->tbAbortRequest.setIcon(QIcon(":/icons/abort.png"));
this->tbAbortRequest.setAutoRaise(true);
this->tbAbortRequest.setToolTip("Abort current request");
connect(&this->tbAbortRequest , SIGNAL (clicked()), this, SLOT(tbAbortRequest_clicked())); // connect button click to our slot function
connect(&this->networkAccessManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));
connect(ui->treeWidget, SIGNAL(deleteKeyPressed()), this, SLOT(treeWidgetDeleteKeyPressed()));
ui->statusBar->addPermanentWidget(&this->tbAbortRequest);
this->lbRequestInfo.hide();
this->pbRequestProgress.hide();
this->tbAbortRequest.hide();
// Restore geometry if it exists
if(this->currentSettings.windowsGeometry.saveWindowsGeometryWhenExiting){
if(!this->currentSettings.windowsGeometry.mainWindow_MainWindowGeometry.isEmpty()){
if(!this->restoreGeometry(this->currentSettings.windowsGeometry.mainWindow_MainWindowGeometry)){
const QString errorMessage = "Couldn't restore saved main window geometry.";
Util::Dialogs::showError(errorMessage);
LOG_ERROR << errorMessage;
return;
}
if(!ui->splitter->restoreState(this->currentSettings.windowsGeometry.mainWindow_RequestsSplitterState)){
const QString errorMessage = "Couldn't restore saved requests splitter state.";
Util::Dialogs::showError(errorMessage);
LOG_ERROR << errorMessage;
return;
}
if(!ui->splitter_2->restoreState(this->currentSettings.windowsGeometry.mainWindow_RequestResponseSplitterState)){
const QString errorMessage = "Couldn't restore saved request response splitter state.";
Util::Dialogs::showError(errorMessage);
LOG_ERROR << errorMessage;
return;
}
}
}
else{
// center window if we are not restoring geometry
this->setGeometry(QStyle::alignedRect(Qt::LeftToRight,Qt::AlignCenter,this->size(),qApp->primaryScreen()->availableGeometry()));
}
ui->treeWidget->setFocus();
}
void MainWindow::showEvent(QShowEvent *e)
{
if(!this->applicationIsFullyLoaded)
{
// Apparently Qt doesn't contains a slot to when the application was fully load (mainwindow). So we do our own implementation instead.
connect(this, SIGNAL(signalAppIsLoaded()), this, SLOT(applicationHasLoaded()), Qt::ConnectionType::QueuedConnection);
emit signalAppIsLoaded();
}
e->accept();
}
// Called only when the MainWindow was fully loaded and painted on the screen. This slot is only called once.
void MainWindow::applicationHasLoaded(){
LOG_INFO << GlobalVars::AppName + " " + GlobalVars::AppVersion + " started";
this->applicationIsFullyLoaded = true;
this->ignoreAnyChangesToProject.UnsetCondition();
if(this->currentSettings.recentProjectsPaths.size() > 0){
const QString &lastSavedProject = this->currentSettings.recentProjectsPaths[0];
if(!lastSavedProject.isEmpty()){
if(this->currentSettings.onStartupSelectedOption == ConfigFileFRequest::OnStartupOption::LOAD_LAST_PROJECT){
loadProjectState(lastSavedProject);
}
else if(this->currentSettings.onStartupSelectedOption == ConfigFileFRequest::OnStartupOption::ASK_TO_LOAD_LAST_PROJECT){
if(Util::Dialogs::showQuestion(this,"Do you want to load latest project?\n\nLatest project was '" +
Util::FileSystem::cutNameWithoutBackSlash(lastSavedProject) + "'.")){
loadProjectState(lastSavedProject);
}
}
}
}
}
MainWindow::~MainWindow()
{
delete ui;
LOG_INFO << GlobalVars::AppName + " " + GlobalVars::AppVersion + " exited";
}
void MainWindow::on_pbSendRequest_clicked()
{
if(formKeyValueInBodyIsValid()){
QVector<UtilFRequest::HttpHeader> requestFinalHeaders = getRequestHeaders();
if(noDuplicatedKeyExistsInRequestHeaders(requestFinalHeaders)) {
// Disable until this request is finished
ui->pbSendRequest->setEnabled(false);
this->lbRequestInfo.show();
this->pbRequestProgress.show();
this->tbAbortRequest.show();
this->pbRequestProgress.setValue(0);
ui->gbProject->setEnabled(false);
ui->gbRequest->setEnabled(false);
// Apply proxy type
ProxySetup::setupProxyForNetworkManager(this->currentSettings, &this->networkAccessManager);
// Attempt to authenticate if we have authentication and its the first request in this project
if(this->currentProjectItem->authData != nullptr){
// We only apply the authentication to urls of the project, overriden urls don't have the auth applied
if(!ui->cbRequestOverrideMainUrl->isChecked()){
switch(this->currentProjectItem->authData->type){
case FRequestAuthentication::AuthenticationType::REQUEST_AUTHENTICATION:
{
if(!this->currentProjectAuthenticationWasMade)
{
this->lbRequestInfo.setText("Authenticating using the request provided...");
applyRequestAuthentication();
// If there was an error with the authorization don't proceed
if(!this->currentProjectAuthenticationWasMade){
return;
}
}
break;
}
case FRequestAuthentication::AuthenticationType::BASIC_AUTHENTICATION:
{
const RequestAuthentication * const concreteAuthData = static_cast<RequestAuthentication*>(this->currentProjectItem->authData.get());
UtilFRequest::HttpHeader authHeader;
authHeader.name = "Authorization";
authHeader.value = "Basic " + QString(concreteAuthData->username + ":" + concreteAuthData->password).toUtf8().toBase64();
requestFinalHeaders.append(authHeader);
break;
}
default:
{
const QString errorMessage = "Invalid authentication type " + QString::number(static_cast<int>(this->currentProjectItem->authData->type)) + "'. Program can't proceed.";
Util::Dialogs::showError(errorMessage);
LOG_FATAL << errorMessage;
exit(1);
}
}
}
}
// we always add the global headers, except in case that the user check the disable checkbox
// this is specially useful if we want to overwrite some existing header
if (!ui->cbDisableGlobalHeaders->isChecked()) {
for (const UtilFRequest::HttpHeader &currGlobalHeader : this->currentProjectItem->globalHeaders) {
// Check if there is already a local header with the same key of the current global variable
QVector<UtilFRequest::HttpHeader>::iterator itLocalHeader = std::find_if(requestFinalHeaders.begin(), requestFinalHeaders.end(),
[&currGlobalHeader](const UtilFRequest::HttpHeader &h){return h.name == currGlobalHeader.name;});
// It doesn't exist so we are free to add our global header (otherwise we prefer the local
// over the global as overriding mechanism)
if(itLocalHeader == requestFinalHeaders.end()) {
requestFinalHeaders.append(currGlobalHeader);
}
}
}
this->ignoreAnyChangesToProject.SetCondition();
formatRequestBody(getRequestCurrentSerializationFormatType());
this->ignoreAnyChangesToProject.UnsetCondition();
// Display info about when request was started
this->lbRequestInfo.setText("Requested started at " + QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
// Clear previous request data:
clearOlderResponse();
this->currentReply = processHttpRequest
(
UtilFRequest::getRequestTypeByString(ui->cbRequestType->currentText()),
ui->leFullPath->text(),
ui->cbBodyType->currentText(),
ui->pteRequestBody->toPlainText(),
requestFinalHeaders
);
lastStartTime = QDateTime::currentDateTime();
checkForQNetworkAccessManagerTimeout(this->currentReply.value());
}
}
}
void MainWindow::applyRequestAuthentication(){
std::shared_ptr<FRequestAuthentication> authData = this->currentProjectItem->authData;
if(authData->type != FRequestAuthentication::AuthenticationType::REQUEST_AUTHENTICATION)
{
const QString errorMessage = "Authentication is not a REQUEST_AUTHENTICATION. Please report this error.";
Util::Dialogs::showError(errorMessage);
LOG_ERROR << errorMessage;
return;
}
this->authenticationIsRunning = true;
const RequestAuthentication * const concreteAuthData = static_cast<RequestAuthentication*>(authData.get());
const FRequestTreeWidgetRequestItem * const authRequestItem =
this->currentProjectItem->getChildRequestByUuid(concreteAuthData->requestForAuthenticationUuid);
QString mainUrl;
if(authRequestItem->itemContent.bOverridesMainUrl){
mainUrl = authRequestItem->itemContent.overrideMainUrl;
}
else{
mainUrl = this->currentProjectItem->projectMainUrl;
}
// Wait for authentication request synchronously
// https://stackoverflow.com/a/5496468/1499019
QEventLoop loop;
connect(this, SIGNAL(signalRequestFinishedAndProcessed()), &loop, SLOT(quit()));
QVector<UtilFRequest::HttpHeader> finalAuthRequestHeaders = authRequestItem->itemContent.headers;
// Apply auth data to headers if it the placeholder fields are found
for(UtilFRequest::HttpHeader ¤tHeader : finalAuthRequestHeaders){
currentHeader.name = UtilFRequest::replaceFRequestAuthenticationPlaceholders(currentHeader.name, concreteAuthData->username, concreteAuthData->password);
currentHeader.value = UtilFRequest::replaceFRequestAuthenticationPlaceholders(currentHeader.value, concreteAuthData->username, concreteAuthData->password);
}
this->currentReply = processHttpRequest(
authRequestItem->itemContent.requestType,
getFullPathFromMainUrlAndPath(mainUrl, UtilFRequest::replaceFRequestAuthenticationPlaceholders(authRequestItem->itemContent.path, concreteAuthData->username, concreteAuthData->password)),
UtilFRequest::getBodyTypeString(authRequestItem->itemContent.bodyType),
UtilFRequest::replaceFRequestAuthenticationPlaceholders(authRequestItem->itemContent.body, concreteAuthData->username, concreteAuthData->password),
finalAuthRequestHeaders
);
// checkForQNetworkAccessManagerTimeout(this->currentReply.value()); // TODO: check why this is causing problems
loop.exec();
}
// Since QNetworkReply doesn't have a way to set a timeout we need implement it by ourselves
// http://stackoverflow.com/a/13229926
void MainWindow::checkForQNetworkAccessManagerTimeout(QNetworkReply *reply)
{
QTimer timer;
timer.setSingleShot(true);
QEventLoop loop;
connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
timer.start(this->currentSettings.requestTimeout * 1000);
loop.exec();
if(timer.isActive() || timer.interval() == 0) // if request timeout is 0 don't timeout
{
timer.stop();
}
else
{
// timeout
const QString errorMessage = "Timeout after " + QString::number(this->currentSettings.requestTimeout) + " seconds";
if(this->authenticationIsRunning){
Util::Dialogs::showError(errorMessage);
}
else{
ui->lbStatus->setText("-1");
ui->lbDescription->setText(errorMessage);
ui->lbTimeElapsed->setText(QString::number(lastStartTime.msecsTo(QDateTime::currentDateTime())) + " ms");
}
LOG_ERROR << errorMessage;
this->lastReplyStatusError = -1;
disconnect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
reply->abort();
}
}
void MainWindow::replyFinished(QNetworkReply *reply){
QString requestReturnCode;
QString requestReturnMessage;
bool isError = false;
bool isToRetryWithAuthentication = false;
// -1 means we have set a custom error, we don't want to override that one
if(this->lastReplyStatusError != -1 && reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).isValid()){ // success request
requestReturnCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toString();
requestReturnMessage = reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString();
}
else if(this->lastReplyStatusError == 0 && reply->error() != QNetworkReply::NoError){
requestReturnCode = "N/A";
requestReturnMessage = reply->errorString() + " - Error " + QString::number(reply->error());
isError = true;
}
// Don't override if we are authenticating or we have a custom error
if(!this->authenticationIsRunning && this->lastReplyStatusError != -1){
ui->lbStatus->setText(requestReturnCode);
ui->lbDescription->setText(requestReturnMessage);
ui->lbTimeElapsed->setText(QString::number(lastStartTime.msecsTo(QDateTime::currentDateTime())) + " ms");
}
if(reply->error() == QNetworkReply::OperationCanceledError){ /* ignore user aborted */ }
else{
if(!this->authenticationIsRunning){
// *1024 to get bytes...
const int maxBytesForBufferAndDisplay = this->currentSettings.maxRequestResponseDataSizeToDisplay*1024;
QString headersText;
QByteArray totalLoadedData;
QByteArray currentData;
// Read the bytes to display
totalLoadedData = reply->read(maxBytesForBufferAndDisplay);
for(const QNetworkReply::RawHeaderPair ¤tPair : reply->rawHeaderPairs()){
headersText += currentPair.first + ": " + currentPair.second + "\n";
}
ui->pteResponseHeaders->document()->setPlainText(headersText);
UtilFRequest::SerializationFormatType serializationType = UtilFRequest::getSerializationFormatTypeForString(totalLoadedData);
if(ui->actionFormat_Response_Body->isChecked()){
ui->pteResponseBody->document()->setPlainText(UtilFRequest::getStringFormattedForSerializationType(totalLoadedData, serializationType));
formatResponseBody(serializationType);
}
else{
ui->pteResponseBody->document()->setPlainText(totalLoadedData);
}
// Check if there are more bytes to read
// (they will not be displayed on the interface, but they can be saved to a file and a warning in the interface will be displayed)
currentData = reply->read(maxBytesForBufferAndDisplay);
if(currentData.size() > 0){
totalLoadedData.append(currentData);
ui->lbResponseBodyWarningIcon->show();
ui->lbResponseBodyWarningMessage->show();
ui->lbResponseBodyWarningMessage->setText("Return data size is greater than " +
QString::number(this->currentSettings.maxRequestResponseDataSizeToDisplay) + " KB, only displaying the first " +
QString::number(this->currentSettings.maxRequestResponseDataSizeToDisplay) + " KB.");
}
if(ui->cbDownloadResponseAsFile->isChecked())
{
downloadResponseAsFile(reply, totalLoadedData, currentData, maxBytesForBufferAndDisplay); // this call handles errors and status bar messages
}
else{
QString successMessage = "Request performed with success.";
if(this->currentProjectItem->authData != nullptr && ui->cbRequestOverrideMainUrl->isChecked()){
successMessage += " Since this was an url overriden request, the authentication was not applied.";
}
Util::StatusBar::showSuccess(ui->statusBar, successMessage);
}
}
else{
Util::StatusBar::showSuccess(ui->statusBar, "Authenticated with success.");
}
if(reply->error() != QNetworkReply::NoError){
// If we receive 401 and if we have an authentication and if we are allowed to retry to authenticate again, repeat the request
if
(
requestReturnCode == "401" && this->currentProjectItem->authData != nullptr &&
this->currentProjectItem->authData->retryLoginIfError401 &&
this->currentProjectItem->authData->type == FRequestAuthentication::AuthenticationType::REQUEST_AUTHENTICATION &&
this->currentProjectAuthenticationWasMade
){
isToRetryWithAuthentication = true;
}
if(!isToRetryWithAuthentication){
QString requestType;
bool overridenRequest = !this->authenticationIsRunning && this->currentProjectItem->authData != nullptr && ui->cbRequestOverrideMainUrl->isChecked();
if(this->authenticationIsRunning){
requestType = "Authentication";
}
else{
requestType = "Request";
}
LOG_ERROR << requestReturnMessage;
QString statusErrorMessage = requestType + " wasn't successful." +
(overridenRequest ? " Since this was an url overriden request, the authentication was not applied." : "");
Util::StatusBar::showError(ui->statusBar, statusErrorMessage); // this one is necessary to override any previous message
}
isError = true;
}
}
this->lbRequestInfo.hide();
this->pbRequestProgress.hide();
this->tbAbortRequest.hide();
ui->pbSendRequest->setEnabled(true);
ui->gbRequest->setEnabled(true);
ui->gbProject->setEnabled(true);
this->currentReply.reset();
reply->deleteLater();
if(this->authenticationIsRunning){
this->authenticationIsRunning = false;
if(!isError){
this->currentProjectAuthenticationWasMade = true;
}
}
emit signalRequestFinishedAndProcessed();
if(isToRetryWithAuthentication){
this->currentProjectAuthenticationWasMade = false;
on_pbSendRequest_clicked();
}
}
void MainWindow::downloadResponseAsFile(QNetworkReply *reply, QByteArray &totalLoadedData, QByteArray ¤tData, const int maxBytesForBufferAndDisplay){
QString filePath;
QString fileName;
if(ui->actionUse_Last_Download_Location->isChecked() && !this->lastResponseFileName.isEmpty())
{
fileName = this->lastResponseFileName;
filePath = this->currentSettings.lastResponseFilePath + "/" + this->lastResponseFileName;
}
else
{
fileName = getDownloadFileName(reply);
filePath = QFileDialog::getSaveFileName(this, tr("Save File"),
this->currentSettings.lastResponseFilePath + "/" + fileName);
}
if(!filePath.isEmpty())
{
this->currentSettings.lastResponseFilePath = Util::FileSystem::normalizePath(QFileInfo(filePath).absoluteDir().path());
this->lastResponseFileName = Util::FileSystem::cutNameWithoutBackSlash(Util::FileSystem::normalizePath(filePath));
QFile file(filePath);
if (file.open(QIODevice::WriteOnly)) {
file.write(totalLoadedData);
// Load remaining data using a buffer
do{
currentData = reply->read(maxBytesForBufferAndDisplay);
file.write(currentData);
}while(currentData.size() > 0);
file.close();
if(ui->actionOpen_file_after_download->isChecked()){
if(!QDesktopServices::openUrl("file:///"+filePath)){
const QString errorMessage = "Could not open downloaded file: " + filePath;
Util::Dialogs::showError(errorMessage);
LOG_ERROR << errorMessage;
Util::StatusBar::showError(ui->statusBar, errorMessage);
}
}
Util::StatusBar::showSuccess(ui->statusBar, "File saved with success.");
}
else{ // use just one exit point so we don't need to duplicate the code to enable the send request button
const QString errorMessage = "Could not open file for writing: " + filePath;
Util::Dialogs::showError(errorMessage);
Util::StatusBar::showSuccess(ui->statusBar, errorMessage);
LOG_ERROR << errorMessage;
}
}
}
void MainWindow::on_leRequestOverrideMainUrl_textChanged(const QString &)
{
setProjectHasChanged();
if(ui->cbRequestOverrideMainUrl->isChecked()){
buildFullPath();
}
}
void MainWindow::buildFullPath(){
QString normalizedMainUrl;
if(ui->cbRequestOverrideMainUrl->isChecked()){
normalizedMainUrl = ui->leRequestOverrideMainUrl->text();
}
else{
if(this->currentProjectItem != nullptr){
normalizedMainUrl = this->currentProjectItem->projectMainUrl;
}
}
ui->leFullPath->setText(getFullPathFromMainUrlAndPath(normalizedMainUrl, ui->lePath->text()));
}
QString MainWindow::getFullPathFromMainUrlAndPath(const QString & mainUrl, const QString & path){
QString normalizedMainUrl = mainUrl;
if(!normalizedMainUrl.endsWith('/') && !path.startsWith('/')){
normalizedMainUrl += '/';
}
return normalizedMainUrl + path;
}
void MainWindow::on_lePath_textChanged(const QString &)
{
setProjectHasChanged();
buildFullPath();
}
QNetworkReply* MainWindow::processHttpRequest
(
const UtilFRequest::RequestType requestType,
const QString &fullPath,
const QString &bodyType,
const QString &requestBody,
const QVector<UtilFRequest::HttpHeader>& requestHeaders
)
{
std::unique_ptr<HttpRequest> httpRequest = nullptr;
switch(requestType){
case UtilFRequest::RequestType::GET_OPTION:
{
httpRequest = std::make_unique<GetHttpRequest>(&this->networkAccessManager, fullPath, requestHeaders);
break;
}
case UtilFRequest::RequestType::POST_OPTION:
{
httpRequest = std::make_unique<PostHttpRequest>(&this->networkAccessManager, ui->twRequestBodyKeyValue, fullPath , bodyType, requestBody, requestHeaders);
break;
}
case UtilFRequest::RequestType::PUT_OPTION:
{
httpRequest = std::make_unique<PutHttpRequest>(&this->networkAccessManager, ui->twRequestBodyKeyValue, fullPath , bodyType, requestBody, requestHeaders);
break;
}
case UtilFRequest::RequestType::DELETE_OPTION:
{
httpRequest = std::make_unique<DeleteHttpRequest>(&this->networkAccessManager, fullPath, requestHeaders);
break;
}
case UtilFRequest::RequestType::PATCH_OPTION:
{
httpRequest = std::make_unique<PatchHttpRequest>(&this->networkAccessManager, ui->twRequestBodyKeyValue, fullPath , bodyType, requestBody, requestHeaders);
break;
}
case UtilFRequest::RequestType::HEAD_OPTION:
{
httpRequest = std::make_unique<HeadHttpRequest>(&this->networkAccessManager, fullPath, requestHeaders);
break;
}
case UtilFRequest::RequestType::TRACE_OPTION:
{
httpRequest = std::make_unique<TraceHttpRequest>(&this->networkAccessManager, ui->twRequestBodyKeyValue, fullPath , bodyType, requestBody, requestHeaders);
break;
}
case UtilFRequest::RequestType::OPTIONS_OPTION:
{
httpRequest = std::make_unique<OptionsHttpRequest>(&this->networkAccessManager, ui->twRequestBodyKeyValue, fullPath , bodyType, requestBody, requestHeaders);
break;
}
default:{
const QString errorMessage = "Request type unknown: '" + ui->cbRequestType->currentText() + "'. Application must exit.";
Util::Dialogs::showError(errorMessage);
LOG_FATAL << errorMessage;
exit(1);
}
}
return httpRequest->processRequest();
}
QString MainWindow::getDownloadFileName(const QNetworkReply * const reply)
{
QString fileFilename;
const QString contentDisposition = reply->rawHeader("Content-Disposition");
const QString stringToFind = "filename=";
int fileNameIndex = contentDisposition.indexOf(stringToFind) + stringToFind.size();
// If we have the filename in content disposition...
if(fileNameIndex != -1){
fileFilename = contentDisposition.mid(fileNameIndex); // assume the name is the remaining string after "filename="
fileFilename = fileFilename.replace("\"","").replace(";",""); // remove any " or ;
}
// use the url filename if content disposition is not available
if(fileFilename.isEmpty())
{
QString path = reply->url().path();
fileFilename = QFileInfo(path).fileName();
if (fileFilename.isEmpty())
fileFilename = "download";
}
return fileFilename;
}
void MainWindow::on_treeWidget_customContextMenuRequested(const QPoint &pos)
{
QTreeWidget *myTree = ui->treeWidget;
QList<int> selectedRows = QList<int>();
for(const QModelIndex &rowItem : myTree->selectionModel()->selectedRows()){
selectedRows << rowItem.row();
}
std::unique_ptr<QMenu> menu = std::make_unique<QMenu>();
// Project actions only
std::unique_ptr<QAction> openProjectLocation = nullptr;
std::unique_ptr<QAction> projectProperties = nullptr;
// Requests actions only
std::unique_ptr<QAction> cloneRequest = nullptr;
std::unique_ptr<QAction> moveRequestUp = nullptr;
std::unique_ptr<QAction> moveRequestDown = nullptr;
std::unique_ptr<QAction> deleteRequest = nullptr;
// Common actions
std::unique_ptr<QAction> addNewRequest = std::make_unique<QAction>("Add new request", myTree);
std::unique_ptr<QAction> renameItem = nullptr;
if(ui->treeWidget->currentItem() == this->currentProjectItem){ // Project
renameItem = std::make_unique<QAction>("Rename project", myTree);
openProjectLocation = std::make_unique<QAction>("Open project location", myTree);
menu->addAction(openProjectLocation.get());
menu->addSeparator();
menu->addAction(addNewRequest.get());
menu->addAction(renameItem.get());
menu->addSeparator();
projectProperties = std::make_unique<QAction>("Project properties", myTree);
menu->addAction(projectProperties.get());
}
else{ // Requests
renameItem = std::make_unique<QAction>("Rename request", myTree);
menu->addAction(addNewRequest.get());
menu->addAction(renameItem.get());
cloneRequest = std::make_unique<QAction>(QIcon(":/icons/clone_icon.png"), "Clone request", myTree);
menu->addAction(cloneRequest.get());
menu->addSeparator();
moveRequestUp = std::make_unique<QAction>("Move up", myTree);
menu->addAction(moveRequestUp.get());
moveRequestDown = std::make_unique<QAction>("Move down", myTree);
menu->addAction(moveRequestDown.get());
menu->addSeparator();
deleteRequest = std::make_unique<QAction>(QIcon(":/icons/delete_icon.png"), "Delete request", myTree);
menu->addAction(deleteRequest.get());
if(this->currentProjectItem->childCount() == 1){
moveRequestDown->setEnabled(false);
moveRequestUp->setEnabled(false);
}
else if(ui->treeWidget->itemAbove(ui->treeWidget->currentItem()) == this->currentProjectItem){
moveRequestUp->setEnabled(false);
}
else if(ui->treeWidget->itemBelow(ui->treeWidget->currentItem()) == nullptr){
moveRequestDown->setEnabled(false);
}
}
// Shortcuts info display for the users
#ifdef Q_OS_MAC
renameItem->setShortcut(Qt::Key_Return);
#else
renameItem->setShortcut(Qt::Key_F2);
#endif
renameItem->setShortcutVisibleInContextMenu(true);
if(deleteRequest != nullptr){
deleteRequest->setShortcut(Qt::Key_Delete);
deleteRequest->setShortcutVisibleInContextMenu(true);
}
// Disable show in explorer if we don't have any project saved to disk
if(openProjectLocation != nullptr && this->lastProjectFilePath.isEmpty()){
openProjectLocation->setEnabled(false);
}
QAction* selectedOption = menu->exec(myTree->viewport()->mapToGlobal(pos));
// if none selected just return
if(selectedOption == nullptr){
return;
}
// Index delta is the difference between the current index and the new one
auto fMoveQTreeWidgetItem = [](QTreeWidgetItem *item, int indexDelta){
// Based from here:
// http://www.qtcentre.org/threads/56247-Moving-QTreeWidgetItem-Up-and-Down-in-a-QTreeWidget
QTreeWidgetItem* parent = item->parent();
int index = parent->indexOfChild(item);
QTreeWidgetItem* child = parent->takeChild(index);
parent->insertChild(index+indexDelta, child);
item->treeWidget()->clearSelection();
item->setSelected(true);
item->treeWidget()->setCurrentItem(item);
};
if(selectedOption == addNewRequest.get()){
this->ignoreAnyChangesToProject.SetCondition();
this->unsavedChangesExist = true;
FRequestTreeWidgetItem *newRequest = addRequestItem("New Request", getNewUuid(), this->currentProjectItem);
ui->treeWidget->clearSelection();
newRequest->setSelected(true);
// Necessary in order to currentIndexChanged to work correctly (select it is not enough)
ui->treeWidget->setCurrentItem(newRequest);
// Reset options
clearRequestAndResponse();
ui->treeWidget->editItem(newRequest);
addGlobalHeaders();
if(this->currentSettings.defaultHeaders.useDefaultHeaders){
addDefaultHeaders();
}
this->ignoreAnyChangesToProject.UnsetCondition();
}
else if(selectedOption == renameItem.get()){
ui->treeWidget->editItem(ui->treeWidget->currentItem());
}
else if(selectedOption == cloneRequest.get()){
this->unsavedChangesExist = true;
const FRequestTreeWidgetRequestItem * const itemToClone = FRequestTreeWidgetRequestItem::fromQTreeWidgetItem(ui->treeWidget->currentItem());
FRequestTreeWidgetRequestItem *newRequest = addRequestItem(itemToClone->text(0), getNewUuid(), this->currentProjectItem);
ui->treeWidget->clearSelection();
newRequest->setSelected(true);
// Necessary in order to currentIndexChanged to work correctly (select it is not enough)
ui->treeWidget->setCurrentItem(newRequest);
this->currentItem = newRequest;
}
else if(openProjectLocation != nullptr && selectedOption == openProjectLocation.get()){
QDesktopServices::openUrl(QUrl("file:///" + QFileInfo(this->lastProjectFilePath).absoluteDir().absolutePath()));
}
else if(selectedOption == moveRequestUp.get()){
fMoveQTreeWidgetItem(ui->treeWidget->currentItem(), -1);
setProjectHasChanged();
}
else if(selectedOption == moveRequestDown.get()){
fMoveQTreeWidgetItem(ui->treeWidget->currentItem(), 1);
setProjectHasChanged();
}
else if(selectedOption == deleteRequest.get()){
removeRequest(FRequestTreeWidgetRequestItem::fromQTreeWidgetItem(ui->treeWidget->currentItem()));
}
else if(selectedOption == projectProperties.get()){
openProjectProperties();
}
}
// This signal is emitted when the current item changes.
// The current item is specified by current, and this replaces the previous current item.
void MainWindow::on_treeWidget_currentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *previous)
{
FRequestTreeWidgetItem* currentFRequestItem = nullptr;
FRequestTreeWidgetItem* previousFRequestItem = nullptr;
if(current != nullptr){
currentFRequestItem = FRequestTreeWidgetItem::fromQTreeWidgetItem(current);
// Add the icon if necessary
if(ui->actionShow_Request_Types_Icons->isChecked() && !currentFRequestItem->isProjectItem && currentFRequestItem->hasEmptyIcon()){
setIconForRequest(static_cast<FRequestTreeWidgetRequestItem*>(currentFRequestItem));
}
}
if(previous != nullptr){
previousFRequestItem = FRequestTreeWidgetItem::fromQTreeWidgetItem(previous);
}
// Save previous item
if(previousFRequestItem != nullptr && !previousFRequestItem->isProjectItem)
{
updateTreeWidgetItemContent(static_cast<FRequestTreeWidgetRequestItem*>(previousFRequestItem));
}
// Update window for new item
if(currentFRequestItem != nullptr){
if(!currentFRequestItem->isProjectItem){
this->currentItem = static_cast<FRequestTreeWidgetRequestItem*>(currentFRequestItem);
if(!this->ignoreAnyChangesToProject.ConditionIsSet()){
reloadRequest(this->currentItem);
}
// Hide project requests number if project item hasn't selected
if(!this->lbProjectInfo.text().isEmpty()){
this->lbProjectInfo.setText(QString());
}
}
else{
// If is the project display the number of requests that this has in status bar
const int projectRequestsNumber = this->currentProjectItem->childCount();
// Singular ? Plural ?
const QString requestText = projectRequestsNumber == 1 ? " request" : " requests";
this->lbProjectInfo.setText(this->currentProjectItem->projectName + " has a total of " + QString::number(projectRequestsNumber) + requestText);
}
updateWindowTitle();
}
}
// This signal is emitted when the contents of the column in the specified item changes.
void MainWindow::on_treeWidget_itemChanged(QTreeWidgetItem *item, int)
{
FRequestTreeWidgetItem *newItem = FRequestTreeWidgetItem::fromQTreeWidgetItem(item);
setProjectHasChanged();
bool updateInterface = false;
// Only necessary to create if the item exists (project requests are only created in on_treeWidget_currentItemChanged)
// If name had changed update the project requests
if(!newItem->isProjectItem){ // Request