Repository: fabiobento512/FRequest Branch: master Commit: 22e98970b78f Files: 75 Total size: 427.2 KB Directory structure: gitextract_qtdfnj81/ ├── .github/ │ └── workflows/ │ └── build.yml ├── .gitignore ├── Authentications/ │ ├── basicauthentication.cpp │ ├── basicauthentication.h │ ├── frequestauthentication.cpp │ ├── frequestauthentication.h │ ├── requestauthentication.cpp │ └── requestauthentication.h ├── FRequest.pro ├── HttpRequests/ │ ├── deletehttprequest.cpp │ ├── deletehttprequest.h │ ├── gethttprequest.cpp │ ├── gethttprequest.h │ ├── headhttprequest.cpp │ ├── headhttprequest.h │ ├── httprequest.cpp │ ├── httprequest.h │ ├── httprequestwithmultipart.cpp │ ├── httprequestwithmultipart.h │ ├── optionshttprequest.cpp │ ├── optionshttprequest.h │ ├── patchhttprequest.cpp │ ├── patchhttprequest.h │ ├── posthttprequest.cpp │ ├── posthttprequest.h │ ├── puthttprequest.cpp │ ├── puthttprequest.h │ ├── tracehttprequest.cpp │ └── tracehttprequest.h ├── LICENSE ├── LinuxAppImageDeployment/ │ └── frequest.desktop ├── README.md ├── Resources/ │ ├── frequest_icon.icns │ ├── icon_resource.rc │ ├── macos_resources.qrc │ ├── plus_file.pdn │ └── resources.qrc ├── SyntaxHighlighters/ │ ├── frequestjsonhighlighter.cpp │ ├── frequestjsonhighlighter.h │ ├── frequestxmlhighlighter.cpp │ └── frequestxmlhighlighter.h ├── Widgets/ │ ├── frequesttreewidget.cpp │ ├── frequesttreewidget.h │ ├── frequesttreewidgetitem.cpp │ ├── frequesttreewidgetitem.h │ ├── frequesttreewidgetprojectitem.cpp │ ├── frequesttreewidgetprojectitem.h │ ├── frequesttreewidgetrequestitem.cpp │ └── frequesttreewidgetrequestitem.h ├── XmlParsers/ │ ├── configfilefrequest.cpp │ ├── configfilefrequest.h │ ├── projectfilefrequest.cpp │ └── projectfilefrequest.h ├── about.cpp ├── about.h ├── about.ui ├── credits.txt ├── main.cpp ├── mainwindow.cpp ├── mainwindow.h ├── mainwindow.ui ├── preferences.cpp ├── preferences.h ├── preferences.ui ├── projectproperties.cpp ├── projectproperties.h ├── projectproperties.ui ├── proxysetup.cpp ├── proxysetup.h ├── readme.txt ├── updatechecker.cpp ├── updatechecker.h ├── utilfrequest.cpp ├── utilfrequest.h └── utilglobalvars.h ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/workflows/build.yml ================================================ name: FRequest Build on: [push] jobs: Build-windows: runs-on: windows-2022 steps: - name: Check out FRequest code uses: actions/checkout@v3 with: path: 'FRequest' - name: Check out CommonLibs uses: actions/checkout@v3 with: repository: ${{ github.event.repository.owner.login }}/CommonLibs path: 'CommonLibs' - name: Check out CommonUtils uses: actions/checkout@v3 with: repository: ${{ github.event.repository.owner.login }}/CommonUtils path: 'CommonUtils' - name: Download Qt SDK and FRequest binaries run: | $files_url="https://github.com/${{ github.event.repository.owner.login }}/Files/releases/download" Invoke-WebRequest "$files_url/frequestwindows/Qt5.15.2.7z" -OutFile Qt5.15.2.7z Invoke-WebRequest "$files_url/frequestwindows/FRequestBinaries.7z" -OutFile FRequestBinaries.7z 7z.exe x -mmt=4 Qt5.15.2.7z -o"Qt5.15.2" 7z.exe x -mmt=4 FRequestBinaries.7z -o"FRequestBinaries" - name: Set Enviroments variables for SDK run: | # https://stackoverflow.com/a/64831469 echo "${{ github.workspace }}\Qt5.15.2\5.15.2\mingw81_32\bin" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append echo "${{ github.workspace }}\Qt5.15.2\Tools\mingw810_32\bin" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append - name: Compile code run: | mkdir output cd output qmake ../${{ github.event.repository.name }}/FRequest.pro "CONFIG+=release" mingw32-make -j cd .. - name: Copy executable / dependencies / readme / license to final folder run: | Invoke-WebRequest "https://github.com/${{ github.event.repository.owner.login }}/Files/releases/download/common/get_zip_name.py" -OutFile get_zip_name.py $zip_name=python3 get_zip_name.py ${{ github.event.repository.owner.login }} ${{ github.event.repository.name }} mkdir distributable mkdir distributable\FRequest cp output\release\FRequest.exe distributable\FRequest xcopy FRequestBinaries distributable\FRequest /e cp ${{ github.event.repository.name }}\readme.txt distributable\FRequest cp ${{ github.event.repository.name }}\LICENSE distributable\FRequest 7z a -tzip -mmt=4 "distributable\$zip_name.zip" "${{ github.workspace }}\distributable\FRequest" - name: Archive the final folder uses: actions/upload-artifact@v3 with: name: FRequest-windows path: distributable/*.zip Build-macos: runs-on: macos-10.15 steps: - name: Check out FRequest code uses: actions/checkout@v3 with: path: 'FRequest' - name: Check out CommonLibs uses: actions/checkout@v3 with: repository: ${{ github.event.repository.owner.login }}/CommonLibs path: 'CommonLibs' - name: Check out CommonUtils uses: actions/checkout@v3 with: repository: ${{ github.event.repository.owner.login }}/CommonUtils path: 'CommonUtils' - name: Install Qt uses: jurplel/install-qt-action@v2 with: version: 5.15.2 target: desktop modules: none # - name: Download and Install Qt SDK (alternative) # # https://superuser.com/a/422785 # run: | # brew install qt@5 # brew link qt@5 - name: Compile code run: | mkdir output cd output qmake ../${{ github.event.repository.name }}/FRequest.pro "CONFIG+=release" make -j cd .. - name: Copy app bundle / readme / license to final folder run: | wget "https://github.com/${{ github.event.repository.owner.login }}/Files/releases/download/common/get_zip_name.py" zip_name=$(python3 get_zip_name.py ${{ github.event.repository.owner.login }} ${{ github.event.repository.name }}) macdeployqt output/FRequest.app mkdir distributable mkdir distributable/FRequest cp -R output/FRequest.app distributable/FRequest cp ${{ github.event.repository.name }}/readme.txt distributable/FRequest cp ${{ github.event.repository.name }}/LICENSE distributable/FRequest 7z a -tzip -mmt=4 distributable/$zip_name.zip ${{ github.workspace }}/distributable/FRequest - name: Archive the final folder uses: actions/upload-artifact@v3 with: name: FRequest-macos path: distributable/*.zip Build-linux: runs-on: ubuntu-18.04 steps: - name: Check out FRequest code uses: actions/checkout@v3 with: path: 'FRequest' - name: Check out CommonLibs uses: actions/checkout@v3 with: repository: ${{ github.event.repository.owner.login }}/CommonLibs path: 'CommonLibs' - name: Check out CommonUtils uses: actions/checkout@v3 with: repository: ${{ github.event.repository.owner.login }}/CommonUtils path: 'CommonUtils' - name: Install Qt uses: jurplel/install-qt-action@v2 with: version: 5.15.2 target: desktop modules: none - name: Download and Set linuxdeployqt run: | wget https://github.com/probonopd/linuxdeployqt/releases/download/continuous/linuxdeployqt-continuous-x86_64.AppImage chmod a+x linuxdeployqt-continuous-x86_64.AppImage - name: Compile code run: | mkdir output cd output qmake ../${{ github.event.repository.name }}/FRequest.pro "CONFIG+=release" make -j cd .. - name: Generate AppImage run: | mkdir AppImage cp output/FRequest AppImage cp ${{ github.event.repository.name }}/LinuxAppImageDeployment/*.* AppImage cd AppImage ${{ github.workspace }}/linuxdeployqt-continuous-x86_64.AppImage frequest.desktop -no-translations -appimage cd .. - name: Copy AppImage / readme / license to final folder run: | wget "https://github.com/${{ github.event.repository.owner.login }}/Files/releases/download/common/get_zip_name.py" zip_name=$(python3 get_zip_name.py ${{ github.event.repository.owner.login }} ${{ github.event.repository.name }}) mkdir distributable mkdir distributable/FRequest cp ${{ github.event.repository.name }}/readme.txt distributable/FRequest cp ${{ github.event.repository.name }}/LICENSE distributable/FRequest cp AppImage/FRequest-x86_64.AppImage distributable/FRequest 7z a -tzip -mmt=4 distributable/$zip_name ${{ github.workspace }}/distributable/FRequest - name: Archive the final folder uses: actions/upload-artifact@v3 with: name: FRequest-linux path: distributable/*.zip ================================================ FILE: .gitignore ================================================ # ignore QtCreator user files *.pro.user* # ignore MacOS specific files *.DS_Store ================================================ FILE: Authentications/basicauthentication.cpp ================================================ /* * 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 . * */ #include "basicauthentication.h" BasicAuthentication::BasicAuthentication ( const bool saveAuthToConfigFile, const bool retryLoginIfError401, const QString &username, const QString &passwordSalt, const QString &password ) : FRequestAuthentication(saveAuthToConfigFile, retryLoginIfError401, AuthenticationType::BASIC_AUTHENTICATION), username(username), passwordSalt(passwordSalt), password(password) { } ================================================ FILE: Authentications/basicauthentication.h ================================================ /* * 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 . * */ #include "frequestauthentication.h" #ifndef BASICAUTHENTICATION_H #define BASICAUTHENTICATION_H class BasicAuthentication : public FRequestAuthentication { public: BasicAuthentication ( const bool saveAuthToConfigFile, const bool retryLoginIfError401, const QString &username, const QString &passwordSalt, const QString &password ); public: const QString username; const QString passwordSalt; const QString password; }; #endif // BASICAUTHENTICATION_H ================================================ FILE: Authentications/frequestauthentication.cpp ================================================ /* * 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 . * */ #include "frequestauthentication.h" FRequestAuthentication::FRequestAuthentication(const bool saveAuthToConfigFile, const bool retryLoginIfError401, const AuthenticationType type) :type(type), saveAuthToConfigFile(saveAuthToConfigFile), retryLoginIfError401(retryLoginIfError401) { } FRequestAuthentication::AuthenticationType FRequestAuthentication::getAuthenticationTypeByString(const QString ¤tAuthenticationTypeText){ if(currentAuthenticationTypeText == "Request Authentication"){ return AuthenticationType::REQUEST_AUTHENTICATION; } else if(currentAuthenticationTypeText == "Basic Authentication"){ return AuthenticationType::BASIC_AUTHENTICATION; } else{ QString errorMessage = "Authentication type unknown: '" + currentAuthenticationTypeText + "'. Program can't proceed."; Util::Dialogs::showError(errorMessage); LOG_FATAL << errorMessage; exit(1); } } QString FRequestAuthentication::getAuthenticationString(const AuthenticationType currentAuthType){ switch(currentAuthType){ case AuthenticationType::REQUEST_AUTHENTICATION: return "Request Authentication"; case AuthenticationType::BASIC_AUTHENTICATION: return "Basic Authentication"; default: { QString errorMessage = "Invalid authentication type " + QString::number(static_cast(currentAuthType)) + "'. Program can't proceed."; Util::Dialogs::showError(errorMessage); LOG_FATAL << errorMessage; exit(1); } } } ================================================ FILE: Authentications/frequestauthentication.h ================================================ /* * 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 . * */ #ifndef FREQUESTAUTHENTICATION_H #define FREQUESTAUTHENTICATION_H #include "util.h" // PLog library (log library) // https://github.com/SergiusTheBest/plog #include class FRequestAuthentication { public: enum class AuthenticationType{ REQUEST_AUTHENTICATION = 0, BASIC_AUTHENTICATION = 1 }; protected: FRequestAuthentication(const bool saveAuthToConfigFile, const bool retryLoginIfError401, const AuthenticationType type); public: virtual ~FRequestAuthentication() = default; // needed to avoid undefined behaviour https://stackoverflow.com/a/22491471/1499019 static AuthenticationType getAuthenticationTypeByString(const QString ¤tAuthenticationTypeText); static QString getAuthenticationString(const AuthenticationType currentAuthType); public: const AuthenticationType type; const bool saveAuthToConfigFile; // otherwise saves for project file const bool retryLoginIfError401; // should we retry on error 401? }; #endif // FREQUESTAUTHENTICATION_H ================================================ FILE: Authentications/requestauthentication.cpp ================================================ /* * 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 . * */ #include "requestauthentication.h" RequestAuthentication::RequestAuthentication ( const bool saveAuthToConfigFile, const bool retryLoginIfError401, const QString &username, const QString &passwordSalt, const QString &password, const QString requestForAuthenticationUuid ) : FRequestAuthentication(saveAuthToConfigFile, retryLoginIfError401, AuthenticationType::REQUEST_AUTHENTICATION), username(username), passwordSalt(passwordSalt), password(password), requestForAuthenticationUuid(requestForAuthenticationUuid) { } ================================================ FILE: Authentications/requestauthentication.h ================================================ /* * 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 . * */ #ifndef REQUESTAUTHENTICATION_H #define REQUESTAUTHENTICATION_H #include "frequestauthentication.h" class RequestAuthentication : public FRequestAuthentication { public: RequestAuthentication ( const bool saveAuthToConfigFile, const bool retryLoginIfError401, const QString &username, const QString &passwordSalt, const QString &password, const QString requestForAuthenticationUuid ); public: const QString username; const QString passwordSalt; const QString password; const QString requestForAuthenticationUuid; }; #endif // REQUESTAUTHENTICATION_H ================================================ FILE: FRequest.pro ================================================ #------------------------------------------------- # # Project created by QtCreator 2017-03-17T15:24:31 # #------------------------------------------------- QT += core gui network CONFIG += c++14 QMAKE_CXXFLAGS += -Wall QMAKE_CXXFLAGS += -Wextra greaterThan(QT_MAJOR_VERSION, 4): QT += widgets include(../CommonUtils/CommonUtils.pri) include(../CommonLibs/CommonLibs.pri) TARGET = FRequest TEMPLATE = app macx { ICON = Resources/frequest_icon.icns # mac os icon } win32 { RC_FILE = Resources/icon_resource.rc #for windows explorer icon } SOURCES += main.cpp\ mainwindow.cpp \ utilfrequest.cpp \ about.cpp \ preferences.cpp \ HttpRequests/deletehttprequest.cpp \ HttpRequests/httprequest.cpp \ HttpRequests/posthttprequest.cpp \ HttpRequests/puthttprequest.cpp \ HttpRequests/gethttprequest.cpp \ HttpRequests/patchhttprequest.cpp \ HttpRequests/headhttprequest.cpp \ HttpRequests/tracehttprequest.cpp \ HttpRequests/optionshttprequest.cpp \ Widgets/frequesttreewidgetitem.cpp \ XmlParsers/configfilefrequest.cpp \ XmlParsers/projectfilefrequest.cpp \ HttpRequests/httprequestwithmultipart.cpp \ projectproperties.cpp \ Authentications/frequestauthentication.cpp \ Authentications/basicauthentication.cpp \ Authentications/requestauthentication.cpp \ Widgets/frequesttreewidgetprojectitem.cpp \ Widgets/frequesttreewidgetrequestitem.cpp \ Widgets/frequesttreewidget.cpp \ updatechecker.cpp \ proxysetup.cpp \ SyntaxHighlighters/frequestjsonhighlighter.cpp \ SyntaxHighlighters/frequestxmlhighlighter.cpp HEADERS += mainwindow.h \ utilglobalvars.h \ utilfrequest.h \ about.h \ preferences.h \ HttpRequests/deletehttprequest.h \ HttpRequests/httprequest.h \ HttpRequests/posthttprequest.h \ HttpRequests/puthttprequest.h \ HttpRequests/gethttprequest.h \ HttpRequests/patchhttprequest.h \ HttpRequests/headhttprequest.h \ HttpRequests/tracehttprequest.h \ HttpRequests/optionshttprequest.h \ Widgets/frequesttreewidgetitem.h \ XmlParsers/configfilefrequest.h \ XmlParsers/projectfilefrequest.h \ HttpRequests/httprequestwithmultipart.h \ projectproperties.h \ Authentications/frequestauthentication.h \ Authentications/basicauthentication.h \ Authentications/requestauthentication.h \ Widgets/frequesttreewidgetprojectitem.h \ Widgets/frequesttreewidgetrequestitem.h \ Widgets/frequesttreewidget.h \ updatechecker.h \ proxysetup.h \ SyntaxHighlighters/frequestjsonhighlighter.h \ SyntaxHighlighters/frequestxmlhighlighter.h FORMS += mainwindow.ui \ about.ui \ preferences.ui \ projectproperties.ui RESOURCES += \ Resources/resources.qrc macx { RESOURCES += \ Resources/macos_resources.qrc } ================================================ FILE: HttpRequests/deletehttprequest.cpp ================================================ /* * 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 . * */ #include "deletehttprequest.h" DeleteHttpRequest::DeleteHttpRequest ( QNetworkAccessManager * const manager, const QString &fullPath, const QVector &requestHeaders ) :HttpRequest(manager, fullPath, requestHeaders) { } QNetworkReply* DeleteHttpRequest::sendRequest(const QNetworkRequest &request, const QByteArray &){ return this->manager->deleteResource(request); } ================================================ FILE: HttpRequests/deletehttprequest.h ================================================ /* * 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 . * */ #ifndef DELETEHTTPREQUEST_H #define DELETEHTTPREQUEST_H #include "httprequest.h" class DeleteHttpRequest : public HttpRequest { public: DeleteHttpRequest(QNetworkAccessManager * const manager, const QString &fullPath, const QVector &requestHeaders ); protected: virtual QNetworkReply* sendRequest(const QNetworkRequest &request, const QByteArray &data) override; }; #endif // DELETEHTTPREQUEST_H ================================================ FILE: HttpRequests/gethttprequest.cpp ================================================ /* * 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 . * */ #include "gethttprequest.h" GetHttpRequest::GetHttpRequest ( QNetworkAccessManager * const manager, const QString &fullPath, const QVector &requestHeaders ) :HttpRequest(manager, fullPath, requestHeaders) { } QNetworkReply* GetHttpRequest::sendRequest(const QNetworkRequest &request, const QByteArray &){ return this->manager->get(request); } ================================================ FILE: HttpRequests/gethttprequest.h ================================================ /* * 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 . * */ #ifndef GETHTTPREQUEST_H #define GETHTTPREQUEST_H #include "httprequest.h" class GetHttpRequest : public HttpRequest { public: GetHttpRequest( QNetworkAccessManager * const manager, const QString &fullPath, const QVector &requestHeaders ); protected: virtual QNetworkReply* sendRequest(const QNetworkRequest &request, const QByteArray &data) override; }; #endif // GETHTTPREQUEST_H ================================================ FILE: HttpRequests/headhttprequest.cpp ================================================ /* * 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 . * */ #include "headhttprequest.h" HeadHttpRequest::HeadHttpRequest ( QNetworkAccessManager * const manager, const QString &fullPath, const QVector &requestHeaders ) :HttpRequest(manager, fullPath, requestHeaders) { } QNetworkReply* HeadHttpRequest::sendRequest(const QNetworkRequest &request, const QByteArray &){ return this->manager->head(request); } ================================================ FILE: HttpRequests/headhttprequest.h ================================================ /* * 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 . * */ #ifndef HEADHTTPREQUEST_H #define HEADHTTPREQUEST_H #include "httprequest.h" class HeadHttpRequest : public HttpRequest { public: HeadHttpRequest( QNetworkAccessManager * const manager, const QString &fullPath, const QVector &requestHeaders ); protected: virtual QNetworkReply* sendRequest(const QNetworkRequest &request, const QByteArray &data) override; }; #endif // HEADHTTPREQUEST_H ================================================ FILE: HttpRequests/httprequest.cpp ================================================ /* * 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 . * */ #include "httprequest.h" HttpRequest::HttpRequest ( QNetworkAccessManager * const manager, QTableWidget * const twBodyFormKeyValue, const QString &fullPath, const QString &bodyType, const QString &rawRequestBody, const QVector &requestHeaders ) :fullPath(fullPath), requestHeaders(requestHeaders), rawRequestBody(rawRequestBody), bodyType(bodyType), manager(manager), twBodyFormKeyValue(twBodyFormKeyValue) { } HttpRequest::HttpRequest ( QNetworkAccessManager * const manager, const QString &fullPath, const QVector &requestHeaders ) :fullPath(fullPath), requestHeaders(requestHeaders), manager(manager), twBodyFormKeyValue(nullptr) { } QNetworkReply* HttpRequest::processRequest(){ QNetworkRequest request(QUrl(this->fullPath)); for(const UtilFRequest::HttpHeader ¤tHeader : this->requestHeaders){ // If multipart, don't add the multipart/form-data header, it is added automatically by HttpRequestWithMultiPart subclass if(!(currentHeader.name == "Content-type" && currentHeader.value == "multipart/form-data")){ request.setRawHeader(currentHeader.name.toUtf8(), currentHeader.value.toUtf8()); } } if(!bodyType.isEmpty()){ if(this->bodyType == "raw"){ return sendRequest(request, this->rawRequestBody.toUtf8()); } else if(this->bodyType == "form-data"){ return sendFormRequest(request); } else if(this->bodyType == "x-form-www-urlencoded"){ return sendFormRequest(request); } else{ QString errorMessage = "Body type unknown: '" + this->bodyType + "'. Application can't proceed."; Util::Dialogs::showError(errorMessage); LOG_FATAL << errorMessage; exit(1); } } else{ // Get, delete etc which doesn't have a "body" return sendRequest(request, QString().toUtf8()); } } QNetworkReply* HttpRequest::sendFormRequest(QNetworkRequest &request){ QUrlQuery params; for(int i = 0; i < this->twBodyFormKeyValue->rowCount(); i++){ params.addQueryItem(this->twBodyFormKeyValue->item(i,0)->text(), this->twBodyFormKeyValue->item(i,1)->text()); } return sendRequest(request, params.toString(QUrl::FullyEncoded).toUtf8()); } QNetworkReply* HttpRequest::sendHttpCustomRequest(const QNetworkRequest &request, const QString &verb, const QByteArray &data){ // Based from here: // https://stackoverflow.com/a/34065736/1499019 QBuffer *buffer=new QBuffer(); if(!data.isNull() && !data.isEmpty()){ buffer->open((QBuffer::ReadWrite)); buffer->write(data); buffer->seek(0); } return this->manager->sendCustomRequest(request, verb.toUtf8(), buffer); } QNetworkReply* HttpRequest::sendHttpCustomRequest(const QNetworkRequest &request, const QString &verb, QHttpMultiPart &data){ return this->manager->sendCustomRequest(request, verb.toUtf8(), &data); } ================================================ FILE: HttpRequests/httprequest.h ================================================ /* * 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 . * */ #ifndef HTTPREQUEST_H #define HTTPREQUEST_H #include #include #include #include #include #include #include "utilfrequest.h" #include class HttpRequest { public: HttpRequest ( QNetworkAccessManager * const manager, QTableWidget * const twBodyFormKeyValue, const QString &fullPath, const QString &bodyType, const QString &rawRequestBody, const QVector &requestHeaders ); HttpRequest ( QNetworkAccessManager * const manager, const QString &fullPath, const QVector &requestHeaders ); virtual ~HttpRequest() = default; // needed to avoid undefined behaviour https://stackoverflow.com/a/22491471/1499019 QNetworkReply* processRequest(); private: const QString fullPath; const QVector requestHeaders; const QString rawRequestBody; protected: const QString bodyType; QNetworkAccessManager * const manager; QTableWidget * const twBodyFormKeyValue; protected: virtual QNetworkReply* sendRequest(const QNetworkRequest &request, const QByteArray &data) = 0; // abstract funtion to be filled by subclasses virtual QNetworkReply* sendFormRequest(QNetworkRequest &request); QNetworkReply* sendHttpCustomRequest(const QNetworkRequest &request, const QString &verb, const QByteArray &data); QNetworkReply* sendHttpCustomRequest(const QNetworkRequest &request, const QString &verb, QHttpMultiPart &data); }; #endif // HTTPREQUEST_H ================================================ FILE: HttpRequests/httprequestwithmultipart.cpp ================================================ /* * 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 . * */ #include "httprequestwithmultipart.h" HttpRequestWithMultiPart::HttpRequestWithMultiPart ( QNetworkAccessManager * const manager, QTableWidget * const twBodyFormKeyValue, const QString &fullPath, const QString &bodyType, const QString &rawRequestBody, const QVector &requestHeaders ) :HttpRequest(manager, twBodyFormKeyValue, fullPath, bodyType, rawRequestBody, requestHeaders) { } QNetworkReply* HttpRequestWithMultiPart::sendFormRequest(QNetworkRequest &request){ // If not form data call default handler if(this->bodyType != "form-data"){ return HttpRequest::sendFormRequest(request); } // Process multi part (form data) request QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType); for(int i = 0; i < this->twBodyFormKeyValue->rowCount(); i++){ // TODO create enums to these columns, so we don't have to put the index directly const QString &currKey = this->twBodyFormKeyValue->item(i,0)->text(); const QString &currValue = this->twBodyFormKeyValue->item(i,1)->text(); const UtilFRequest::FormKeyValueType currFormKeyValueType = UtilFRequest::getFormKeyTypeByString(this->twBodyFormKeyValue->item(i,2)->text()); switch(currFormKeyValueType){ case UtilFRequest::FormKeyValueType::TEXT: { QHttpPart textPart; textPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"" + currKey + "\"")); textPart.setBody(currValue.toUtf8()); multiPart->append(textPart); break; } case UtilFRequest::FormKeyValueType::FILE: { QHttpPart filePart; filePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant(UtilFRequest::mimeDatabase.mimeTypeForFile(currValue, QMimeDatabase::MatchMode::MatchExtension).name())); filePart.setHeader( QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"" + Util::FileSystem::cutNameWithoutBackSlash(currKey) + "\"; filename=\"" + Util::FileSystem::cutNameWithoutBackSlash(currValue) + "\"") ); QFile *currFile = new QFile(currValue); currFile->open(QIODevice::ReadOnly); filePart.setBodyDevice(currFile); currFile->setParent(multiPart); // we cannot delete the file now, so delete it with the multiPart multiPart->append(filePart); break; } default: { QString errorMessage = "Invalid form key type " + QString::number(static_cast(currFormKeyValueType)) + "'. Program can't proceed."; Util::Dialogs::showError(errorMessage); LOG_FATAL << errorMessage; exit(1); } } } QNetworkReply *reply = sendRequest(request, *multiPart); multiPart->setParent(reply); return reply; } ================================================ FILE: HttpRequests/httprequestwithmultipart.h ================================================ /* * 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 . * */ #ifndef HTTPREQUESTWITHMULTIPART_H #define HTTPREQUESTWITHMULTIPART_H #include "httprequest.h" class HttpRequestWithMultiPart : public HttpRequest { public: HttpRequestWithMultiPart( QNetworkAccessManager * const manager, QTableWidget * const twBodyFormKeyValue, const QString &fullPath, const QString &bodyType, const QString &rawRequestBody, const QVector &requestHeaders ); // This constructor is not used for HttpRequestWithMultiPart classes HttpRequestWithMultiPart ( QNetworkAccessManager * const manager, const QString &fullPath, const QVector &requestHeaders ) = delete; virtual ~HttpRequestWithMultiPart() = default; // needed to avoid undefined behaviour https://stackoverflow.com/a/22491471/1499019 protected: virtual QNetworkReply* sendRequest(const QNetworkRequest &request, QHttpMultiPart &data) = 0; // abstract funtion to be filled by subclasses virtual QNetworkReply* sendRequest(const QNetworkRequest &request, const QByteArray &data) = 0; // abstract funtion to be filled by subclasses private: QNetworkReply* sendFormRequest(QNetworkRequest &request); }; #endif // HTTPREQUESTWITHMULTIPART_H ================================================ FILE: HttpRequests/optionshttprequest.cpp ================================================ /* * 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 . * */ #include "optionshttprequest.h" OptionsHttpRequest::OptionsHttpRequest ( QNetworkAccessManager * const manager, QTableWidget * const twBodyFormKeyValue, const QString &fullPath, const QString &bodyType, const QString &rawRequestBody, const QVector &requestHeaders ) :HttpRequestWithMultiPart(manager, twBodyFormKeyValue, fullPath, bodyType, rawRequestBody, requestHeaders) { } QNetworkReply* OptionsHttpRequest::sendRequest(const QNetworkRequest &request, const QByteArray &data){ return sendHttpCustomRequest(request, "OPTIONS", data); } QNetworkReply* OptionsHttpRequest::sendRequest(const QNetworkRequest &request, QHttpMultiPart &data){ return sendHttpCustomRequest(request, "OPTIONS", data); } ================================================ FILE: HttpRequests/optionshttprequest.h ================================================ /* * 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 . * */ #ifndef OPTIONSHTTPREQUEST_H #define OPTIONSHTTPREQUEST_H #include "httprequestwithmultipart.h" class OptionsHttpRequest : public HttpRequestWithMultiPart { public: OptionsHttpRequest( QNetworkAccessManager * const manager, QTableWidget * const twBodyFormKeyValue, const QString &fullPath, const QString &bodyType, const QString &rawRequestBody, const QVector &requestHeaders ); protected: virtual QNetworkReply* sendRequest(const QNetworkRequest &request, const QByteArray &data) override; virtual QNetworkReply* sendRequest(const QNetworkRequest &request, QHttpMultiPart &data) override; }; #endif // OPTIONSHTTPREQUEST_H ================================================ FILE: HttpRequests/patchhttprequest.cpp ================================================ /* * 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 . * */ #include "patchhttprequest.h" PatchHttpRequest::PatchHttpRequest ( QNetworkAccessManager * const manager, QTableWidget * const twBodyFormKeyValue, const QString &fullPath, const QString &bodyType, const QString &rawRequestBody, const QVector &requestHeaders ) :HttpRequestWithMultiPart(manager, twBodyFormKeyValue, fullPath, bodyType, rawRequestBody, requestHeaders) { } QNetworkReply* PatchHttpRequest::sendRequest(const QNetworkRequest &request, const QByteArray &data){ return sendHttpCustomRequest(request, "PATCH", data); } QNetworkReply* PatchHttpRequest::sendRequest(const QNetworkRequest &request, QHttpMultiPart &data){ return sendHttpCustomRequest(request, "PATCH", data); } ================================================ FILE: HttpRequests/patchhttprequest.h ================================================ /* * 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 . * */ #ifndef PATCHHTTPREQUEST_H #define PATCHHTTPREQUEST_H #include "httprequestwithmultipart.h" class PatchHttpRequest : public HttpRequestWithMultiPart { public: PatchHttpRequest( QNetworkAccessManager * const manager, QTableWidget * const twBodyFormKeyValue, const QString &fullPath, const QString &bodyType, const QString &rawRequestBody, const QVector &requestHeaders ); protected: virtual QNetworkReply* sendRequest(const QNetworkRequest &request, const QByteArray &data) override; virtual QNetworkReply* sendRequest(const QNetworkRequest &request, QHttpMultiPart &data) override; }; #endif // PATCHHTTPREQUEST_H ================================================ FILE: HttpRequests/posthttprequest.cpp ================================================ /* * 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 . * */ #include "posthttprequest.h" PostHttpRequest::PostHttpRequest ( QNetworkAccessManager * const manager, QTableWidget * const twBodyFormKeyValue, const QString &fullPath, const QString &bodyType, const QString &rawRequestBody, const QVector &requestHeaders ) :HttpRequestWithMultiPart(manager, twBodyFormKeyValue, fullPath, bodyType, rawRequestBody, requestHeaders) { } QNetworkReply* PostHttpRequest::sendRequest(const QNetworkRequest &request, const QByteArray &data){ return this->manager->post(request, data); } QNetworkReply* PostHttpRequest::sendRequest(const QNetworkRequest &request, QHttpMultiPart &data){ return this->manager->post(request, &data); } ================================================ FILE: HttpRequests/posthttprequest.h ================================================ /* * 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 . * */ #ifndef POSTHTTPREQUEST_H #define POSTHTTPREQUEST_H #include "httprequestwithmultipart.h" class PostHttpRequest : public HttpRequestWithMultiPart { public: PostHttpRequest( QNetworkAccessManager * const manager, QTableWidget * const twBodyFormKeyValue, const QString &fullPath, const QString &bodyType, const QString &rawRequestBody, const QVector &requestHeaders ); protected: virtual QNetworkReply* sendRequest(const QNetworkRequest &request, const QByteArray &data) override; virtual QNetworkReply* sendRequest(const QNetworkRequest &request, QHttpMultiPart &data) override; }; #endif // POSTHTTPREQUEST_H ================================================ FILE: HttpRequests/puthttprequest.cpp ================================================ /* * 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 . * */ #include "puthttprequest.h" PutHttpRequest::PutHttpRequest ( QNetworkAccessManager * const manager, QTableWidget * const twBodyFormKeyValue, const QString &fullPath, const QString &bodyType, const QString &rawRequestBody, const QVector &requestHeaders ) :HttpRequestWithMultiPart(manager, twBodyFormKeyValue, fullPath, bodyType, rawRequestBody, requestHeaders) { } QNetworkReply* PutHttpRequest::sendRequest(const QNetworkRequest &request, const QByteArray &data){ return this->manager->put(request, data); } QNetworkReply* PutHttpRequest::sendRequest(const QNetworkRequest &request, QHttpMultiPart &data){ return this->manager->put(request, &data); } ================================================ FILE: HttpRequests/puthttprequest.h ================================================ /* * 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 . * */ #ifndef PUTHTTPREQUEST_H #define PUTHTTPREQUEST_H #include "httprequestwithmultipart.h" class PutHttpRequest : public HttpRequestWithMultiPart { public: PutHttpRequest( QNetworkAccessManager * const manager, QTableWidget * const twBodyFormKeyValue, const QString &fullPath, const QString &bodyType, const QString &rawRequestBody, const QVector &requestHeaders ); protected: virtual QNetworkReply* sendRequest(const QNetworkRequest &request, const QByteArray &data) override; virtual QNetworkReply* sendRequest(const QNetworkRequest &request, QHttpMultiPart &data) override; }; #endif // PUTHTTPREQUEST_H ================================================ FILE: HttpRequests/tracehttprequest.cpp ================================================ /* * 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 . * */ #include "tracehttprequest.h" TraceHttpRequest::TraceHttpRequest ( QNetworkAccessManager * const manager, QTableWidget * const twBodyFormKeyValue, const QString &fullPath, const QString &bodyType, const QString &rawRequestBody, const QVector &requestHeaders ) :HttpRequestWithMultiPart(manager, twBodyFormKeyValue, fullPath, bodyType, rawRequestBody, requestHeaders) { } QNetworkReply* TraceHttpRequest::sendRequest(const QNetworkRequest &request, const QByteArray &){ return sendHttpCustomRequest(request, "TRACE", QByteArray()); } QNetworkReply* TraceHttpRequest::sendRequest(const QNetworkRequest &request, QHttpMultiPart &data){ return sendHttpCustomRequest(request, "TRACE", data); } ================================================ FILE: HttpRequests/tracehttprequest.h ================================================ /* * 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 . * */ #ifndef TRACEHTTPREQUEST_H #define TRACEHTTPREQUEST_H #include "httprequestwithmultipart.h" class TraceHttpRequest : public HttpRequestWithMultiPart { public: TraceHttpRequest( QNetworkAccessManager * const manager, QTableWidget * const twBodyFormKeyValue, const QString &fullPath, const QString &bodyType, const QString &rawRequestBody, const QVector &requestHeaders ); protected: virtual QNetworkReply* sendRequest(const QNetworkRequest &request, const QByteArray &data) override; virtual QNetworkReply* sendRequest(const QNetworkRequest &request, QHttpMultiPart &data) override; }; #endif // TRACEHTTPREQUEST_H ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. {one line to give the program's name and a brief idea of what it does.} Copyright (C) {year} {name of author} 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 . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: {project} Copyright (C) {year} {fullname} This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: LinuxAppImageDeployment/frequest.desktop ================================================ [Desktop Entry] Type=Application Name=FRequest Exec=FRequest Icon=frequest_icon Comment=A fast, lightweight and opensource desktop application to make HTTP(s) requests Categories=Development; Terminal=false ================================================ FILE: README.md ================================================ # FRequest [![Latest](https://img.shields.io/github/release/fabiobento512/frequest.svg?label=latest)](https://github.com/fabiobento512/FRequest/releases) FRequest - A fast, lightweight and opensource desktop application to make HTTP(s) requests. Available for Windows / macOS / Linux. Check FRequest website for more information. To build FRequest look here. ================================================ FILE: Resources/icon_resource.rc ================================================ IDI_ICON1 ICON DISCARDABLE "frequest_icon.ico" ================================================ FILE: Resources/macos_resources.qrc ================================================ macos_apptrans_workaround.png ================================================ FILE: Resources/resources.qrc ================================================ projects_folder_icon.png frequest_icon.png send_request_icon.png minus.png plus.png clipboard_icon.png plus_file.png warning_icon.png abort.png clone_icon.png delete_icon.png ================================================ FILE: SyntaxHighlighters/frequestjsonhighlighter.cpp ================================================ /* * 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 . * */ #include "frequestjsonhighlighter.h" FRequestJSONHighlighter::FRequestJSONHighlighter(QTextDocument *parent) : Highlighter(parent) { // Override colors for(HighlightingRule &currRule : this->rules){ if(currRule.pattern == QRegExp("(true|false|null)(?!\"[^\"]*\")")){ //reserved words currRule.format.setForeground(QColor(0x0066ff)); break; } } } ================================================ FILE: SyntaxHighlighters/frequestjsonhighlighter.h ================================================ /* * 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 . * */ #ifndef FREQUESTJSONHIGHLIGHTER_H #define FREQUESTJSONHIGHLIGHTER_H #include class FRequestJSONHighlighter: public Highlighter { Q_OBJECT public: FRequestJSONHighlighter(QTextDocument *parent = 0); }; #endif // FREQUESTJSONHIGHLIGHTER_H ================================================ FILE: SyntaxHighlighters/frequestxmlhighlighter.cpp ================================================ /* * 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 . * */ #include "frequestxmlhighlighter.h" FRequestXMLHighlighter::FRequestXMLHighlighter(QTextDocument * parent) : BasicXMLSyntaxHighlighter(parent) { m_xmlKeywordFormat.setForeground(QColor(0x0066ff)); m_xmlElementFormat.setForeground(QColor(0x0066ff)); } ================================================ FILE: SyntaxHighlighters/frequestxmlhighlighter.h ================================================ /* * 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 . * */ #ifndef FREQUESTXMLHIGHLIGHTER_H #define FREQUESTXMLHIGHLIGHTER_H #include class FRequestXMLHighlighter : public BasicXMLSyntaxHighlighter { Q_OBJECT public: FRequestXMLHighlighter(QTextDocument * parent = nullptr); }; #endif // FREQUESTXMLHIGHLIGHTER_H ================================================ FILE: Widgets/frequesttreewidget.cpp ================================================ /* * 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 . * */ #include "frequesttreewidget.h" FRequestTreeWidget::FRequestTreeWidget(QWidget *parent) : CustomTreeWidget(parent) { } void FRequestTreeWidget::keyPressEvent(QKeyEvent *event) { CustomTreeWidget::keyPressEvent(event); if (event->key() == Qt::Key_Delete) { event->accept(); emit deleteKeyPressed(); } } ================================================ FILE: Widgets/frequesttreewidget.h ================================================ /* * 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 . * */ #ifndef FREQUESTTREEWIDGET_H #define FREQUESTTREEWIDGET_H #include class FRequestTreeWidget : public CustomTreeWidget { Q_OBJECT public: FRequestTreeWidget(QWidget* parent); private slots: void keyPressEvent(QKeyEvent *event); signals: void deleteKeyPressed(); }; #endif // FREQUESTTREEWIDGET_H ================================================ FILE: Widgets/frequesttreewidgetitem.cpp ================================================ /* * 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 . * */ #include "frequesttreewidgetitem.h" FRequestTreeWidgetItem::FRequestTreeWidgetItem(const QStringList &list, const bool isProjectItem) :QTreeWidgetItem(list), isProjectItem(isProjectItem) { } FRequestTreeWidgetItem* FRequestTreeWidgetItem::fromQTreeWidgetItem(QTreeWidgetItem* widget){ FRequestTreeWidgetItem* result = dynamic_cast(widget); if(result == nullptr){ QString errorString = "Fatal error, failed to convert QTreeWidgetItem* to FRequestTreeWidgetItem*. Widget Text: " + widget->text(0) + "Widget Position: " + QString::number(widget->parent()->indexOfChild(widget)); LOG_FATAL << errorString; Util::Dialogs::showError(errorString + "\n Application can't proceed."); exit(-1); } return result; } bool FRequestTreeWidgetItem::hasEmptyIcon(){ return this->icon(0).isNull(); } ================================================ FILE: Widgets/frequesttreewidgetitem.h ================================================ /* * 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 . * */ #ifndef FREQUESTTREEWIDGETITEM_H #define FREQUESTTREEWIDGETITEM_H #include #include #include "utilfrequest.h" class FRequestTreeWidgetItem : public QTreeWidgetItem { public: FRequestTreeWidgetItem(const QStringList &list, const bool isProjectItem); static FRequestTreeWidgetItem* fromQTreeWidgetItem(QTreeWidgetItem* widget); bool hasEmptyIcon(); public: const bool isProjectItem; }; #endif // FREQUESTTREEWIDGETITEM_H ================================================ FILE: Widgets/frequesttreewidgetprojectitem.cpp ================================================ /* * 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 . * */ #include "frequesttreewidgetprojectitem.h" FRequestTreeWidgetProjectItem::FRequestTreeWidgetProjectItem(const QStringList &list, const QString &uuid) :FRequestTreeWidgetItem(list, true), uuid(uuid) { } FRequestTreeWidgetProjectItem* FRequestTreeWidgetProjectItem::fromQTreeWidgetItem(QTreeWidgetItem* widget){ FRequestTreeWidgetProjectItem* result = dynamic_cast(widget); if(result == nullptr){ QString errorString = "Fatal error, failed to convert QTreeWidgetItem* to FRequestTreeWidgetProjectItem*. Widget Text: " + widget->text(0) + "Widget Position: " + QString::number(widget->parent()->indexOfChild(widget)); LOG_FATAL << errorString; Util::Dialogs::showError(errorString + "\n Application can't proceed."); exit(-1); } return result; } QString FRequestTreeWidgetProjectItem::getUuid(){ return this->uuid; } FRequestTreeWidgetRequestItem * FRequestTreeWidgetProjectItem::getChildRequestByUuid(const QString &requestUuid){ if(!this->mapOfChilds_UuidToRequest.contains(requestUuid)){ QString errorString = "Fatal error, failed to get request item for the given uuid '" + requestUuid + "'"; LOG_FATAL << errorString; Util::Dialogs::showError(errorString + "\n Application can't proceed."); exit(-1); } return this->mapOfChilds_UuidToRequest[requestUuid]; } void FRequestTreeWidgetProjectItem::addRequestItemChild(FRequestTreeWidgetRequestItem * const child){ // Add uuid to our child cache this->mapOfChilds_UuidToRequest.insert(child->itemContent.uuid, child); addChild(child); // calls QTreeWidgetItem addChild() } ================================================ FILE: Widgets/frequesttreewidgetprojectitem.h ================================================ /* * 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 . * */ #ifndef FREQUESTTREEWIDGETPROJECTITEM_H #define FREQUESTTREEWIDGETPROJECTITEM_H #include "frequesttreewidgetrequestitem.h" #include "utilfrequest.h" #include class FRequestTreeWidgetProjectItem : public FRequestTreeWidgetItem { public: FRequestTreeWidgetProjectItem(const QStringList &list, const QString &uuid); public: static FRequestTreeWidgetProjectItem* fromQTreeWidgetItem(QTreeWidgetItem* widget); QString getUuid(); FRequestTreeWidgetRequestItem * getChildRequestByUuid(const QString &requestUuid); virtual void addRequestItemChild(FRequestTreeWidgetRequestItem * const child); public: QString projectName; QString projectMainUrl = "http://localhost/"; // can't use optional because it is an abstract base class, using unique_ptr as nullptr as alternative std::shared_ptr authData = nullptr; UtilFRequest::IdentCharacter saveIdentCharacter = UtilFRequest::IdentCharacter::SPACE; // space by default QVector globalHeaders; private: QString uuid; QHash mapOfChilds_UuidToRequest; }; #endif // FREQUESTTREEWIDGETPROJECTITEM_H ================================================ FILE: Widgets/frequesttreewidgetrequestitem.cpp ================================================ /* * 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 . * */ #include "frequesttreewidgetrequestitem.h" FRequestTreeWidgetRequestItem::FRequestTreeWidgetRequestItem(const QStringList &list, const QString &uuid) :FRequestTreeWidgetItem(list, false) { itemContent.uuid = uuid; } FRequestTreeWidgetRequestItem* FRequestTreeWidgetRequestItem::fromQTreeWidgetItem(QTreeWidgetItem* widget){ FRequestTreeWidgetRequestItem* result = dynamic_cast(widget); if(result == nullptr){ QString errorString = "Fatal error, failed to convert QTreeWidgetItem* to FRequestTreeWidgetRequestItem*. Widget Text: " + widget->text(0) + "Widget Position: " + QString::number(widget->parent()->indexOfChild(widget)); LOG_FATAL << errorString; Util::Dialogs::showError(errorString + "\n Application can't proceed."); exit(-1); } return result; } ================================================ FILE: Widgets/frequesttreewidgetrequestitem.h ================================================ /* * 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 . * */ #ifndef FREQUESTTREEWIDGETREQUESTITEM_H #define FREQUESTTREEWIDGETREQUESTITEM_H #include "frequesttreewidgetitem.h" class FRequestTreeWidgetRequestItem : public FRequestTreeWidgetItem { public: FRequestTreeWidgetRequestItem(const QStringList &list, const QString &uuid); static FRequestTreeWidgetRequestItem* fromQTreeWidgetItem(QTreeWidgetItem* widget); public: UtilFRequest::RequestInfo itemContent; }; Q_DECLARE_METATYPE(FRequestTreeWidgetRequestItem*) // necessary for qvariant_cast #endif // FREQUESTTREEWIDGETREQUESTITEM_H ================================================ FILE: XmlParsers/configfilefrequest.cpp ================================================ /* * 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 . * */ #include "configfilefrequest.h" ConfigFileFRequest::ConfigFileFRequest(const QString &fileFullPath) :fileFullPath(fileFullPath) { if(!QFile::exists(fileFullPath)){ createNewConfig(); return; } readSettingsFromFile(); } void ConfigFileFRequest::createNewConfig(){ pugi::xml_document doc; pugi::xml_node rootNode = doc.append_child("FRequestConfig"); rootNode.append_attribute("frequestVersion").set_value(QSTR_TO_TEMPORARY_CSTR(GlobalVars::LastCompatibleVersionConfig)); pugi::xml_node generalNode = rootNode.append_child("General"); generalNode.append_attribute("requestTimeout").set_value(currentSettings.requestTimeout); generalNode.append_attribute("maxRequestResponseDataSizeToDisplay").set_value(currentSettings.maxRequestResponseDataSizeToDisplay); generalNode.append_attribute("onStartupOption").set_value(static_cast(currentSettings.onStartupSelectedOption)); generalNode.append_attribute("theme").set_value(static_cast(currentSettings.theme)); generalNode.append_attribute("lastProjectPath"); generalNode.append_attribute("lastResponseFilePath"); generalNode.append_attribute("showRequestTypesIcons"); generalNode.append_attribute("hideProjectSavedDialog"); pugi::xml_node recentProjectsNode = rootNode.append_child("RecentProjects"); for(int i=1; i<=GlobalVars::AppRecentProjectsMaxSize; i++){ recentProjectsNode.append_child(QSTR_TO_TEMPORARY_CSTR("RecentProject" + QString::number(i))); } pugi::xml_node proxyNode = rootNode.append_child("Proxy"); proxyNode.append_attribute("useProxy").set_value(false); proxyNode.append_attribute("proxyType").set_value(0); proxyNode.append_attribute("hostName"); proxyNode.append_attribute("port").set_value(0); pugi::xml_node windowsGeometryNode = rootNode.append_child("WindowsGeometry"); windowsGeometryNode.append_attribute("saveWindowsGeometryWhenExiting").set_value(currentSettings.windowsGeometry.saveWindowsGeometryWhenExiting); pugi::xml_node mainWindowNode = windowsGeometryNode.append_child("MainWindow"); mainWindowNode.append_child("MainWindowGeometry"); mainWindowNode.append_child("RequestsSplitterState"); mainWindowNode.append_child("RequestResponseSplitterState"); pugi::xml_node defaultHeadersNode = rootNode.append_child("DefaultHeaders"); defaultHeadersNode.append_attribute("useDefaultHeaders").set_value(currentSettings.defaultHeaders.useDefaultHeaders); if(!doc.save_file(QSTR_TO_TEMPORARY_CSTR(fileFullPath), PUGIXML_TEXT("\t"), pugi::format_default | pugi::format_write_bom, pugi::xml_encoding::encoding_utf8)){ #ifdef Q_OS_MAC QString errorMessage = "An error ocurred while creating the FRequest config file.
" "Make sure the application is placed on a writable location." "
" "This problem can be caused by \"App Translocation\" more information here.
" "As workaround please try to move FRequest.app using finder to another folder with write permission, for instance your \"Documents\" folder, and then try to open it again.

" "" "
" "Application needs to abort."; const bool richError = true; #else QString errorMessage = "An error ocurred while creating the FRequest config file.\n" "Make sure the application is placed on a writable location.\n" "Application needs to abort."; const bool richError = false; #endif LOG_FATAL << errorMessage; Util::Dialogs::showError(errorMessage, richError); exit(1); } LOG_INFO << "Couldn't find an FRequest config file. A new config file was created."; } void ConfigFileFRequest::saveSettings(ConfigFileFRequest::Settings &newSettings){ try { pugi::xml_document doc; doc.load_file(QSTR_TO_TEMPORARY_CSTR(this->fileFullPath)); pugi::xml_node generalNode = doc.select_single_node("/FRequestConfig/General").node(); generalNode.attribute("requestTimeout").set_value(newSettings.requestTimeout); generalNode.attribute("maxRequestResponseDataSizeToDisplay").set_value(newSettings.maxRequestResponseDataSizeToDisplay); generalNode.attribute("onStartupOption").set_value(static_cast(newSettings.onStartupSelectedOption)); generalNode.attribute("theme").set_value(static_cast(newSettings.theme)); generalNode.attribute("lastProjectPath").set_value(QSTR_TO_TEMPORARY_CSTR(newSettings.lastProjectPath)); generalNode.attribute("lastResponseFilePath").set_value(QSTR_TO_TEMPORARY_CSTR(newSettings.lastResponseFilePath)); generalNode.attribute("showRequestTypesIcons").set_value(newSettings.showRequestTypesIcons); generalNode.attribute("hideProjectSavedDialog").set_value(newSettings.hideProjectSavedDialog); pugi::xml_node recentProjectsNode = doc.select_single_node("/FRequestConfig/RecentProjects").node(); for(int i=1; i<=GlobalVars::AppRecentProjectsMaxSize && newSettings.recentProjectsPaths.size() >= i; i++){ recentProjectsNode.child(QSTR_TO_TEMPORARY_CSTR("RecentProject" + QString::number(i))).text().set(QSTR_TO_TEMPORARY_CSTR(newSettings.recentProjectsPaths.at(i-1))); } pugi::xml_node proxyNode = doc.select_single_node("/FRequestConfig/Proxy").node(); proxyNode.attribute("useProxy").set_value(newSettings.useProxy); proxyNode.attribute("proxyType").set_value(static_cast(newSettings.proxySettings.type)); proxyNode.attribute("hostName").set_value(QSTR_TO_TEMPORARY_CSTR(newSettings.proxySettings.hostName)); proxyNode.attribute("port").set_value(newSettings.proxySettings.portNumber); pugi::xml_node windowsGeometryNode = doc.select_single_node("/FRequestConfig/WindowsGeometry").node(); windowsGeometryNode.attribute("saveWindowsGeometryWhenExiting").set_value(newSettings.windowsGeometry.saveWindowsGeometryWhenExiting); pugi::xml_node mainWindowNode = windowsGeometryNode.child("MainWindow"); mainWindowNode.child("MainWindowGeometry").text().set(QSTR_TO_TEMPORARY_CSTR(QString(newSettings.windowsGeometry.mainWindow_MainWindowGeometry.toBase64()))); mainWindowNode.child("RequestsSplitterState").text().set(QSTR_TO_TEMPORARY_CSTR(QString(newSettings.windowsGeometry.mainWindow_RequestsSplitterState.toBase64()))); mainWindowNode.child("RequestResponseSplitterState").text().set(QSTR_TO_TEMPORARY_CSTR(QString(newSettings.windowsGeometry.mainWindow_RequestResponseSplitterState.toBase64()))); pugi::xml_node defaultHeadersNode = doc.select_single_node("/FRequestConfig/DefaultHeaders").node(); defaultHeadersNode.attribute("useDefaultHeaders").set_value(newSettings.defaultHeaders.useDefaultHeaders); auto fUpdateHeaders = [](pugi::xml_node ¤tHeaderNode, const QVector &headers, const char *nodeName){ // Remove current Headers to update with new ones currentHeaderNode.remove_child(nodeName); pugi::xml_node rawNode = currentHeaderNode.append_child(nodeName); for(const UtilFRequest::HttpHeader ¤tHeader : headers){ pugi::xml_node headerNode = rawNode.append_child("Header"); headerNode.append_child("Key").append_child(pugi::xml_node_type::node_cdata).text().set(QSTR_TO_TEMPORARY_CSTR(currentHeader.name)); headerNode.append_child("Value").append_child(pugi::xml_node_type::node_cdata).text().set(QSTR_TO_TEMPORARY_CSTR(currentHeader.value)); } }; auto fWriteRequestType = [&fUpdateHeaders, &defaultHeadersNode](const QString &requestText, const std::experimental::optional &requestHeaders, const bool hasBody){ if(requestHeaders.has_value()){ pugi::xml_node currentHeaderNode = defaultHeadersNode.child(QSTR_TO_TEMPORARY_CSTR(requestText)); if(currentHeaderNode.empty()){ currentHeaderNode = defaultHeadersNode.append_child(QSTR_TO_TEMPORARY_CSTR(requestText)); } if(requestHeaders.value().headers_Raw.has_value()){ fUpdateHeaders(currentHeaderNode, requestHeaders.value().headers_Raw.value(), "Raw"); } if(hasBody){ if(requestHeaders.value().headers_Form_Data.has_value()){ fUpdateHeaders(currentHeaderNode, requestHeaders.value().headers_Form_Data.value(), "Form-data"); } if(requestHeaders.value().headers_X_form_www_urlencoded.has_value()){ fUpdateHeaders(currentHeaderNode, requestHeaders.value().headers_X_form_www_urlencoded.value(), "X-form-www-urlencoded"); } } } }; for(const UtilFRequest::RequestType ¤tRequestType : UtilFRequest::possibleRequestTypes){ QString currentRequestTypeText = UtilFRequest::getRequestTypeString(currentRequestType); bool hasBody = UtilFRequest::requestTypeMayHaveBody(currentRequestType); const std::experimental::optional &requestHeaders = getSettingsHeaderForRequestType(currentRequestType, newSettings); fWriteRequestType(currentRequestTypeText, requestHeaders, hasBody); } // Remove current config authentications (if they exist), since we will write all of them again doc.select_single_node("/FRequestConfig").node().remove_child("ConfigProjectAuthentications"); pugi::xml_node configAuthNode = doc.select_single_node("/FRequestConfig").node().append_child("ConfigProjectAuthentications"); for(const ConfigurationProjectAuthentication ¤tConfigAuth : newSettings.mapOfConfigAuths_UuidToConfigAuth){ const FRequestAuthentication &authData = *currentConfigAuth.authData; pugi::xml_node currentAuth = configAuthNode.append_child("Authentication"); currentAuth.append_attribute("lastProjectName").set_value(QSTR_TO_TEMPORARY_CSTR(currentConfigAuth.lastProjectName)); currentAuth.append_attribute("projectUuid").set_value(QSTR_TO_TEMPORARY_CSTR(currentConfigAuth.projectUuid)); currentAuth.append_attribute("type").set_value(static_cast(authData.type)); currentAuth.append_attribute("bRetryLoginIfError").set_value(authData.retryLoginIfError401); switch(authData.type){ case FRequestAuthentication::AuthenticationType::REQUEST_AUTHENTICATION: { const RequestAuthentication &requestAuth = static_cast(authData); currentAuth.append_attribute("requestUuid").set_value(QSTR_TO_TEMPORARY_CSTR(requestAuth.requestForAuthenticationUuid)); currentAuth.append_child("Username").append_child(pugi::xml_node_type::node_pcdata).set_value(QSTR_TO_TEMPORARY_CSTR(requestAuth.username)); currentAuth.append_child("PasswordSalt").append_child(pugi::xml_node_type::node_pcdata).set_value(QSTR_TO_TEMPORARY_CSTR(requestAuth.passwordSalt)); currentAuth.append_child("Password").append_child(pugi::xml_node_type::node_pcdata). set_value(QSTR_TO_TEMPORARY_CSTR(QString(UtilFRequest::simpleStringObfuscationDeobfuscation(requestAuth.passwordSalt, requestAuth.password).toBase64()))); break; } case FRequestAuthentication::AuthenticationType::BASIC_AUTHENTICATION: { const BasicAuthentication &basicAuth = static_cast(authData); currentAuth.append_child("Username").append_child(pugi::xml_node_type::node_pcdata).set_value(QSTR_TO_TEMPORARY_CSTR(basicAuth.username)); currentAuth.append_child("PasswordSalt").append_child(pugi::xml_node_type::node_pcdata).set_value(QSTR_TO_TEMPORARY_CSTR(basicAuth.passwordSalt)); currentAuth.append_child("Password").append_child(pugi::xml_node_type::node_pcdata). set_value(QSTR_TO_TEMPORARY_CSTR(QString(UtilFRequest::simpleStringObfuscationDeobfuscation(basicAuth.passwordSalt, basicAuth.password).toBase64()))); break; } default: { QString errorMessage = "Authentication type unknown: '" + QString::number(static_cast(authData.type)) + "'. Program can't proceed."; Util::Dialogs::showError(errorMessage); LOG_FATAL << errorMessage; exit(1); } } } if(!doc.save_file(QSTR_TO_TEMPORARY_CSTR(fileFullPath), PUGIXML_TEXT("\t"), pugi::format_default | pugi::format_write_bom, pugi::xml_encoding::encoding_utf8)){ throw std::runtime_error(QSTR_TO_TEMPORARY_CSTR("Error while saving: '" + fileFullPath + "'")); } } catch(const std::exception &e) { QString errorMessage = "An error ocurred while saving the FRequest settings. Settings were not saved." + QString(e.what()); LOG_ERROR << errorMessage; Util::Dialogs::showError(errorMessage); } this->currentSettings = newSettings; } void ConfigFileFRequest::readSettingsFromFile(){ try { upgradeConfigFileIfNecessary(); pugi::xml_document doc; doc.load_file(QSTR_TO_TEMPORARY_CSTR(this->fileFullPath)); pugi::xml_node generalNode = doc.select_single_node("/FRequestConfig/General").node(); this->currentSettings.requestTimeout = generalNode.attribute("requestTimeout").as_uint(); this->currentSettings.maxRequestResponseDataSizeToDisplay = generalNode.attribute("maxRequestResponseDataSizeToDisplay").as_uint(); this->currentSettings.onStartupSelectedOption = static_cast(generalNode.attribute("onStartupOption").as_int()); this->currentSettings.theme = static_cast(generalNode.attribute("theme").as_int()); this->currentSettings.lastProjectPath = generalNode.attribute("lastProjectPath").as_string(); this->currentSettings.lastResponseFilePath = generalNode.attribute("lastResponseFilePath").as_string(); this->currentSettings.showRequestTypesIcons = generalNode.attribute("showRequestTypesIcons").as_bool(); this->currentSettings.hideProjectSavedDialog = generalNode.attribute("hideProjectSavedDialog").as_bool(); pugi::xml_node recentProjectsNode = doc.select_single_node("/FRequestConfig/RecentProjects").node(); this->currentSettings.recentProjectsPaths.clear(); for(int i=1; i<=GlobalVars::AppRecentProjectsMaxSize; i++){ if(!recentProjectsNode.child(QSTR_TO_TEMPORARY_CSTR("RecentProject" + QString::number(i))).empty()){ if(!QString(recentProjectsNode.child(QSTR_TO_TEMPORARY_CSTR("RecentProject" + QString::number(i))).text().as_string()).isEmpty()){ this->currentSettings.recentProjectsPaths.append(recentProjectsNode.child(QSTR_TO_TEMPORARY_CSTR("RecentProject" + QString::number(i))).text().as_string()); } } } pugi::xml_node proxyNode = doc.select_single_node("/FRequestConfig/Proxy").node(); this->currentSettings.useProxy = proxyNode.attribute("useProxy").as_bool(false); this->currentSettings.proxySettings.type = static_cast(proxyNode.attribute("proxyType").as_int(0)); this->currentSettings.proxySettings.hostName = proxyNode.attribute("hostName").as_string(); this->currentSettings.proxySettings.portNumber = proxyNode.attribute("port").as_uint(0); pugi::xml_node windowsGeometryNode = doc.select_single_node("/FRequestConfig/WindowsGeometry").node(); this->currentSettings.windowsGeometry.saveWindowsGeometryWhenExiting = windowsGeometryNode.attribute("saveWindowsGeometryWhenExiting").as_bool(); pugi::xml_node mainWindowNode = windowsGeometryNode.child("MainWindow"); auto fReadBase64Setting = [&mainWindowNode](const char * const node) -> QByteArray{ QByteArray auxBase64Decode; auxBase64Decode.append(QString(mainWindowNode.child(node).text().as_string()).toUtf8()); return QByteArray::fromBase64(auxBase64Decode); }; this->currentSettings.windowsGeometry.mainWindow_MainWindowGeometry = fReadBase64Setting("MainWindowGeometry"); this->currentSettings.windowsGeometry.mainWindow_RequestsSplitterState = fReadBase64Setting("RequestsSplitterState"); this->currentSettings.windowsGeometry.mainWindow_RequestResponseSplitterState = fReadBase64Setting("RequestResponseSplitterState"); pugi::xml_node defaultHeadersNode = doc.select_single_node("/FRequestConfig/DefaultHeaders").node(); this->currentSettings.defaultHeaders.useDefaultHeaders = defaultHeadersNode.attribute("useDefaultHeaders").as_bool(); auto fReadHeaders = [](UtilFRequest::BodyType bodyType, std::experimental::optional &requestHeaders, pugi::xml_node ¤tHeaderNode){ QString nodeName; switch(bodyType){ case UtilFRequest::BodyType::RAW: nodeName = "Raw"; break; case UtilFRequest::BodyType::FORM_DATA: nodeName = "Form-data"; break; case UtilFRequest::BodyType::X_FORM_WWW_URLENCODED: nodeName = "X-form-www-urlencoded"; break; default: throw std::runtime_error(QSTR_TO_TEMPORARY_CSTR("Unknown body type " + QString::number(static_cast(bodyType)))); } for(const pugi::xml_node ¤tNode : currentHeaderNode.child(QSTR_TO_TEMPORARY_CSTR(nodeName)).children()){ if(!requestHeaders.has_value()){ requestHeaders = ProtocolHeader(); } std::experimental::optional> *currentHeaders; switch(bodyType){ case UtilFRequest::BodyType::RAW: currentHeaders = &requestHeaders.value().headers_Raw; break; case UtilFRequest::BodyType::FORM_DATA: currentHeaders = &requestHeaders.value().headers_Form_Data; break; case UtilFRequest::BodyType::X_FORM_WWW_URLENCODED: currentHeaders = &requestHeaders.value().headers_X_form_www_urlencoded; break; default: throw std::runtime_error(QSTR_TO_TEMPORARY_CSTR("Unknown body type " + QString::number(static_cast(bodyType)))); } if(!currentHeaders->has_value()){ (*currentHeaders) = QVector(); } UtilFRequest::HttpHeader currentHeader; currentHeader.name = currentNode.child("Key").text().as_string(); currentHeader.value = currentNode.child("Value").text().as_string(); (*currentHeaders).value().append(currentHeader); } }; auto fReadRequestType = [&defaultHeadersNode, &fReadHeaders](const QString &requestText, std::experimental::optional &requestHeaders, const bool hasBody){ pugi::xml_node currentHeaderNode = defaultHeadersNode.child(QSTR_TO_TEMPORARY_CSTR(requestText)); if(!currentHeaderNode.empty()){ if(!requestHeaders.has_value()){ requestHeaders = ProtocolHeader(); } if(!currentHeaderNode.child("Raw").empty()){ fReadHeaders(UtilFRequest::BodyType::RAW, requestHeaders, currentHeaderNode); } if(hasBody){ if(!currentHeaderNode.child("Form-data").empty()){ fReadHeaders(UtilFRequest::BodyType::FORM_DATA, requestHeaders, currentHeaderNode); } if(!currentHeaderNode.child("X-form-www-urlencoded").empty()){ fReadHeaders(UtilFRequest::BodyType::X_FORM_WWW_URLENCODED, requestHeaders, currentHeaderNode); } } } }; for(const UtilFRequest::RequestType ¤tRequestType : UtilFRequest::possibleRequestTypes){ QString currentRequestTypeText = UtilFRequest::getRequestTypeString(currentRequestType); bool hasBody = UtilFRequest::requestTypeMayHaveBody(currentRequestType); std::experimental::optional &requestHeaders = getSettingsHeaderForRequestType(currentRequestType, this->currentSettings); fReadRequestType(currentRequestTypeText, requestHeaders, hasBody); } // Check if there is authentication data and load it pugi::xpath_node_set configAuthNodes = doc.select_nodes("/FRequestConfig/ConfigProjectAuthentications/Authentication"); for(const pugi::xpath_node &currXPathNode : configAuthNodes){ pugi::xml_node currAuthNode = currXPathNode.node(); ConfigurationProjectAuthentication currProjAuth; currProjAuth.lastProjectName = currAuthNode.attribute("lastProjectName").value(); currProjAuth.projectUuid = currAuthNode.attribute("projectUuid").value(); FRequestAuthentication::AuthenticationType authType = static_cast(currAuthNode.attribute("type").as_int()); const bool retryLoginIfError401 = currAuthNode.attribute("bRetryLoginIfError").as_bool(); switch(authType){ case FRequestAuthentication::AuthenticationType::REQUEST_AUTHENTICATION: { QString username = currAuthNode.child("Username").child_value(); QString passwordSalt = currAuthNode.child("PasswordSalt").child_value(); QString password = QString(UtilFRequest::simpleStringObfuscationDeobfuscation(passwordSalt, QByteArray::fromBase64(currAuthNode.child("Password").child_value()))); QString requestUuid = currAuthNode.attribute("requestUuid").value(); currProjAuth.authData = std::make_shared(RequestAuthentication(true, retryLoginIfError401, username, passwordSalt, password, requestUuid)); break; } case FRequestAuthentication::AuthenticationType::BASIC_AUTHENTICATION: { QString username = currAuthNode.child("Username").child_value(); QString passwordSalt = currAuthNode.child("PasswordSalt").child_value(); QString password = QString(UtilFRequest::simpleStringObfuscationDeobfuscation(passwordSalt, QByteArray::fromBase64(currAuthNode.child("Password").child_value()))); currProjAuth.authData = std::make_shared(BasicAuthentication(true, retryLoginIfError401, username, passwordSalt, password)); break; } default: { QString errorMessage = "Authentication type unknown: '" + QString::number(static_cast(authType)) + "'. Program can't proceed."; Util::Dialogs::showError(errorMessage); LOG_FATAL << errorMessage; exit(1); } } this->currentSettings.mapOfConfigAuths_UuidToConfigAuth.insert(currProjAuth.projectUuid, currProjAuth); } if(!doc.save_file(QSTR_TO_TEMPORARY_CSTR(fileFullPath), PUGIXML_TEXT("\t"), pugi::format_default | pugi::format_write_bom, pugi::xml_encoding::encoding_utf8)){ throw std::runtime_error(QSTR_TO_TEMPORARY_CSTR("Error while saving: '" + fileFullPath + "'")); } } catch(const std::exception &e) { QString errorMessage = "An error ocurred while loading the FRequest settings. Settings were not loaded. " + QString(e.what()); LOG_ERROR << errorMessage; Util::Dialogs::showError(errorMessage); } } ConfigFileFRequest::Settings ConfigFileFRequest::getCurrentSettings(){ return this->currentSettings; } std::experimental::optional& ConfigFileFRequest::getSettingsHeaderForRequestType(UtilFRequest::RequestType currentRequestType, Settings ¤tSettings){ std::experimental::optional *currentProtocolHeader = nullptr; switch(currentRequestType){ case UtilFRequest::RequestType::GET_OPTION: { currentProtocolHeader = ¤tSettings.defaultHeaders.getHeaders; break; } case UtilFRequest::RequestType::POST_OPTION: { currentProtocolHeader = ¤tSettings.defaultHeaders.postHeaders; break; } case UtilFRequest::RequestType::PUT_OPTION: { currentProtocolHeader = ¤tSettings.defaultHeaders.putHeaders; break; } case UtilFRequest::RequestType::DELETE_OPTION: { currentProtocolHeader = ¤tSettings.defaultHeaders.deleteHeaders; break; } case UtilFRequest::RequestType::PATCH_OPTION: { currentProtocolHeader = ¤tSettings.defaultHeaders.patchHeaders; break; } case UtilFRequest::RequestType::HEAD_OPTION: { currentProtocolHeader = ¤tSettings.defaultHeaders.headHeaders; break; } case UtilFRequest::RequestType::TRACE_OPTION: { currentProtocolHeader = ¤tSettings.defaultHeaders.traceHeaders; break; } case UtilFRequest::RequestType::OPTIONS_OPTION: { currentProtocolHeader = ¤tSettings.defaultHeaders.optionsHeaders; break; } default: { QString errorMessage = "Request type unknown: '" + QString::number(static_cast(currentRequestType)) + "'. Program can't proceed."; Util::Dialogs::showError(errorMessage); LOG_FATAL << errorMessage; exit(1); } } return *currentProtocolHeader; } void ConfigFileFRequest::upgradeConfigFileIfNecessary(){ pugi::xml_document doc; pugi::xml_parse_result result = doc.load_file(QSTR_TO_TEMPORARY_CSTR(this->fileFullPath)); if(result.status!=pugi::status_ok){ throw std::runtime_error(QSTR_TO_TEMPORARY_CSTR(QString("An error ocurred while loading project file.\n") + result.description())); } QString currentConfigVersion = QString(doc.select_single_node("/FRequestConfig").node().attribute("frequestVersion").as_string()); if(currentConfigVersion != GlobalVars::LastCompatibleVersionConfig){ if(!Util::FileSystem::backupFile(this->fileFullPath, this->fileFullPath + UtilFRequest::getDateTimeFormatForFilename(QDateTime::currentDateTime()))){ QString errorMessage = "Couldn't backup the existing config file for version upgrade, program can't proceed."; Util::Dialogs::showError(errorMessage); LOG_FATAL << errorMessage; exit(1); } } auto fUpgradeFileIfNecessary = [&doc, fileFullPath = this->fileFullPath, ¤tConfigVersion]( const QString &oldVersion, const QString &newVersion, std::function upgradeFunction){ // Upgrade necessary? if(currentConfigVersion == oldVersion){ // Update version doc.select_single_node("/FRequestConfig").node().attribute("frequestVersion").set_value(QSTR_TO_TEMPORARY_CSTR(newVersion)); // do specific upgrade changes upgradeFunction(); if(!doc.save_file(QSTR_TO_TEMPORARY_CSTR(fileFullPath), PUGIXML_TEXT("\t"), pugi::format_default | pugi::format_write_bom, pugi::xml_encoding::encoding_utf8)){ throw std::runtime_error(QSTR_TO_TEMPORARY_CSTR("Error while saving: '" + fileFullPath + "'. After file version upgrade. (to version " + newVersion + " )")); } currentConfigVersion = newVersion; } }; fUpgradeFileIfNecessary("1.0", "1.1", [&](){ pugi::xml_node generalNode = doc.select_single_node("/FRequestConfig/General").node(); generalNode.append_attribute("showRequestTypesIcons").set_value(true); // Fix proxy node (it should start with upper case instead of lower case pugi::xml_node proxyNode = doc.select_single_node("/FRequestConfig/proxy").node(); if(!proxyNode.empty()){ proxyNode.set_name("Proxy"); } }); fUpgradeFileIfNecessary("1.1", "1.1a", [&](){ pugi::xml_node generalNode = doc.select_single_node("/FRequestConfig/General").node(); // Delete old attribute 'askToOpenLastProject' pugi::xml_attribute askToOpenLastProjectAttribute = generalNode.attribute("askToOpenLastProject"); if(!askToOpenLastProjectAttribute.empty()){ generalNode.remove_attribute(askToOpenLastProjectAttribute); } // Add new attribute that replaces 'askToOpenLastProject' // use ASK_TO_LOAD_LAST_PROJECT as default generalNode.append_attribute("onStartupOption").set_value("0"); // 0 = ASK_TO_LOAD_LAST_PROJECT in 1.1a // Add new attribute that specifies the max response size for display in ui generalNode.append_attribute("maxRequestResponseDataSizeToDisplay").set_value(200); // 200 kb default }); fUpgradeFileIfNecessary("1.1a", "1.1b", [&](){ pugi::xml_node generalNode = doc.select_single_node("/FRequestConfig/General").node(); // Add new attribute for themes generalNode.append_attribute("theme").set_value("0"); // 0 = OS_DEFAULT in 1.1b }); fUpgradeFileIfNecessary("1.1b", "1.2", [&](){ pugi::xml_node generalNode = doc.select_single_node("/FRequestConfig/General").node(); generalNode.append_attribute("hideProjectSavedDialog").set_value(false); }); if(currentConfigVersion != GlobalVars::LastCompatibleVersionConfig){ throw std::runtime_error("Can't load the config file, it is from an incompatible version. Probably newer?"); } } ConfigFileFRequest::FRequestTheme ConfigFileFRequest::geFRequestThemeByString(const QString ¤tFRequestThemeText){ if(currentFRequestThemeText == "OS Default"){ return FRequestTheme::OS_DEFAULT; } else if(currentFRequestThemeText == "Jorgen's Dark Theme"){ return FRequestTheme::JORGEN_DARK_THEME; } else{ QString errorMessage = "FRequestTheme unknown: '" + currentFRequestThemeText + "'. Program can't proceed."; Util::Dialogs::showError(errorMessage); LOG_FATAL << errorMessage; exit(1); } } QString ConfigFileFRequest::getFRequestThemeString(const FRequestTheme currentFRequestTheme){ switch(currentFRequestTheme){ case FRequestTheme::OS_DEFAULT: return "OS Default"; case FRequestTheme::JORGEN_DARK_THEME: return "Jorgen's Dark Theme"; default: { QString errorMessage = "Invalid FRequestTheme " + QString::number(static_cast(currentFRequestTheme)) + "'. Program can't proceed."; Util::Dialogs::showError(errorMessage); LOG_FATAL << errorMessage; exit(1); } } } ================================================ FILE: XmlParsers/configfilefrequest.h ================================================ /* * 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 . * */ #ifndef CONFIGFILEFREQUEST_H #define CONFIGFILEFREQUEST_H #include "utilfrequest.h" #include "Authentications/requestauthentication.h" #include "Authentications/basicauthentication.h" #include class ConfigFileFRequest { public: enum class ProxyType{ AUTOMATIC = 0, HTTP_TRANSPARENT = 1, HTTP = 2, SOCKS5 = 3 }; enum class OnStartupOption{ ASK_TO_LOAD_LAST_PROJECT = 0, LOAD_LAST_PROJECT = 1, DO_NOTHING = 100 }; enum class FRequestTheme{ OS_DEFAULT = 0, JORGEN_DARK_THEME = 1 }; struct ProtocolHeader{ std::experimental::optional> headers_Raw; std::experimental::optional> headers_Form_Data; std::experimental::optional> headers_X_form_www_urlencoded; }; struct DefaultHeaders{ bool useDefaultHeaders = false; std::experimental::optional getHeaders; std::experimental::optional postHeaders; std::experimental::optional putHeaders; std::experimental::optional deleteHeaders; std::experimental::optional patchHeaders; std::experimental::optional headHeaders; std::experimental::optional traceHeaders; std::experimental::optional optionsHeaders; }; struct WindowsGeometry{ bool saveWindowsGeometryWhenExiting = false; QByteArray mainWindow_MainWindowGeometry; QByteArray mainWindow_RequestsSplitterState; QByteArray mainWindow_RequestResponseSplitterState; }; struct ProxySettings{ ProxyType type = ProxyType::AUTOMATIC; QString hostName; unsigned int portNumber = 0; }; struct ConfigurationProjectAuthentication{ QString lastProjectName; QString projectUuid; std::shared_ptr authData; // using shared ptr just to not be obligated to initialize all members at same time }; struct Settings{ unsigned int requestTimeout = 20; unsigned int maxRequestResponseDataSizeToDisplay = 200; OnStartupOption onStartupSelectedOption = OnStartupOption::ASK_TO_LOAD_LAST_PROJECT; FRequestTheme theme = FRequestTheme::OS_DEFAULT; QString lastProjectPath; QString lastResponseFilePath; bool showRequestTypesIcons = true; QVector recentProjectsPaths; WindowsGeometry windowsGeometry; DefaultHeaders defaultHeaders; bool useProxy = false; ProxySettings proxySettings; // the hash map below contains the authentication data of the projects that specified it to be saved on config file instead of in project file QHash mapOfConfigAuths_UuidToConfigAuth; bool hideProjectSavedDialog = false; }; public: ConfigFileFRequest(const QString &fileFullPath); ConfigFileFRequest::Settings getCurrentSettings(); void saveSettings(Settings &newSettings); static std::experimental::optional& getSettingsHeaderForRequestType(UtilFRequest::RequestType currentRequestType, Settings ¤tSettings); static FRequestTheme geFRequestThemeByString(const QString ¤tFRequestThemeText); static QString getFRequestThemeString(const FRequestTheme currentFRequestTheme); private: void createNewConfig(); void readSettingsFromFile(); void upgradeConfigFileIfNecessary(); private: Settings currentSettings; const QString fileFullPath; }; #endif // CONFIGFILEFREQUEST_H ================================================ FILE: XmlParsers/projectfilefrequest.cpp ================================================ /* * 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 . * */ #include "projectfilefrequest.h" ProjectFileFRequest::ProjectData ProjectFileFRequest::readProjectDataFromFile(const QString &fileFullPath){ ProjectFileFRequest::ProjectData currentProjectData; upgradeProjectFileIfNecessary(fileFullPath); pugi::xml_document doc; pugi::xml_parse_result result = doc.load_file(QSTR_TO_TEMPORARY_CSTR(fileFullPath)); if(result.status!=pugi::status_ok){ throw std::runtime_error(QSTR_TO_TEMPORARY_CSTR(QString("An error ocurred while loading project file.\n") + result.description())); } if(QString(doc.root().first_child().name()) != "FRequestProject"){ throw std::runtime_error(QSTR_TO_TEMPORARY_CSTR(QString(doc.root().name()) + "The file opened is not a valid FRequestProject file. Load aborted.")); } QString projFRequestVersion; try{ projFRequestVersion = QString(doc.select_node("/FRequestProject/@frequestVersion").attribute().value()); } catch (const pugi::xpath_exception& e) { throw std::runtime_error(QSTR_TO_TEMPORARY_CSTR(QString("Couldn't find the frequestVersion of the current project. Load aborted.\n") + e.what())); } if(projFRequestVersion != GlobalVars::LastCompatibleVersionProjects){ throw std::runtime_error("The project that you are trying to load seems it is not compatible with your FRequest Version. Please update FRequest and try again."); } // After the initial validations begin loading the project data currentProjectData.mainUrl = doc.select_node("/FRequestProject/@mainUrl").attribute().value(); currentProjectData.projectName = doc.select_node("/FRequestProject/@name").attribute().value(); currentProjectData.projectUuid = doc.select_node("/FRequestProject/@uuid").attribute().value(); currentProjectData.saveIdentCharacter = static_cast(doc.select_node("/FRequestProject/@saveIdentCharacter").attribute().as_int()); // Check if there is authentication data and load it pugi::xml_node authNode = doc.select_node("/FRequestProject/Authentication").node(); if(!authNode.empty()){ FRequestAuthentication::AuthenticationType authType = static_cast(authNode.attribute("type").as_int()); const bool retryLoginIfError401 = authNode.attribute("bRetryLoginIfError").as_bool(); switch(authType){ case FRequestAuthentication::AuthenticationType::REQUEST_AUTHENTICATION: { QString username = authNode.child("Username").child_value(); QString passwordSalt = authNode.child("PasswordSalt").child_value(); QString password = QString(UtilFRequest::simpleStringObfuscationDeobfuscation(passwordSalt, QByteArray::fromBase64(authNode.child("Password").child_value()))); QString requestUuid = authNode.attribute("requestUuid").value(); currentProjectData.authData = std::make_shared(RequestAuthentication(false, retryLoginIfError401, username, passwordSalt, password, requestUuid)); break; } case FRequestAuthentication::AuthenticationType::BASIC_AUTHENTICATION: { QString username = authNode.child("Username").child_value(); QString passwordSalt = authNode.child("PasswordSalt").child_value(); QString password = QString(UtilFRequest::simpleStringObfuscationDeobfuscation(passwordSalt, QByteArray::fromBase64(authNode.child("Password").child_value()))); currentProjectData.authData = std::make_shared(BasicAuthentication(false, retryLoginIfError401, username, passwordSalt, password)); break; } default: { QString errorMessage = "Authentication type unknown: '" + QString::number(static_cast(authType)) + "'. Program can't proceed."; Util::Dialogs::showError(errorMessage); LOG_FATAL << errorMessage; exit(1); } } } // Fetch request items pugi::xpath_node_set requestNodes = doc.select_nodes("/FRequestProject/Request"); // Aux lambda to avoid duplicated code for FORM_DATA / X_FORM_WWW_URLENCODED auto fGetBodyForm = [](pugi::xml_node &bodyNode) -> QVector { QVector bodyForm; for(const pugi::xml_node ¤tFormKeyValueNode : bodyNode.children()){ UtilFRequest::HttpFormKeyValueType currentFormKeyValue ( currentFormKeyValueNode.child("Key").child_value(), currentFormKeyValueNode.child("Value").child_value(), static_cast(QString(currentFormKeyValueNode.child("Type").child_value()).toInt()) // TODO check if pugixml has any method do retreive int directly for elements / pcdata ); bodyForm.append(currentFormKeyValue); } return bodyForm; }; for(size_t i=0; i < requestNodes.size(); i++){ pugi::xml_node currNode = requestNodes[i].node(); UtilFRequest::RequestInfo currentRequestInfo; currentRequestInfo.path = currNode.attribute("path").as_string(); currentRequestInfo.requestType = static_cast(currNode.attribute("type").as_int()); pugi::xml_node bodyNode = currNode.child("Body"); currentRequestInfo.bodyType = static_cast(bodyNode.attribute("type").as_int()); switch (currentRequestInfo.bodyType) { case UtilFRequest::BodyType::RAW: { currentRequestInfo.body = bodyNode.child_value(); break; } case UtilFRequest::BodyType::FORM_DATA: { currentRequestInfo.bodyForm = fGetBodyForm(bodyNode); break; } case UtilFRequest::BodyType::X_FORM_WWW_URLENCODED: { currentRequestInfo.bodyForm = fGetBodyForm(bodyNode); break; } default: { break; } } QVector requestHeaders; for(const pugi::xml_node ¤tHeaderNode : currNode.child("Headers").children()){ UtilFRequest::HttpHeader currentRequestHeader; currentRequestHeader.name = QString(currentHeaderNode.child("Key").child_value()); currentRequestHeader.value = currentHeaderNode.child("Value").child_value(); requestHeaders.append(currentRequestHeader); } currentRequestInfo.headers = requestHeaders; currentRequestInfo.bOverridesMainUrl = currNode.attribute("bOverridesMainUrl").as_bool(); currentRequestInfo.overrideMainUrl = currNode.attribute("overrideMainUrl").value(); currentRequestInfo.bDownloadResponseAsFile = currNode.attribute("bDownloadResponseAsFile").as_bool(); currentRequestInfo.name = requestNodes[i].node().attribute("name").value(); currentRequestInfo.uuid = requestNodes[i].node().attribute("uuid").value(); currentRequestInfo.order = requestNodes[i].node().attribute("order").as_ullong(); currentRequestInfo.bDisableGlobalHeaders = currNode.attribute("bDisableGlobalHeaders").as_bool(); currentProjectData.projectRequests.append(currentRequestInfo); } pugi::xml_node globalHeadersNode = doc.select_node("/FRequestProject/GlobalHeaders").node(); QVector globalHeaders; for(const pugi::xml_node ¤tGlobalHeaderNode : globalHeadersNode.children()){ UtilFRequest::HttpHeader currentGlobalHeader; currentGlobalHeader.name = QString(currentGlobalHeaderNode.child("Key").child_value()); currentGlobalHeader.value = currentGlobalHeaderNode.child("Value").child_value(); globalHeaders.append(currentGlobalHeader); } currentProjectData.globalHeaders = globalHeaders; return currentProjectData; } void ProjectFileFRequest::saveProjectDataToFile(const QString &fileFullPath, const ProjectFileFRequest::ProjectData &newProjectData, const QVector &uuidsToCleanUp){ pugi::xml_document doc; pugi::xml_node rootNode; bool isNewFile = !QFileInfo(fileFullPath).exists(); // If file already exists try to read the project file if(!isNewFile){ pugi::xml_parse_result result = doc.load_file(QSTR_TO_TEMPORARY_CSTR(fileFullPath)); if(result.status!=pugi::status_ok){ throw std::runtime_error(QSTR_TO_TEMPORARY_CSTR(QString("An error ocurred while loading project file.\n") + result.description())); } // Try to clear deleted items from projects file if they exist for(const QString ¤tDeletedItemUuid : uuidsToCleanUp){ pugi::xml_node nodeToDelete = doc.select_node(QSTR_TO_TEMPORARY_CSTR("/FRequestProject/Request[@uuid='" + currentDeletedItemUuid + "']")).node(); if(!nodeToDelete.empty()){ nodeToDelete.parent().remove_child(nodeToDelete); } } rootNode = doc.child("FRequestProject"); } else{ rootNode = doc.append_child("FRequestProject"); // create } createOrGetPugiXmlAttribute(rootNode, "frequestVersion").set_value(QSTR_TO_TEMPORARY_CSTR(GlobalVars::LastCompatibleVersionProjects)); createOrGetPugiXmlAttribute(rootNode, "name").set_value(QSTR_TO_TEMPORARY_CSTR(newProjectData.projectName)); createOrGetPugiXmlAttribute(rootNode, "mainUrl").set_value(QSTR_TO_TEMPORARY_CSTR(newProjectData.mainUrl)); createOrGetPugiXmlAttribute(rootNode, "uuid").set_value(QSTR_TO_TEMPORARY_CSTR(newProjectData.projectUuid)); createOrGetPugiXmlAttribute(rootNode, "saveIdentCharacter").set_value(static_cast(newProjectData.saveIdentCharacter)); // Delete old auth data if exists (we always need to rebuild it rootNode.remove_child("Authentication"); // Save authentication data if it exists if(newProjectData.authData != nullptr && !newProjectData.authData->saveAuthToConfigFile){ // please add it as the first node, since it is less likely to be removed than some request pugi::xml_node currentAuth = rootNode.prepend_child("Authentication"); currentAuth.append_attribute("type").set_value(static_cast(newProjectData.authData->type)); currentAuth.append_attribute("bRetryLoginIfError").set_value(newProjectData.authData->retryLoginIfError401); switch(newProjectData.authData->type){ case FRequestAuthentication::AuthenticationType::REQUEST_AUTHENTICATION: { const RequestAuthentication &requestAuth = static_cast(*newProjectData.authData.get()); currentAuth.append_attribute("requestUuid").set_value(QSTR_TO_TEMPORARY_CSTR(requestAuth.requestForAuthenticationUuid)); currentAuth.append_child("Username").append_child(pugi::xml_node_type::node_pcdata).set_value(QSTR_TO_TEMPORARY_CSTR(requestAuth.username)); currentAuth.append_child("PasswordSalt").append_child(pugi::xml_node_type::node_pcdata).set_value(QSTR_TO_TEMPORARY_CSTR(requestAuth.passwordSalt)); currentAuth.append_child("Password").append_child(pugi::xml_node_type::node_pcdata). set_value(QSTR_TO_TEMPORARY_CSTR(QString(UtilFRequest::simpleStringObfuscationDeobfuscation(requestAuth.passwordSalt, requestAuth.password).toBase64()))); break; } case FRequestAuthentication::AuthenticationType::BASIC_AUTHENTICATION: { const BasicAuthentication &basicAuth = static_cast(*newProjectData.authData.get()); currentAuth.append_child("Username").append_child(pugi::xml_node_type::node_pcdata).set_value(QSTR_TO_TEMPORARY_CSTR(basicAuth.username)); currentAuth.append_child("PasswordSalt").append_child(pugi::xml_node_type::node_pcdata).set_value(QSTR_TO_TEMPORARY_CSTR(basicAuth.passwordSalt)); currentAuth.append_child("Password").append_child(pugi::xml_node_type::node_pcdata). set_value(QSTR_TO_TEMPORARY_CSTR(QString(UtilFRequest::simpleStringObfuscationDeobfuscation(basicAuth.passwordSalt, basicAuth.password).toBase64()))); break; } default: { QString errorMessage = "Authentication type unknown: '" + QString::number(static_cast(newProjectData.authData->type)) + "'. Program can't proceed."; Util::Dialogs::showError(errorMessage); LOG_FATAL << errorMessage; exit(1); } } } // Save by the current tree order for(const UtilFRequest::RequestInfo ¤tRequest : newProjectData.projectRequests){ pugi::xml_node requestNode; pugi::xpath_node xpathRequestNode = doc.select_node(QSTR_TO_TEMPORARY_CSTR("/FRequestProject/Request[@uuid='" + currentRequest.uuid + "']")); // if it doesn't exist yet create it if(xpathRequestNode.node().empty()){ requestNode = rootNode.append_child("Request"); } else{ // otherwise use the existing one requestNode = xpathRequestNode.node(); } createOrGetPugiXmlAttribute(requestNode, "name").set_value(QSTR_TO_TEMPORARY_CSTR(currentRequest.name)); createOrGetPugiXmlAttribute(requestNode, "uuid").set_value(QSTR_TO_TEMPORARY_CSTR(currentRequest.uuid)); createOrGetPugiXmlAttribute(requestNode, "order").set_value(currentRequest.order); createOrGetPugiXmlAttribute(requestNode, "bOverridesMainUrl").set_value(currentRequest.bOverridesMainUrl); createOrGetPugiXmlAttribute(requestNode, "overrideMainUrl").set_value(QSTR_TO_TEMPORARY_CSTR(currentRequest.overrideMainUrl)); createOrGetPugiXmlAttribute(requestNode, "path").set_value(QSTR_TO_TEMPORARY_CSTR(currentRequest.path)); createOrGetPugiXmlAttribute(requestNode, "type").set_value(static_cast(currentRequest.requestType)); createOrGetPugiXmlAttribute(requestNode, "bDownloadResponseAsFile").set_value(currentRequest.bDownloadResponseAsFile); createOrGetPugiXmlAttribute(requestNode, "bDisableGlobalHeaders").set_value(currentRequest.bDisableGlobalHeaders); // remove body if exists, we will rebuild it requestNode.remove_child("Body"); pugi::xml_node bodyNode = requestNode.append_child("Body"); bodyNode.append_attribute("type").set_value(static_cast(currentRequest.bodyType)); // Aux lambda to avoid duplicated code for FORM_DATA / X_FORM_WWW_URLENCODED auto fSaveFormKeyValues = [](const QVector &bodyForm, pugi::xml_node &bodyNode){ for(const UtilFRequest::HttpFormKeyValueType ¤tKeyValue : bodyForm){ pugi::xml_node currentFormKeyValueNode = bodyNode.append_child("FormKeyValue"); currentFormKeyValueNode.append_child("Key").append_child(pugi::xml_node_type::node_cdata).set_value(QSTR_TO_TEMPORARY_CSTR(currentKeyValue.key)); currentFormKeyValueNode.append_child("Value").append_child(pugi::xml_node_type::node_cdata).set_value(QSTR_TO_TEMPORARY_CSTR(currentKeyValue.value)); currentFormKeyValueNode.append_child("Type").append_child(pugi::node_pcdata).set_value(QSTR_TO_TEMPORARY_CSTR(QString::number(static_cast(currentKeyValue.type)))); // TODO check if pugixml accepts int directly } }; switch (currentRequest.bodyType) { case UtilFRequest::BodyType::RAW: { bodyNode.append_child(pugi::xml_node_type::node_cdata).set_value(QSTR_TO_TEMPORARY_CSTR(currentRequest.body)); break; } case UtilFRequest::BodyType::FORM_DATA: { fSaveFormKeyValues(currentRequest.bodyForm, bodyNode); break; } case UtilFRequest::BodyType::X_FORM_WWW_URLENCODED: { fSaveFormKeyValues(currentRequest.bodyForm, bodyNode); break; } default: { break; } } // remove headers if they exist, we will rebuild them requestNode.remove_child("Headers"); pugi::xml_node requestHeadersNode = requestNode.append_child("Headers"); for(const UtilFRequest::HttpHeader ¤tRequestHeader : currentRequest.headers){ pugi::xml_node currentRequestHeaderNode = requestHeadersNode.append_child("Header"); currentRequestHeaderNode.append_child("Key").append_child(pugi::xml_node_type::node_cdata).set_value(QSTR_TO_TEMPORARY_CSTR(currentRequestHeader.name)); currentRequestHeaderNode.append_child("Value").append_child(pugi::xml_node_type::node_cdata).set_value(QSTR_TO_TEMPORARY_CSTR(currentRequestHeader.value)); } } rootNode.remove_child("GlobalHeaders"); pugi::xml_node globalHeadersNode = rootNode.append_child("GlobalHeaders"); for (const UtilFRequest::HttpHeader ¤tGlobalHeader: newProjectData.globalHeaders) { pugi::xml_node currentGlobalHeaderNode = globalHeadersNode.append_child("Header"); currentGlobalHeaderNode.append_child("Key").append_child(pugi::xml_node_type::node_cdata).set_value(QSTR_TO_TEMPORARY_CSTR(currentGlobalHeader.name)); currentGlobalHeaderNode.append_child("Value").append_child(pugi::xml_node_type::node_cdata).set_value(QSTR_TO_TEMPORARY_CSTR(currentGlobalHeader.value)); } const pugi::char_t* const identCharacterChar = newProjectData.saveIdentCharacter == UtilFRequest::IdentCharacter::SPACE ? pugiIdentChars::spaceChar : pugiIdentChars::tabChar; if(!doc.save_file(fileFullPath.toUtf8().constData(), identCharacterChar, pugi::format_default | pugi::format_write_bom, pugi::xml_encoding::encoding_utf8)){ throw std::runtime_error("An error ocurred while trying to save the project file. Please try another path."); } } pugi::xml_attribute ProjectFileFRequest::createOrGetPugiXmlAttribute(pugi::xml_node &mainNode, const char *name){ // if attributes doesnt exists create it if(mainNode.attribute(name).empty()) { return mainNode.append_attribute(name); } else { // if it already exists return it return mainNode.attribute(name); } } void ProjectFileFRequest::upgradeProjectFileIfNecessary(const QString &filePath){ pugi::xml_document doc; pugi::xml_parse_result result = doc.load_file(QSTR_TO_TEMPORARY_CSTR(filePath)); if(result.status!=pugi::status_ok){ throw std::runtime_error(QSTR_TO_TEMPORARY_CSTR(QString("An error ocurred while loading project file.\n") + result.description())); } QString currProjectVersion = QString(doc.select_single_node("/FRequestProject").node().attribute("frequestVersion").as_string()); if(currProjectVersion != GlobalVars::LastCompatibleVersionProjects){ if(!Util::FileSystem::backupFile(filePath, filePath + UtilFRequest::getDateTimeFormatForFilename(QDateTime::currentDateTime()))){ QString errorMessage = "Couldn't backup the existing project file for version upgrade, program can't proceed."; Util::Dialogs::showError(errorMessage); LOG_FATAL << errorMessage; exit(1); } } auto fUpgradeFileIfNecessary = [&doc, &filePath, &currProjectVersion]( const QString &oldVersion, const QString &newVersion, const pugi::char_t* const identChar, std::function upgradeFunction){ // Upgrade necessary? if(currProjectVersion == oldVersion){ pugi::xml_node projectNode = doc.select_single_node("/FRequestProject").node(); // Update version projectNode.attribute("frequestVersion").set_value(QSTR_TO_TEMPORARY_CSTR(newVersion)); // do specific upgrade changes upgradeFunction(); if(!doc.save_file(QSTR_TO_TEMPORARY_CSTR(filePath), identChar, pugi::format_default | pugi::format_write_bom, pugi::xml_encoding::encoding_utf8)){ throw std::runtime_error(QSTR_TO_TEMPORARY_CSTR("Error while saving: '" + filePath + "'. After file version upgrade. (to version " + newVersion + " )")); } currProjectVersion = newVersion; } }; fUpgradeFileIfNecessary("1.0", "1.1", pugiIdentChars::tabChar, [&](){ pugi::xml_node projectNode = doc.select_single_node("/FRequestProject").node(); // Generate an uuid to the project projectNode.append_attribute("uuid").set_value(QSTR_TO_TEMPORARY_CSTR(QUuid::createUuid().toString())); // Add types to form rows // Get form request bodies nodes to update pugi::xpath_node_set formKeyValuesNodes = doc.select_nodes("/FRequestProject/Request/Body/FormKeyValue"); for(size_t i=0; i < formKeyValuesNodes.size(); i++){ formKeyValuesNodes[i].node().append_child("Type").append_child(pugi::node_pcdata).set_value("0"); // 0 is Text in 1.1 } }); fUpgradeFileIfNecessary("1.1", "1.1c", pugiIdentChars::tabChar, [&](){ pugi::xml_node projectNode = doc.select_single_node("/FRequestProject").node(); // Set the default ident character // Previous to 1.1c all versions use tab as separator, so we want to keep that // until user changes, even though now space is the default projectNode.append_attribute("saveIdentCharacter").set_value("1"); // 0 is tab in 1.1c }); const pugi::char_t* const currSaveIdentCharacter = pugiIdentChars::getIdentCharaterForEnum(static_cast( doc.select_node("/FRequestProject/@saveIdentCharacter").attribute().as_int())); fUpgradeFileIfNecessary("1.1c", "1.2", currSaveIdentCharacter, [&](){ pugi::xml_node projectNode = doc.select_single_node("/FrequestProject").node(); projectNode.append_child("GlobalHeaders"); }); if(currProjectVersion != GlobalVars::LastCompatibleVersionProjects){ throw std::runtime_error("Can't load the project file, it is from an incompatible version. Probably newer?"); } } namespace pugiIdentChars { const pugi::char_t* getIdentCharaterForEnum(const UtilFRequest::IdentCharacter identEnum){ switch(identEnum){ case UtilFRequest::IdentCharacter::SPACE: { return pugiIdentChars::spaceChar; } case UtilFRequest::IdentCharacter::TAB: { return pugiIdentChars::tabChar; } default: { QString errorMessage = "UtilFRequest::IdentCharacter type unknown: '" + QString::number(static_cast(identEnum)) + "'. Program can't proceed."; Util::Dialogs::showError(errorMessage); LOG_FATAL << errorMessage; exit(1); } } } } ================================================ FILE: XmlParsers/projectfilefrequest.h ================================================ /* * 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 . * */ #ifndef PROJECTFILEFREQUEST_H #define PROJECTFILEFREQUEST_H #include #include #include "utilfrequest.h" #include "Authentications/requestauthentication.h" #include "Authentications/basicauthentication.h" class ProjectFileFRequest { public: struct ProjectData{ QString projectName; QString mainUrl; QVector projectRequests; QString projectUuid; std::shared_ptr authData = nullptr; bool retryLoginIfError401 = false; UtilFRequest::IdentCharacter saveIdentCharacter; QVector globalHeaders; }; public: ProjectFileFRequest() = delete; static ProjectFileFRequest::ProjectData readProjectDataFromFile(const QString &fileFullPath); static void saveProjectDataToFile(const QString &fileFullPath, const ProjectData &newProjectData, const QVector &uuidsToCleanUp); private: static pugi::xml_attribute createOrGetPugiXmlAttribute(pugi::xml_node &mainNode, const char *name); static void upgradeProjectFileIfNecessary(const QString &filePath); }; namespace pugiIdentChars { static constexpr pugi::char_t spaceChar[] = PUGIXML_TEXT(" "); // we use 4 spaces as default static constexpr pugi::char_t tabChar[] = PUGIXML_TEXT("\t"); const pugi::char_t* getIdentCharaterForEnum(const UtilFRequest::IdentCharacter identEnum); } #endif // PROJECTFILEFREQUEST_H ================================================ FILE: about.cpp ================================================ /* * 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 . * */ #include "about.h" #include "ui_about.h" About::About(QWidget *parent) : QDialog(parent), ui(new Ui::About) { ui->setupUi(this); this->setAttribute(Qt::WA_DeleteOnClose,true ); //destroy itself once finished. ui->lbAbout->setText("" "

" + GlobalVars::AppName + " " + GlobalVars::AppVersion + "

" "

" "Written by Fábio Bento (fabiobento512)

" "Build Date " + __DATE__ + " " + __TIME__ + "

" "Thanks to:

" "Main contributors:
" "Alejandro Valdés (alevalv) for global headers feature
" "fcolecumberri for scrollable area for request and response areas
" "
" "Libraries contributors:
" "Arseny Kapoulkine and the remaining contributors for pugixml library
" "Andrzej Krzemienski and the remaining contributors for C++14 optional library
" "Sergey Podobry and the remaining contributors for plog library
" "Jane G. (isomoar) for the JSON syntax highlighter (from SchemaBasedJSONEditor)
" "Dmitry Ivanov for the XML syntax highlighter (from SchemaBasedJSONEditor)
" "
" "UI contributors:
" "Jürgen Skrotzky (Jorgen-VikingGod) for the Dark Theme
" "Murakumon for project folder icon (found in findicons.com)
" "Woothemes for application icon (found in findicons.com)
" "ana nirwana for send request icon (found in iconfinder.com)
" "Omercetin for clipboard icon (found in iconfinder.com) (license)
" "Icons8 for clone icon (found in here) (license)
" "Aha-Soft Team for abort icon (found in findicons.com)
" "FatCow Web Hosting for warning icon (found in iconfinder.com) (license)
" "Icons8 for delete icon (found in here) (license)" "
" + R"(


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/. )" + "

" ""); // Don't use rich text in qtdesigner because it generates platform dependent code ui->lbCommunity->setText("" "

" "

" "Visit FRequest website
" "or the github project
" "
" "

" "" ); } About::~About() { delete ui; } void About::on_pushButton_clicked() { this->close(); } ================================================ FILE: about.h ================================================ /* * 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 . * */ #ifndef ABOUT_H #define ABOUT_H #include #include "utilglobalvars.h" namespace Ui { class About; } class About : public QDialog { Q_OBJECT public: explicit About(QWidget *parent = 0); ~About(); private slots: void on_pushButton_clicked(); private: Ui::About *ui; }; #endif // ABOUT_H ================================================ FILE: about.ui ================================================ About 0 0 600 480 0 0 About FRequest 0 0 180 0 :/icons/frequest_icon.png true 0 0 true 0 0 390 363 0 0 0 0 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">FRequest</span> </p> <p style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Written by Fábio Bento<br /><br />Thanks to:<br />Edit in About.cpp</p></body></html> Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop true true Qt::Vertical QSizePolicy::Fixed 20 10 <html><head/><body><p align="center">Github:<br/><a href="http://oni.bungie.org"><span style=" text-decoration: underline; color:#0000ff;">github.com </span></a></p></body></html> true true Qt::Vertical QSizePolicy::Fixed 20 10 Qt::Horizontal 40 20 100 0 Close ================================================ FILE: credits.txt ================================================ libs: json syntax highligher: https://github.com/isomoar/json-editor/blob/master/syntaxhighlightening/highlighter.cpp pugixml c++17 optional plog basic xml highlighter (Dmitry Ivanov https://github.com/d1vanov/basic-xml-syntax-highlighter) ----------- icons: project folder: http://findicons.com/icon/173045/projects_folder frequest icon: http://findicons.com/icon/69518/web_search send icon: https://www.iconfinder.com/icons/1214637/email_envelope_letter_mail_message_send_sent_icon#size=128 copy clipboard: https://www.iconfinder.com/icons/56070/clipboard_icon#size=32 files icon (modified): https://www.iconfinder.com/icons/905572/blanc_documents_file_page_plus_sheet_icon#size=32 warning icon: https://www.iconfinder.com/icons/36026/error_hazard_pending_warning_icon#size=32 abort icon (Aha-Soft Team, Freeware): http://findicons.com/icon/219146/close clone icon (see license here: https://icons8.com/license/): https://icons8.com/icon/set/sheep/all delete icon (see license here: https://icons8.com/license/): https://icons8.com/icon/set/delete/all dark theme: Jürgen Skrotzky (Jorgen-VikingGod) https://github.com/Jorgen-VikingGod/Qt-Frameless-Window-DarkStyle dark orange theme (currently unused, maybe in the future): http://discourse.techart.online/t/release-qt-dark-orange-stylesheet/2287 ================================================ FILE: main.cpp ================================================ /* * 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 . * */ #include "mainwindow.h" #include int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); a.setStyleSheet("QStatusBar::item { border: 0px; }"); //hide borders in status bar //http://qt-project.org/forums/viewthread/18743 return a.exec(); } ================================================ FILE: mainwindow.cpp ================================================ /* * 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 . * */ #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 #include #include #include #include #include #include #include #include #include #include #include #include #include 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> 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() << 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 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(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(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::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 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(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 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& requestHeaders ) { std::unique_ptr httpRequest = nullptr; switch(requestType){ case UtilFRequest::RequestType::GET_OPTION: { httpRequest = std::make_unique(&this->networkAccessManager, fullPath, requestHeaders); break; } case UtilFRequest::RequestType::POST_OPTION: { httpRequest = std::make_unique(&this->networkAccessManager, ui->twRequestBodyKeyValue, fullPath , bodyType, requestBody, requestHeaders); break; } case UtilFRequest::RequestType::PUT_OPTION: { httpRequest = std::make_unique(&this->networkAccessManager, ui->twRequestBodyKeyValue, fullPath , bodyType, requestBody, requestHeaders); break; } case UtilFRequest::RequestType::DELETE_OPTION: { httpRequest = std::make_unique(&this->networkAccessManager, fullPath, requestHeaders); break; } case UtilFRequest::RequestType::PATCH_OPTION: { httpRequest = std::make_unique(&this->networkAccessManager, ui->twRequestBodyKeyValue, fullPath , bodyType, requestBody, requestHeaders); break; } case UtilFRequest::RequestType::HEAD_OPTION: { httpRequest = std::make_unique(&this->networkAccessManager, fullPath, requestHeaders); break; } case UtilFRequest::RequestType::TRACE_OPTION: { httpRequest = std::make_unique(&this->networkAccessManager, ui->twRequestBodyKeyValue, fullPath , bodyType, requestBody, requestHeaders); break; } case UtilFRequest::RequestType::OPTIONS_OPTION: { httpRequest = std::make_unique(&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 selectedRows = QList(); for(const QModelIndex &rowItem : myTree->selectionModel()->selectedRows()){ selectedRows << rowItem.row(); } std::unique_ptr menu = std::make_unique(); // Project actions only std::unique_ptr openProjectLocation = nullptr; std::unique_ptr projectProperties = nullptr; // Requests actions only std::unique_ptr cloneRequest = nullptr; std::unique_ptr moveRequestUp = nullptr; std::unique_ptr moveRequestDown = nullptr; std::unique_ptr deleteRequest = nullptr; // Common actions std::unique_ptr addNewRequest = std::make_unique("Add new request", myTree); std::unique_ptr renameItem = nullptr; if(ui->treeWidget->currentItem() == this->currentProjectItem){ // Project renameItem = std::make_unique("Rename project", myTree); openProjectLocation = std::make_unique("Open project location", myTree); menu->addAction(openProjectLocation.get()); menu->addSeparator(); menu->addAction(addNewRequest.get()); menu->addAction(renameItem.get()); menu->addSeparator(); projectProperties = std::make_unique("Project properties", myTree); menu->addAction(projectProperties.get()); } else{ // Requests renameItem = std::make_unique("Rename request", myTree); menu->addAction(addNewRequest.get()); menu->addAction(renameItem.get()); cloneRequest = std::make_unique(QIcon(":/icons/clone_icon.png"), "Clone request", myTree); menu->addAction(cloneRequest.get()); menu->addSeparator(); moveRequestUp = std::make_unique("Move up", myTree); menu->addAction(moveRequestUp.get()); moveRequestDown = std::make_unique("Move down", myTree); menu->addAction(moveRequestDown.get()); menu->addSeparator(); deleteRequest = std::make_unique(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(currentFRequestItem)); } } if(previous != nullptr){ previousFRequestItem = FRequestTreeWidgetItem::fromQTreeWidgetItem(previous); } // Save previous item if(previousFRequestItem != nullptr && !previousFRequestItem->isProjectItem) { updateTreeWidgetItemContent(static_cast(previousFRequestItem)); } // Update window for new item if(currentFRequestItem != nullptr){ if(!currentFRequestItem->isProjectItem){ this->currentItem = static_cast(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 FRequestTreeWidgetRequestItem * const newItemRequest = static_cast(newItem); if(item->text(0) != newItemRequest->itemContent.name){ updateTreeWidgetItemContent(newItemRequest); // update request content updateInterface = true; } } else{ // Project FRequestTreeWidgetProjectItem * const newItemProject = static_cast(newItem); if(item->text(0) != newItemProject->projectName){ newItemProject->projectName = item->text(0); // update project name updateInterface = true; } } if(updateInterface){ // Set item tooltip (same as text) item->setToolTip(0, item->text(0)); updateWindowTitle(); } } void MainWindow::updateWindowTitle(){ // using QStringBuilder concatenation method: // https://wiki.qt.io/Using_QString_Effectively QString fRequestTitle; if(this->lastProjectFilePath.isEmpty()){ fRequestTitle = fRequestTitle % "Untitled"; } else{ fRequestTitle = fRequestTitle % Util::FileSystem::cutNameWithoutBackSlash(this->lastProjectFilePath); } fRequestTitle = fRequestTitle % " - " % this->currentProjectItem->projectName; if(this->currentItem != nullptr){ fRequestTitle = fRequestTitle % "/" % this->currentItem->text(0); } fRequestTitle = fRequestTitle % " - " % GlobalVars::AppName % " " % GlobalVars::AppVersion; if(this->unsavedChangesExist){ fRequestTitle = fRequestTitle % "*"; } setWindowTitle(fRequestTitle); } FRequestTreeWidgetProjectItem* MainWindow::addProjectItem(const QString &projectName, const QString &projectUuid){ FRequestTreeWidgetProjectItem *projectFolder = new FRequestTreeWidgetProjectItem(QStringList() << projectName, projectUuid); projectFolder->setIcon(0, QIcon(":/icons/projects_folder_icon.png")); projectFolder->setToolTip(0, projectFolder->text(0)); projectFolder->setFlags(projectFolder->flags() | Qt::ItemIsEditable); ui->treeWidget->addTopLevelItem(projectFolder); projectFolder->setExpanded(true); return projectFolder; } FRequestTreeWidgetRequestItem* MainWindow::addRequestItem(const QString &requestName, const QString &projectUuid, FRequestTreeWidgetProjectItem * const currentProject){ FRequestTreeWidgetRequestItem *newRequest = new FRequestTreeWidgetRequestItem(QStringList() << requestName, projectUuid); newRequest->setToolTip(0, newRequest->text(0)); newRequest->setFlags((newRequest->flags() | Qt::ItemIsEditable) ^ Qt::ItemIsDropEnabled); // don't allow drop inside another items currentProject->addRequestItemChild(newRequest); return newRequest; } void MainWindow::setIconForRequest(FRequestTreeWidgetRequestItem * const item){ if(this->generatedIconCache.contains(item->itemContent.requestType)){ item->setIcon(0, this->generatedIconCache.value(item->itemContent.requestType)); } else{ // generate the necessary icon and add it to our cache QPixmap myIcon(48,16); myIcon.fill(Qt::transparent); QPainter painter( &myIcon ); painter.setFont(item->font(0)); QString textToDraw; std::unique_ptr colorToDraw; switch(item->itemContent.requestType){ case UtilFRequest::RequestType::GET_OPTION:{ textToDraw = "GET"; colorToDraw = std::make_unique(0x0066ff); break; } case UtilFRequest::RequestType::POST_OPTION:{ textToDraw = "POST"; colorToDraw = std::make_unique(Qt::darkGreen); break; } case UtilFRequest::RequestType::PUT_OPTION:{ textToDraw = "PUT"; colorToDraw = std::make_unique(0xFFAD00); break; } case UtilFRequest::RequestType::DELETE_OPTION:{ textToDraw = "DEL"; colorToDraw = std::make_unique(Qt::red); break; } case UtilFRequest::RequestType::PATCH_OPTION:{ textToDraw = "PTCH"; colorToDraw = std::make_unique(Qt::magenta); break; } case UtilFRequest::RequestType::HEAD_OPTION:{ textToDraw = "HEAD"; colorToDraw = std::make_unique(0x4EC995); break; } case UtilFRequest::RequestType::TRACE_OPTION:{ textToDraw = "TRCE"; colorToDraw = std::make_unique(Qt::darkYellow); break; } case UtilFRequest::RequestType::OPTIONS_OPTION:{ textToDraw = "OPT"; colorToDraw = std::make_unique(Qt::darkGray); break; } default:{ const QString errorMessage = "Couldn't set icon for request " + item->text(0) + " unknown request type: " + QString::number(static_cast(item->itemContent.requestType)); LOG_ERROR << errorMessage; Util::Dialogs::showError(errorMessage); return; } } painter.setPen(*colorToDraw); painter.drawText( QRect(0, 0, myIcon.width(), myIcon.height()), Qt::AlignCenter, textToDraw ); item->setIcon(0, *this->generatedIconCache.insert(item->itemContent.requestType, QIcon(myIcon))); } } void MainWindow::setNewProject(){ if(this->unsavedChangesExist){ QMessageBox::StandardButton result = askToSaveCurrentProject(); if(result == QMessageBox::StandardButton::Cancel){ return; } } this->ignoreAnyChangesToProject.SetCondition(); clearEverything(); FRequestTreeWidgetProjectItem *projectFolder = addProjectItem("New Project", getNewUuid()); FRequestTreeWidgetRequestItem *newRequest = addRequestItem("New Request", getNewUuid(), projectFolder); newRequest->setSelected(true); this->currentProjectItem = projectFolder; this->currentItem = newRequest; this->currentProjectItem->projectName = projectFolder->text(0); // Necessary in order to currentIndexChanged to work correctly (select it is not enough) ui->treeWidget->setCurrentItem(newRequest); this->lastProjectFilePath = QString(); if(this->currentSettings.defaultHeaders.useDefaultHeaders){ addDefaultHeaders(); } this->unsavedChangesExist = false; updateWindowTitle(); // it doesn't get called automatically here this->ignoreAnyChangesToProject.UnsetCondition(); } QVector MainWindow::getRequestHeaders(){ QVector requestHeaders; for(int i = 0; i < ui->twRequestHeadersKeyValue->rowCount(); i++){ if (!UtilFRequest::isGlobalHeaderTableWidgetRow(ui->twRequestHeadersKeyValue, i)) { UtilFRequest::HttpHeader currentHeader; currentHeader.name = ui->twRequestHeadersKeyValue->item(i, 0)->text(); currentHeader.value = ui->twRequestHeadersKeyValue->item(i, 1)->text(); requestHeaders.append(currentHeader); } } return requestHeaders; } QVector MainWindow::getRequestForm(){ QVector requestForm; for(int i = 0; i < ui->twRequestBodyKeyValue->rowCount(); i++){ // TODO use enum for index UtilFRequest::HttpFormKeyValueType currentFormKeyValue( ui->twRequestBodyKeyValue->item(i, 0)->text(), ui->twRequestBodyKeyValue->item(i, 1)->text(), UtilFRequest::getFormKeyTypeByString(ui->twRequestBodyKeyValue->item(i, 2)->text()) ); requestForm.append(currentFormKeyValue); } return requestForm; } void MainWindow::updateTreeWidgetItemContent(FRequestTreeWidgetRequestItem * const requestItem){ requestItem->itemContent.name = requestItem->text(0); requestItem->itemContent.path = ui->lePath->text(); requestItem->itemContent.bOverridesMainUrl = ui->cbRequestOverrideMainUrl->isChecked(); requestItem->itemContent.overrideMainUrl = ui->leRequestOverrideMainUrl->text(); requestItem->itemContent.bDisableGlobalHeaders = ui->cbDisableGlobalHeaders->isChecked(); requestItem->itemContent.headers = getRequestHeaders(); requestItem->itemContent.order = requestItem->parent()->indexOfChild(requestItem); requestItem->itemContent.bodyType = UtilFRequest::getBodyTypeByString(ui->cbBodyType->currentText()); switch(requestItem->itemContent.bodyType){ case UtilFRequest::BodyType::RAW: { requestItem->itemContent.body = ui->pteRequestBody->toPlainText(); break; } case UtilFRequest::BodyType::FORM_DATA: { requestItem->itemContent.bodyForm = getRequestForm(); break; } case UtilFRequest::BodyType::X_FORM_WWW_URLENCODED: { requestItem->itemContent.bodyForm = getRequestForm(); break; } default: { const QString errorMessage = "Invalid body type " + QString::number(static_cast(requestItem->itemContent.bodyType)) + "'. Program can't proceed."; Util::Dialogs::showError(errorMessage); LOG_FATAL << errorMessage; exit(1); } } requestItem->itemContent.requestType = UtilFRequest::getRequestTypeByString(ui->cbRequestType->currentText()); requestItem->itemContent.bDownloadResponseAsFile = ui->cbDownloadResponseAsFile->isChecked(); } void MainWindow::saveProjectState(const QString &filePath) { // Make sure the current request is updated in memory if(this->currentItem != nullptr){ updateTreeWidgetItemContent(this->currentItem); } try{ ProjectFileFRequest::saveProjectDataToFile(filePath, fetchCurrentProjectData(), this->uuidsToCleanUp); this->currentSettings.lastProjectPath = QFileInfo(filePath).absoluteDir().path(); this->lastProjectFilePath = filePath; this->uuidsToCleanUp.clear(); this->unsavedChangesExist = false; addNewRecentProject(filePath); updateWindowTitle(); Util::StatusBar::showSuccess(ui->statusBar, "Project saved with success!"); } catch(const std::exception& e){ const QString errorMessage = QString("Couldn't save project file. Save aborted.\n") + e.what(); LOG_ERROR << errorMessage; Util::Dialogs::showError(errorMessage); Util::StatusBar::showError(ui->statusBar, "Couldn't save project file."); } } void MainWindow::loadProjectState(const QString &filePath) { if(this->unsavedChangesExist){ QMessageBox::StandardButton result = askToSaveCurrentProject(); if(result == QMessageBox::StandardButton::Cancel){ return; } } // Prepare for project loading this->ignoreAnyChangesToProject.SetCondition(); try{ std::unique_ptr projectData = std::make_unique(ProjectFileFRequest::readProjectDataFromFile(filePath)); clearEverything(); this->currentProjectItem = addProjectItem(projectData->projectName, projectData->projectUuid); this->currentProjectItem->projectName = projectData->projectName; this->currentProjectItem->projectMainUrl = projectData->mainUrl; this->currentProjectItem->authData = projectData->authData; this->currentProjectItem->saveIdentCharacter = projectData->saveIdentCharacter; this->currentProjectItem->globalHeaders = projectData->globalHeaders; // Order them by the correct order std::sort( projectData->projectRequests.begin(), projectData->projectRequests.end(), [](const UtilFRequest::RequestInfo &first, const UtilFRequest::RequestInfo &second){ return first.order < second.order; } ); // Now the items are in the correct order, we can now load them in the interface for(int i=0; iprojectRequests.size(); i++){ UtilFRequest::RequestInfo ¤tRequestInfo = projectData->projectRequests[i]; // fix order currentRequestInfo.order = i; FRequestTreeWidgetRequestItem *currRequest = addRequestItem(currentRequestInfo.name, currentRequestInfo.uuid, this->currentProjectItem); currRequest->itemContent = currentRequestInfo; if(ui->actionShow_Request_Types_Icons->isChecked()){ setIconForRequest(currRequest); } // Load first request if(i==0){ reloadRequest(currRequest); ui->treeWidget->setCurrentItem(currRequest); this->currentItem = currRequest; } } // All items loaded, finally check if we don't have an authentication yet. // If we don't, check if it is present in config file and load it from there if(this->currentProjectItem->authData == nullptr && this->currentSettings.mapOfConfigAuths_UuidToConfigAuth.contains(this->currentProjectItem->getUuid())){ // Project has auth data in config file, load it this->currentProjectItem->authData = this->currentSettings.mapOfConfigAuths_UuidToConfigAuth.value(this->currentProjectItem->getUuid()).authData; } this->currentSettings.lastProjectPath = QFileInfo(filePath).absoluteDir().path(); this->lastProjectFilePath = filePath; this->unsavedChangesExist = false; this->currentProjectAuthenticationWasMade = false; addNewRecentProject(filePath); updateWindowTitle(); Util::StatusBar::showSuccess(ui->statusBar, "Project loaded successfully."); } catch(const std::exception& e){ const QString errorMessage = "Couldn't load the FRequest project. Error: " + QString(e.what()); LOG_ERROR << errorMessage; Util::Dialogs::showError(errorMessage); Util::StatusBar::showError(ui->statusBar, "Couldn't load project."); } this->ignoreAnyChangesToProject.UnsetCondition(); } ProjectFileFRequest::ProjectData MainWindow::fetchCurrentProjectData(){ ProjectFileFRequest::ProjectData currentProjectData; currentProjectData.projectName = this->currentProjectItem->projectName; currentProjectData.mainUrl = this->currentProjectItem->projectMainUrl; currentProjectData.projectUuid = this->currentProjectItem->getUuid(); currentProjectData.authData = this->currentProjectItem->authData; currentProjectData.saveIdentCharacter = this->currentProjectItem->saveIdentCharacter; currentProjectData.globalHeaders = this->currentProjectItem->globalHeaders; // Save by the current tree order for(int i=0; icurrentProjectItem->childCount(); i++){ UtilFRequest::RequestInfo ¤tRequest = FRequestTreeWidgetRequestItem::fromQTreeWidgetItem(this->currentProjectItem->child(i))->itemContent; currentRequest.order = i; currentProjectData.projectRequests.append(currentRequest); } return currentProjectData; } void MainWindow::on_actionNew_Project_triggered() { setNewProject(); } void MainWindow::on_actionSave_Project_triggered() { if(this->lastProjectFilePath.isEmpty()){ on_actionSave_Project_As_triggered(); return; } saveProjectState(this->lastProjectFilePath); } void MainWindow::on_actionSave_Project_As_triggered() { QString filePath = QFileDialog::getSaveFileName(this, tr("Save File"), this->currentSettings.lastProjectPath, tr("FRequest project files (*.frp)")); if(!filePath.isEmpty()){ saveProjectState(filePath); } } void MainWindow::on_actionLoad_Project_triggered() { QString filePath = QFileDialog::getOpenFileName(this, tr("Load File"), this->currentSettings.lastProjectPath, tr("FRequest project files (*.frp)")); if(!filePath.isEmpty()){ loadProjectState(filePath); } } void MainWindow::on_actionExit_triggered() { this->close(); } void MainWindow::on_actionAbout_triggered() { //Show about dialog (new About(this))->show(); //it destroys itself when finished. } void MainWindow::on_actionProject1_triggered() { loadProjectState(this->ui->actionProject1->text()); } void MainWindow::on_actionProject2_triggered() { loadProjectState(this->ui->actionProject2->text()); } void MainWindow::on_actionProject3_triggered() { loadProjectState(this->ui->actionProject3->text()); } void MainWindow::on_actionProject4_triggered() { loadProjectState(this->ui->actionProject4->text()); } void MainWindow::on_actionProject5_triggered() { loadProjectState(this->ui->actionProject5->text()); } void MainWindow::on_actionProject6_triggered() { loadProjectState(this->ui->actionProject6->text()); } void MainWindow::on_actionFormat_Response_Body_triggered() { formatResponseBody(getResponseCurrentSerializationFormatType()); } void MainWindow::on_actionFormat_Request_body_triggered() { this->ignoreAnyChangesToProject.SetCondition(); formatRequestBody(getRequestCurrentSerializationFormatType()); this->ignoreAnyChangesToProject.UnsetCondition(); } void MainWindow::reloadRequest(FRequestTreeWidgetRequestItem* const item){ this->ignoreAnyChangesToProject.SetCondition(); UtilFRequest::RequestInfo info = item->itemContent; // Clear old contents clearRequestAndResponse(); ui->lePath->setText(info.path); ui->cbRequestOverrideMainUrl->setChecked(info.bOverridesMainUrl); ui->leRequestOverrideMainUrl->setText(info.overrideMainUrl); ui->cbDisableGlobalHeaders->setChecked(info.bDisableGlobalHeaders); setRequestType(info.requestType); // Aux lambda to avoid duplicated code for FORM_DATA / X_FORM_WWW_URLENCODED auto fFillRequestBodyKeyValueTable = [](const QVector &bodyForm, QTableWidget * const table){ for(const UtilFRequest::HttpFormKeyValueType &currFormKeyValue : bodyForm){ UtilFRequest::addRequestFormBodyRow(table, currFormKeyValue.key, currFormKeyValue.value, currFormKeyValue.type); } }; ui->cbBodyType->setCurrentText(UtilFRequest::getBodyTypeString(info.bodyType)); switch(info.bodyType){ case UtilFRequest::BodyType::RAW: { ui->pteRequestBody->setPlainText(info.body); break; } case UtilFRequest::BodyType::FORM_DATA: { fFillRequestBodyKeyValueTable(info.bodyForm, ui->twRequestBodyKeyValue); break; } case UtilFRequest::BodyType::X_FORM_WWW_URLENCODED: { fFillRequestBodyKeyValueTable(info.bodyForm, ui->twRequestBodyKeyValue); break; } default: { const QString errorMessage = "Invalid body type " + QString::number(static_cast(info.bodyType)) + "'. Program can't proceed."; Util::Dialogs::showError(errorMessage); LOG_FATAL << errorMessage; exit(1); } } formatRequestBody(getRequestCurrentSerializationFormatType()); addGlobalHeaders(); for(const UtilFRequest::HttpHeader ¤tHeader : info.headers){ Util::TableWidget::addRow(ui->twRequestHeadersKeyValue, QStringList() << currentHeader.name << currentHeader.value); } ui->cbDownloadResponseAsFile->setChecked(info.bDownloadResponseAsFile); this->ignoreAnyChangesToProject.UnsetCondition(); } void MainWindow::clearOlderResponse(){ this->lastReplyStatusError = 0; ui->lbResponseBodyWarningIcon->hide(); ui->lbResponseBodyWarningMessage->hide(); ui->pteResponseBody->clear(); ui->pteResponseHeaders->clear(); ui->lbStatus->clear(); ui->lbDescription->clear(); ui->lbTimeElapsed->clear(); } void MainWindow::clearRequestAndResponse(){ ui->leRequestOverrideMainUrl->clear(); ui->cbRequestOverrideMainUrl->setChecked(false); ui->lePath->clear(); ui->leFullPath->clear(); ui->cbRequestType->setCurrentText("GET"); ui->cbBodyType->setCurrentIndex(0); ui->cbResponseChooseHeader->setCurrentIndex(0); ui->pteRequestBody->clear(); Util::TableWidget::clearContentsNoPrompt(ui->twRequestBodyKeyValue); Util::TableWidget::clearContentsNoPrompt(ui->twRequestHeadersKeyValue); ui->cbDownloadResponseAsFile->setChecked(false); clearOlderResponse(); } void MainWindow::clearEverything(){ // order is important // (we should clear the pointers first, because clearing tree widgets // will then call update title that will try to access pointer to unexisting objects) this->uuidsInUse.clear(); this->uuidsToCleanUp.clear(); this->currentItem = nullptr; this->currentProjectItem = nullptr; ui->treeWidget->clear(); ui->leRequestsFilter->clear(); clearRequestAndResponse(); } void MainWindow::on_cbResponseChooseHeader_currentIndexChanged(const QString &arg1) { if(arg1 == "Content-type: application/json"){ Util::TableWidget::addRow(ui->twRequestHeadersKeyValue, QStringList() << "Content-type" << "application/json"); } else if(arg1 == "Content-type: application/xml"){ Util::TableWidget::addRow(ui->twRequestHeadersKeyValue, QStringList() << "Content-type" << "application/xml"); } else if(arg1 == "Content-type: multipart/form-data"){ Util::TableWidget::addRow(ui->twRequestHeadersKeyValue, QStringList() << "Content-type" << "multipart/form-data"); } else if(arg1 == "Content-type: application/x-www-form-urlencoded"){ Util::TableWidget::addRow(ui->twRequestHeadersKeyValue, QStringList() << "Content-type" << "application/x-www-form-urlencoded"); } ui->cbResponseChooseHeader->setCurrentIndex(0); } void MainWindow::closeEvent(QCloseEvent *event){ if(this->unsavedChangesExist){ QMessageBox::StandardButton result = askToSaveCurrentProject(); if(result == QMessageBox::StandardButton::Cancel){ event->ignore(); return; } } if(this->currentSettings.windowsGeometry.saveWindowsGeometryWhenExiting){ this->currentSettings.windowsGeometry.mainWindow_MainWindowGeometry = this->saveGeometry(); this->currentSettings.windowsGeometry.mainWindow_RequestsSplitterState = ui->splitter->saveState(); this->currentSettings.windowsGeometry.mainWindow_RequestResponseSplitterState = ui->splitter_2->saveState(); } // Save unsaved settings saveCurrentSettings(); // Exit application (this will also close all other windows which don't have parent) QApplication::quit(); } void MainWindow::loadRecentProjects(){ for(const QString ¤tRecentPath : this->currentSettings.recentProjectsPaths){ recentProjectsList.append(currentRecentPath); } reloadRecentProjectsMenu(); } void MainWindow::addNewRecentProject(const QString &filePath){ // If the new project is equal to the last one simply ignore if(this->currentSettings.recentProjectsPaths.size() > 0 && filePath == this->currentSettings.recentProjectsPaths[0]){ return; } // If the item already exists in our list remove it, so it can go to the top again for(auto it = this->recentProjectsList.begin(); it != this->recentProjectsList.end();){ if(*it == filePath){ it = this->recentProjectsList.erase(it); } else{ it++; } } // if we gonna overflow our list, remove the older item to reserve space to the new one if(this->recentProjectsList.size()==GlobalVars::AppRecentProjectsMaxSize){ this->recentProjectsList.removeLast(); } this->currentSettings.lastProjectPath = QFileInfo(filePath).absoluteDir().path(); // add new recent file this->recentProjectsList.prepend(filePath); reloadRecentProjectsMenu(); saveRecentProjects(); } void MainWindow::reloadRecentProjectsMenu(){ ui->menuRecent_Projects->setEnabled(false); ui->actionProject1->setVisible(false); ui->actionProject2->setVisible(false); ui->actionProject3->setVisible(false); ui->actionProject4->setVisible(false); ui->actionProject5->setVisible(false); ui->actionProject6->setVisible(false); { QList::const_iterator it; int i; for(it = recentProjectsList.cbegin(), i=0; it != recentProjectsList.cend(); it++, i++){ QAction* currAction = nullptr; switch (i){ case 0: currAction = ui->actionProject1; break; case 1: currAction = ui->actionProject2; break; case 2: currAction = ui->actionProject3; break; case 3: currAction = ui->actionProject4; break; case 4: currAction = ui->actionProject5; break; case 5: currAction = ui->actionProject6; break; } if(currAction){ ui->menuRecent_Projects->setEnabled(true); currAction->setText(*it); currAction->setVisible(true); } } } } void MainWindow::saveRecentProjects(){ this->currentSettings.recentProjectsPaths = recentProjectsList.toVector(); } void MainWindow::on_tbRequestHeadersKeyValueAdd_clicked() { Util::TableWidget::addRow(ui->twRequestHeadersKeyValue, QStringList() << "" << ""); } void MainWindow::on_tbRequestHeadersKeyValueRemove_clicked() { int size = Util::TableWidget::getSelectedRows(ui->twRequestHeadersKeyValue).size(); if(size==0){ Util::Dialogs::showInfo("Select a row first!"); return; } if(Util::Dialogs::showQuestion(this, "Are you sure you want to remove all selected rows?")){ for(int i=0; i < size; i++){ ui->twRequestHeadersKeyValue->removeRow(Util::TableWidget::getSelectedRows(ui->twRequestHeadersKeyValue).at(size-i-1).row()); } Util::StatusBar::showSuccess(ui->statusBar, "Key-Value rows deleted"); } } void MainWindow::on_twRequestHeadersKeyValue_cellChanged(int row, int column) { setProjectHasChanged(); if(!ui->twRequestHeadersKeyValue->item(row, column)->text().trimmed().isEmpty()){ ui->twRequestHeadersKeyValue->resizeColumnsToContents(); } } void MainWindow::on_tbRequestBodyKeyValueAdd_clicked() { UtilFRequest::addRequestFormBodyRow(ui->twRequestBodyKeyValue, "", "", UtilFRequest::FormKeyValueType::TEXT); } void MainWindow::on_tbRequestBodyFile_clicked() { QString filePath = QFileDialog::getOpenFileName(this, tr("Choose a file to upload")); // Only add a row if a file was selected if(!filePath.isEmpty()){ UtilFRequest::addRequestFormBodyRow(ui->twRequestBodyKeyValue, "", filePath, UtilFRequest::FormKeyValueType::FILE); } } void MainWindow::on_tbRequestBodyKeyValueRemove_clicked() { int size = Util::TableWidget::getSelectedRows(ui->twRequestBodyKeyValue).size(); if(size==0){ Util::Dialogs::showInfo("Select a row first!"); return; } if(Util::Dialogs::showQuestion(this, "Are you sure you want to remove all selected rows?")){ for(int i=0; i < size; i++){ ui->twRequestBodyKeyValue->removeRow(Util::TableWidget::getSelectedRows(ui->twRequestBodyKeyValue).at(size-i-1).row()); } Util::StatusBar::showSuccess(ui->statusBar, "Key-Value rows deleted"); } } void MainWindow::on_twRequestBodyKeyValue_cellChanged(int row, int column) { setProjectHasChanged(); // TODO use column enums if(column != 1 && !ui->twRequestBodyKeyValue->item(row, column)->text().trimmed().isEmpty()){ ui->twRequestBodyKeyValue->resizeColumnToContents(column); } } void MainWindow::on_cbBodyType_currentIndexChanged(const QString &arg1) { auto fSetBodyKeyValuesTableVisibility = [=](const bool &isVisible){ ui->twRequestBodyKeyValue->setVisible(isVisible); ui->tbRequestBodyKeyValueAdd->setVisible(isVisible); ui->tbRequestBodyFile->setVisible(isVisible); ui->tbRequestBodyKeyValueRemove->setVisible(isVisible); }; // Files are only allowed in form-data, so we need to remove them if the user is changing to something else // Before removing them ask the user if that is ok if(!this->ignoreAnyChangesToProject.ConditionIsSet() && arg1 != "form-data" && formKeyValueInBodyHasFiles()){ // revert to form data and don't do more anything if user doesn't approve files rows deletion if(Util::Dialogs::showQuestionWithCancel(this, "You have files rows in the form, changing to " + arg1 + " will REMOVE these files rows. Proceed?") != QMessageBox::Yes){ this->ignoreAnyChangesToProject.SetCondition(); ui->cbBodyType->setCurrentText("form-data"); this->ignoreAnyChangesToProject.UnsetCondition(); return; } else{ removeAllFilesRowsFromFormKeyValueInBody(); // if approved remove the files rows } } ui->pteRequestBody->hide(); fSetBodyKeyValuesTableVisibility(false); if(arg1 == "raw"){ ui->pteRequestBody->show(); } else if(arg1 == "form-data"){ fSetBodyKeyValuesTableVisibility(true); } else if(arg1 == "x-form-www-urlencoded"){ fSetBodyKeyValuesTableVisibility(true); ui->tbRequestBodyFile->setVisible(false); } if(!this->ignoreAnyChangesToProject.ConditionIsSet()){ if(ui->twRequestHeadersKeyValue->rowCount() > 0 && (QMessageBox::Yes == Util::Dialogs::showQuestionWithCancel(this, "You have changed the request body type. Delete previous headers?"))){ Util::TableWidget::clearContentsNoPrompt(ui->twRequestHeadersKeyValue); } if(this->currentSettings.defaultHeaders.useDefaultHeaders){ addDefaultHeaders(); } } } void MainWindow::on_cbRequestType_currentIndexChanged(const QString &) { // Indicates if body can be set or not depending on the given option bool toogle = UtilFRequest::requestTypeMayHaveBody(UtilFRequest::getRequestTypeByString(ui->cbRequestType->currentText())); setProjectHasChanged(); ui->cbBodyType->setEnabled(toogle); ui->twRequestBodyKeyValue->setEnabled(toogle); ui->pteRequestBody->setEnabled(toogle); ui->tbRequestBodyKeyValueAdd->setEnabled(toogle); ui->tbRequestBodyFile->setEnabled(toogle); ui->tbRequestBodyKeyValueRemove->setEnabled(toogle); // Save previous item (to update icon) if(this->currentItem != nullptr && !this->currentItem->isProjectItem) { updateTreeWidgetItemContent(this->currentItem); // Update icon if(ui->actionShow_Request_Types_Icons->isChecked()){ setIconForRequest(this->currentItem); } } if(!this->ignoreAnyChangesToProject.ConditionIsSet()){ if(ui->twRequestHeadersKeyValue->rowCount() > 0 && (QMessageBox::Yes == Util::Dialogs::showQuestionWithCancel(this, "You have changed the request type. Delete previous headers?"))){ Util::TableWidget::clearContentsNoPrompt(ui->twRequestHeadersKeyValue); } if(this->currentSettings.defaultHeaders.useDefaultHeaders){ addDefaultHeaders(); } } } void MainWindow::on_cbRequestOverrideMainUrl_toggled(bool checked) { setProjectHasChanged(); ui->leRequestOverrideMainUrl->setEnabled(checked); buildFullPath(); } void MainWindow::on_cbDisableGlobalHeaders_toggled(bool /*checked*/) { setProjectHasChanged(); } void MainWindow::on_actionShow_Request_Types_Icons_triggered(bool checked) { this->ignoreAnyChangesToProject.SetCondition(); setAllRequestIcons(checked); this->currentSettings.showRequestTypesIcons = checked; this->ignoreAnyChangesToProject.UnsetCondition(); } void MainWindow::on_actionCheck_for_updates_triggered() { // This deletes itself once finished UpdateChecker::startNewInstance(this->currentSettings); } void MainWindow::setAllRequestIcons(bool showIcon){ if(showIcon){ // Set request icons for(int i=0; icurrentProjectItem->childCount(); i++){ setIconForRequest(FRequestTreeWidgetRequestItem::fromQTreeWidgetItem(this->currentProjectItem->child(i))); } } else{ // clear request icons for(int i=0; icurrentProjectItem->childCount(); i++){ this->currentProjectItem->child(i)->setIcon(0, QIcon()); } } } void MainWindow::on_pteRequestBody_textChanged() { setProjectHasChanged(); } void MainWindow::on_cbDownloadResponseAsFile_toggled(bool) { setProjectHasChanged(); } void MainWindow::tbAbortRequest_clicked() { QString typeRequest; if(this->authenticationIsRunning){ typeRequest = "Authentication"; } else{ typeRequest = "Request"; } if(Util::Dialogs::showQuestion(this,"Are you sure you want to abort the current " + typeRequest + "?")){ if(this->currentReply.has_value()){ this->currentReply.value()->abort(); Util::StatusBar::showError(ui->statusBar, typeRequest + " was aborted."); } } } void MainWindow::setProjectHasChanged(){ if(!this->ignoreAnyChangesToProject.ConditionIsSet() && !this->unsavedChangesExist){ this->unsavedChangesExist = true; updateWindowTitle(); } } QMessageBox::StandardButton MainWindow::askToSaveCurrentProject(){ QMessageBox::StandardButton result = Util::Dialogs::showQuestionWithCancel(this,"There are unsaved changes. Do you want to save the current project?", QMessageBox::StandardButton::Yes); if(result == QMessageBox::StandardButton::Yes){ on_actionSave_Project_triggered(); } return result; } void MainWindow::on_tbCopyToClipboardRequest_clicked() { QString textToClipboard; auto fRequestFormToString = [](const QVector &requestForm){ QString result; for(int i=0; i < requestForm.size(); i++){ result = requestForm[i].key + ": " + requestForm[i].value; if(i != requestForm.size()-1){ result += "\n"; } } return result; }; auto fRequestHeadersToString = [](const QVector &requestHeaders){ QString result; for(int i=0; i < requestHeaders.size(); i++){ result = requestHeaders[i].name + ": " + requestHeaders[i].value; if(i != requestHeaders.size()-1){ result += "\n"; } } return result; }; if(ui->twRequest->tabText(ui->twRequest->currentIndex()) == "Body"){ switch(UtilFRequest::getBodyTypeByString(ui->cbBodyType->currentText())){ case UtilFRequest::BodyType::RAW: { textToClipboard = ui->pteRequestBody->toPlainText(); break; } break; case UtilFRequest::BodyType::FORM_DATA: { textToClipboard = fRequestFormToString(getRequestForm()); break; } break; case UtilFRequest::BodyType::X_FORM_WWW_URLENCODED: { textToClipboard = fRequestFormToString(getRequestForm()); break; } default: { const QString errorMessage = "Invalid body type " + QString::number(static_cast(UtilFRequest::getBodyTypeByString(ui->cbBodyType->currentText()))) + "'. Program can't proceed."; Util::Dialogs::showError(errorMessage); LOG_FATAL << errorMessage; exit(1); } } } else if(ui->twRequest->tabText(ui->twRequest->currentIndex()) == "Headers"){ textToClipboard = fRequestHeadersToString(getRequestHeaders()); } QApplication::clipboard()->setText(textToClipboard); } void MainWindow::on_tbCopyToClipboardResponse_clicked() { QString textToClipboard; if(ui->twResponse->tabText(ui->twResponse->currentIndex()) == "Body"){ textToClipboard = ui->pteResponseBody->toPlainText(); } else if(ui->twResponse->tabText(ui->twResponse->currentIndex()) == "Headers"){ textToClipboard = ui->pteResponseHeaders->toPlainText(); } QApplication::clipboard()->setText(textToClipboard); } void MainWindow::on_actionPreferences_triggered() { //Show preferences Preferences *preferencesWindow = new Preferences(this, this->currentSettings); // this is disconnected automatically once preferences object is destroyed: // https://stackoverflow.com/a/9264888/1499019 connect(preferencesWindow, SIGNAL(saveSettings()), this, SLOT(saveCurrentSettings()), Qt::ConnectionType::DirectConnection); preferencesWindow->exec(); //it destroys itself when finished. } void MainWindow::saveCurrentSettings(){ this->configFileManager.saveSettings(this->currentSettings); } void MainWindow::addDefaultHeaders(){ UtilFRequest::RequestType currentRequestType = UtilFRequest::getRequestTypeByString(ui->cbRequestType->currentText()); std::experimental::optional& currentProtocolHeader = ConfigFileFRequest::getSettingsHeaderForRequestType(currentRequestType, this->currentSettings); if(currentProtocolHeader.has_value()){ std::experimental::optional> *currentHeaders = nullptr; switch(UtilFRequest::getBodyTypeByString(ui->cbBodyType->currentText())){ case UtilFRequest::BodyType::RAW: { currentHeaders = ¤tProtocolHeader.value().headers_Raw; break; } case UtilFRequest::BodyType::FORM_DATA: { currentHeaders = ¤tProtocolHeader.value().headers_Form_Data; break; } case UtilFRequest::BodyType::X_FORM_WWW_URLENCODED: { currentHeaders = ¤tProtocolHeader.value().headers_X_form_www_urlencoded; break; } default: { const QString errorMessage = "Invalid body type " + QString::number(static_cast(UtilFRequest::getBodyTypeByString(ui->cbBodyType->currentText()))) + "'. Program can't proceed."; Util::Dialogs::showError(errorMessage); LOG_FATAL << errorMessage; exit(1); } } if(currentHeaders == nullptr){ const QString errorMessage = "An error ocurred while trying to insert the default headers. currentHeaders == nullptr"; LOG_ERROR << errorMessage; Util::Dialogs::showError(errorMessage); return; } if(currentHeaders->has_value()){ for(const UtilFRequest::HttpHeader ¤tHeader : currentHeaders->value()){ Util::TableWidget::addRow(ui->twRequestHeadersKeyValue, QStringList() << currentHeader.name << currentHeader.value); } } } } void MainWindow::setRequestType(UtilFRequest::RequestType requestType){ ui->cbRequestType->setCurrentText(UtilFRequest::getRequestTypeString(requestType)); } void MainWindow::formatRequestBody(const UtilFRequest::SerializationFormatType serializationType){ this->xmlRequestBodyHighligher.setDocument(nullptr); this->jsonRequestBodyHighligher.setDocument(nullptr); if(serializationType != UtilFRequest::SerializationFormatType::UNKNOWN){ switch(serializationType){ case UtilFRequest::SerializationFormatType::JSON: { this->jsonRequestBodyHighligher.setDocument(ui->pteRequestBody->document()); // we re-highlight immediately because we may want to ignore the change in the plain text edit // (is just formatting or re-color), this way frequest doesn't think the project was changed this->jsonRequestBodyHighligher.rehighlight(); break; } case UtilFRequest::SerializationFormatType::XML: { this->xmlRequestBodyHighligher.setDocument(ui->pteRequestBody->document()); // we re-highlight immediately because we may want to ignore the change in the plain text edit // (is just formatting or re-color), this way frequest doesn't think the project was changed this->xmlRequestBodyHighligher.rehighlight(); break; } default: { const QString errorMessage = "Invalid serializationType " + QString::number(static_cast(serializationType)) + "'. Program can't proceed."; Util::Dialogs::showError(errorMessage); LOG_FATAL << errorMessage; exit(1); } } } } void MainWindow::formatResponseBody(const UtilFRequest::SerializationFormatType serializationType){ this->xmlResponseBodyHighligher.setDocument(nullptr); this->jsonResponseBodyHighligher.setDocument(nullptr); if(serializationType != UtilFRequest::SerializationFormatType::UNKNOWN){ switch(serializationType){ case UtilFRequest::SerializationFormatType::JSON: { this->jsonResponseBodyHighligher.setDocument(ui->pteResponseBody->document()); break; } case UtilFRequest::SerializationFormatType::XML: { this->xmlResponseBodyHighligher.setDocument(ui->pteResponseBody->document()); break; } default: { const QString errorMessage = "Invalid serializationType " + QString::number(static_cast(serializationType)) + "'. Program can't proceed."; Util::Dialogs::showError(errorMessage); LOG_FATAL << errorMessage; exit(1); } } } } bool MainWindow::formKeyValueInBodyIsValid(){ for(int i = 0; i < ui->twRequestBodyKeyValue->rowCount(); i++){ // const QString &currKey = ui->twRequestBodyKeyValue->item(i,0)->text(); // ignore const QString &currValue = ui->twRequestBodyKeyValue->item(i,1)->text(); const UtilFRequest::FormKeyValueType currFormKeyValueType = UtilFRequest::getFormKeyTypeByString(ui->twRequestBodyKeyValue->item(i,2)->text()); if(currFormKeyValueType == UtilFRequest::FormKeyValueType::FILE){ if(!QFile::exists(currValue)){ const QString errorMessage = "File '" + currValue + "' doesn't exist.\n\nPlease fix it in your request body form data and try again."; Util::Dialogs::showError(errorMessage); LOG_ERROR << errorMessage; return false; } } } return true; } bool MainWindow::formKeyValueInBodyHasFiles(){ for(int i = 0; i < ui->twRequestBodyKeyValue->rowCount(); i++){ const UtilFRequest::FormKeyValueType currFormKeyValueType = UtilFRequest::getFormKeyTypeByString(ui->twRequestBodyKeyValue->item(i,2)->text()); if(currFormKeyValueType == UtilFRequest::FormKeyValueType::FILE){ return true; } } return false; } bool MainWindow::noDuplicatedKeyExistsInRequestHeaders(const QVector &headers){ // Check for duplicated headers (user error as that does not seem to be allowed by RFCs) QVector::const_iterator itDuplicatedHeader = std::adjacent_find(headers.begin(), headers.end(), [](const UtilFRequest::HttpHeader &first, const UtilFRequest::HttpHeader &second){return first.name == second.name;}); if(itDuplicatedHeader != headers.end()) { const QString errorMessage = "The header '" + itDuplicatedHeader->name + "' is duplicated in the request. This is not allowed."; Util::Dialogs::showError(errorMessage); LOG_ERROR << errorMessage; return false; } return true; } void MainWindow::removeAllFilesRowsFromFormKeyValueInBody(){ for(int i = 0; i < ui->twRequestBodyKeyValue->rowCount(); i++){ const UtilFRequest::FormKeyValueType currFormKeyValueType = UtilFRequest::getFormKeyTypeByString(ui->twRequestBodyKeyValue->item(i,2)->text()); if(currFormKeyValueType == UtilFRequest::FormKeyValueType::FILE){ ui->twRequestBodyKeyValue->selectRow(i); } } Util::TableWidget::deleteSelectedRows(ui->twRequestBodyKeyValue); } UtilFRequest::SerializationFormatType MainWindow::getRequestCurrentSerializationFormatType(){ UtilFRequest::SerializationFormatType serializationType = UtilFRequest::SerializationFormatType::UNKNOWN; if(ui->actionFormat_Request_body->isChecked()){ serializationType = UtilFRequest::getSerializationFormatTypeForString(ui->pteRequestBody->toPlainText()); } return serializationType; } UtilFRequest::SerializationFormatType MainWindow::getResponseCurrentSerializationFormatType(){ UtilFRequest::SerializationFormatType serializationType = UtilFRequest::SerializationFormatType::UNKNOWN; if(ui->actionFormat_Response_Body->isChecked()){ serializationType = UtilFRequest::getSerializationFormatTypeForString(ui->pteResponseBody->toPlainText()); } return serializationType; } QString MainWindow::getNewUuid(){ QString generatedUuid; // make sure we get a unique identifier (while very small, there it is still possible to exist collisions, // plus the xml uuid can be edited by hand by anyone) do { generatedUuid = QUuid::createUuid().toString(); } while( this->uuidsInUse.contains(generatedUuid) ); this->uuidsInUse.insert(generatedUuid); return generatedUuid; } void MainWindow::saveProjectProperties(){ // Project properties changed, we need to save the project file and maybe the configuration file (for the authentications) this->unsavedChangesExist = true; updateWindowTitle(); buildFullPath(); // project url may have been updated on_actionSave_Project_triggered(); // Do we have auth data to save? if(this->currentProjectItem->authData != nullptr){ // Assume the credentials are new, so a new authentication may need to be done this->currentProjectAuthenticationWasMade = false; // Is to save to config file? if(this->currentProjectItem->authData->saveAuthToConfigFile){ ConfigFileFRequest::ConfigurationProjectAuthentication currConfigProjAuth; currConfigProjAuth.lastProjectName = this->currentProjectItem->projectName; currConfigProjAuth.projectUuid = this->currentProjectItem->getUuid(); currConfigProjAuth.authData = this->currentProjectItem->authData; this->currentSettings.mapOfConfigAuths_UuidToConfigAuth[this->currentProjectItem->getUuid()] = currConfigProjAuth; // add or override config proj auth data saveCurrentSettings(); } else{ // Nop! We are saving to project file. In this case make sure we remove the auth data from config file if it exists if(this->currentSettings.mapOfConfigAuths_UuidToConfigAuth.contains(this->currentProjectItem->getUuid())){ this->currentSettings.mapOfConfigAuths_UuidToConfigAuth.remove(this->currentProjectItem->getUuid()); saveCurrentSettings(); } } } // necessary because global headers may have changed if(this->currentItem != nullptr) { reloadRequest(this->currentItem); } if (!this->currentSettings.hideProjectSavedDialog) { if(!this->unsavedChangesExist){ Util::Dialogs::showInfo("Project properties saved with success!"); } else{ Util::Dialogs::showWarning("Project properties weren't saved. Please save the project manually from file menu."); } } } void MainWindow::on_leRequestsFilter_textChanged(const QString &arg1) { QString trimmedFilter = arg1.trimmed(); setFilterThemePalette(); if(trimmedFilter.isEmpty()){ // if filter is empty ui->treeWidget->headerItem()->setText(0, "Requests"); if(this->currentProjectItem != nullptr){ for(int i=0; icurrentProjectItem->childCount(); i++){ this->currentProjectItem->child(i)->setHidden(false); } } } else{ ui->treeWidget->headerItem()->setText(0, "Requests (filtred)"); // Show only the ones which the name match the filter if(this->currentProjectItem != nullptr){ for(int i=0; icurrentProjectItem->childCount(); i++){ if(!this->currentProjectItem->child(i)->text(0).contains(trimmedFilter, Qt::CaseInsensitive)){ // TODO change with enum this->currentProjectItem->child(i)->setHidden(true); } else{ this->currentProjectItem->child(i)->setHidden(false); } } } } } void MainWindow::openProjectProperties(){ // Show project properties ProjectProperties *projectPropertiesDialog = new ProjectProperties(this, this->currentProjectItem); // https://stackoverflow.com/a/9264888/1499019 connect(projectPropertiesDialog, SIGNAL (signalSaveProjectProperties()), this, SLOT(saveProjectProperties())); projectPropertiesDialog->exec(); //it destroys itself when finished. } void MainWindow::on_actionProject_Properties_triggered() { openProjectProperties(); } void MainWindow::removeRequest(FRequestTreeWidgetRequestItem * const itemToDelete){ if(Util::Dialogs::showQuestion(this, "Remove the request '" + itemToDelete->text(0) + "'?")){ QString uuidToRemove = itemToDelete->itemContent.uuid; this->currentProjectItem->removeChild(itemToDelete); this->uuidsToCleanUp.append(uuidToRemove); this->uuidsInUse.remove(uuidToRemove); if(ui->treeWidget->currentItem() != this->currentProjectItem){ this->currentItem = FRequestTreeWidgetRequestItem::fromQTreeWidgetItem(ui->treeWidget->currentItem()); } else{ this->currentItem = nullptr; } // We need to call this event manually when a item is removed (it is not called automatically in this case) on_treeWidget_currentItemChanged(ui->treeWidget->currentItem(), nullptr); setProjectHasChanged(); } } void MainWindow::treeWidgetDeleteKeyPressed(){ if (this->currentItem != nullptr && ui->treeWidget->currentItem() == this->currentItem) { removeRequest(this->currentItem); } } void MainWindow::setThemePaletteForCustomWidgets(){ setFilterThemePalette(); QPalette palette; switch(this->currentSettings.theme){ case ConfigFileFRequest::FRequestTheme::OS_DEFAULT: { palette.setColor(QPalette::Active, QPalette::Base, palette.color(QPalette::Disabled, QPalette::Base)); break; } case ConfigFileFRequest::FRequestTheme::JORGEN_DARK_THEME: { palette.setColor(QPalette::Active, QPalette::Text, palette.color(QPalette::Disabled, QPalette::Text)); ui->treeWidget->setStyleSheet("selection-background-color: rgba(42, 130, 218, 25%)"); break; } default: { const QString errorMessage = "Unknown theme selected! '" + QString::number(static_cast(this->currentSettings.theme)) + "'. Please report this error."; this->currentSettings.theme = ConfigFileFRequest::FRequestTheme::OS_DEFAULT; Util::Dialogs::showError(errorMessage); LOG_ERROR << errorMessage; } } ui->leFullPath->setPalette(palette); // Set the background color the same as disable } void MainWindow::setFilterThemePalette(){ QPalette palette; // to set filter background color QString trimmedFilter = ui->leRequestsFilter->text().trimmed(); if(trimmedFilter.isEmpty()){ // if filter is empty palette.setColor(QPalette::Base, ui->lePath->palette().color(QPalette::Base)); // just use another text box to get the default value } else{ switch(this->currentSettings.theme){ case ConfigFileFRequest::FRequestTheme::OS_DEFAULT: { palette.setColor(QPalette::Base, 0xFFFACD /* "LemonChiffon" */); break; } case ConfigFileFRequest::FRequestTheme::JORGEN_DARK_THEME: { palette.setColor(QPalette::Base, 0x2A82DA /* Light Blue */); break; } default: { const QString errorMessage = "Unknown theme selected! '" + QString::number(static_cast(this->currentSettings.theme)) + "'. Please report this error."; this->currentSettings.theme = ConfigFileFRequest::FRequestTheme::OS_DEFAULT; Util::Dialogs::showError(errorMessage); LOG_ERROR << errorMessage; } } } ui->leRequestsFilter->setPalette(palette); } void MainWindow::setTheme(){ switch(this->currentSettings.theme){ case ConfigFileFRequest::FRequestTheme::OS_DEFAULT: { // Nothing to do break; } case ConfigFileFRequest::FRequestTheme::JORGEN_DARK_THEME: { // From here: // https://stackoverflow.com/a/45634644/1499019 // https://github.com/Jorgen-VikingGod/Qt-Frameless-Window-DarkStyle/blob/master/DarkStyle.cpp // Just removed font resizing qApp->setStyle(QStyleFactory::create("Fusion")); // modify palette to dark QPalette darkPalette; darkPalette.setColor(QPalette::Window,QColor(53,53,53)); darkPalette.setColor(QPalette::WindowText,Qt::white); darkPalette.setColor(QPalette::Disabled,QPalette::WindowText,QColor(127,127,127)); darkPalette.setColor(QPalette::Base,QColor(42,42,42)); darkPalette.setColor(QPalette::AlternateBase,QColor(66,66,66)); darkPalette.setColor(QPalette::ToolTipBase,Qt::white); darkPalette.setColor(QPalette::ToolTipText,Qt::white); darkPalette.setColor(QPalette::Text,Qt::white); darkPalette.setColor(QPalette::Disabled,QPalette::Text,QColor(127,127,127)); darkPalette.setColor(QPalette::Dark,QColor(35,35,35)); darkPalette.setColor(QPalette::Shadow,QColor(20,20,20)); darkPalette.setColor(QPalette::Button,QColor(53,53,53)); darkPalette.setColor(QPalette::ButtonText,Qt::white); darkPalette.setColor(QPalette::Disabled,QPalette::ButtonText,QColor(127,127,127)); darkPalette.setColor(QPalette::BrightText,Qt::red); darkPalette.setColor(QPalette::Link,QColor(42,130,218)); darkPalette.setColor(QPalette::Highlight,QColor(42,130,218)); darkPalette.setColor(QPalette::Disabled,QPalette::Highlight,QColor(80,80,80)); darkPalette.setColor(QPalette::HighlightedText,Qt::white); darkPalette.setColor(QPalette::Disabled,QPalette::HighlightedText,QColor(127,127,127)); qApp->setPalette(darkPalette); // Fix for macos, if we don't do this, tabs of main window doesn't get properly rethemed // Fix from here: https://gist.github.com/QuantumCD/9863860, https://forum.qt.io/topic/37154/qpalette-not-inherited-properly/12 // To apply only to custom themes, the default one doesn't need (it even gets broken by this) for (QWidget* const w : this->findChildren()) { w->setPalette(darkPalette); } break; } default: { const QString errorMessage = "Unknown theme selected! '" + QString::number(static_cast(this->currentSettings.theme)) + "'. Please report this error."; this->currentSettings.theme = ConfigFileFRequest::FRequestTheme::OS_DEFAULT; Util::Dialogs::showError(errorMessage); LOG_ERROR << errorMessage; } } setThemePaletteForCustomWidgets(); } void MainWindow::on_twRequestHeadersKeyValue_currentItemChanged(QTableWidgetItem *current, QTableWidgetItem */*previous*/) { // We can't remove global headers here... (global headers are always disabled) if(current != nullptr){ ui->tbRequestHeadersKeyValueRemove->setEnabled( !UtilFRequest::isGlobalHeaderTableWidgetRow(ui->twRequestHeadersKeyValue, current->row())); } } void MainWindow::addGlobalHeaders() { for (UtilFRequest::HttpHeader const& header : currentProjectItem->globalHeaders) { Util::TableWidget::addRow(ui->twRequestHeadersKeyValue, QStringList() << header.name << header.value); UtilFRequest::setGlobalHeaderTableWidgetRow(ui->twRequestHeadersKeyValue, ui->twRequestHeadersKeyValue->rowCount()-1); } } ================================================ FILE: mainwindow.h ================================================ /* * 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 . * */ #ifndef MAINWINDOW_H #define MAINWINDOW_H #include #include #include #include #include #include #include "projectproperties.h" #include "updatechecker.h" #include "SyntaxHighlighters/frequestjsonhighlighter.h" #include "SyntaxHighlighters/frequestxmlhighlighter.h" #include "XmlParsers/projectfilefrequest.h" namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); private slots: void applicationHasLoaded(); void saveProjectProperties(); void treeWidgetDeleteKeyPressed(); void on_pbSendRequest_clicked(); void on_lePath_textChanged(const QString &arg1); void replyFinished(QNetworkReply *reply); void on_treeWidget_customContextMenuRequested(const QPoint &pos); void on_treeWidget_itemChanged(QTreeWidgetItem *item, int column); void on_treeWidget_currentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *previous); void on_actionSave_Project_triggered(); void on_actionNew_Project_triggered(); void on_actionSave_Project_As_triggered(); void on_actionLoad_Project_triggered(); void on_actionExit_triggered(); void on_actionAbout_triggered(); void on_actionProject1_triggered(); void on_actionProject2_triggered(); void on_actionProject3_triggered(); void on_actionProject4_triggered(); void on_actionProject5_triggered(); void on_actionProject6_triggered(); void on_cbResponseChooseHeader_currentIndexChanged(const QString &arg1); void on_tbRequestBodyKeyValueAdd_clicked(); void on_twRequestBodyKeyValue_cellChanged(int row, int column); void on_cbBodyType_currentIndexChanged(const QString &arg1); void on_tbRequestBodyKeyValueRemove_clicked(); void on_tbRequestHeadersKeyValueAdd_clicked(); void on_tbRequestHeadersKeyValueRemove_clicked(); void on_twRequestHeadersKeyValue_cellChanged(int row, int column); void on_cbRequestOverrideMainUrl_toggled(bool checked); void on_leRequestOverrideMainUrl_textChanged(const QString &arg1); void on_pteRequestBody_textChanged(); void on_cbDownloadResponseAsFile_toggled(bool checked); void on_tbCopyToClipboardRequest_clicked(); void on_tbCopyToClipboardResponse_clicked(); void on_actionPreferences_triggered(); void saveCurrentSettings(); void on_cbRequestType_currentIndexChanged(const QString &arg1); void on_actionFormat_Response_Body_triggered(); void on_actionFormat_Request_body_triggered(); void on_tbRequestBodyFile_clicked(); void tbAbortRequest_clicked(); void on_actionShow_Request_Types_Icons_triggered(bool checked); void on_leRequestsFilter_textChanged(const QString &arg1); void on_actionProject_Properties_triggered(); void on_actionCheck_for_updates_triggered(); void on_cbDisableGlobalHeaders_toggled(bool checked); void on_twRequestHeadersKeyValue_currentItemChanged(QTableWidgetItem *current, QTableWidgetItem *previous); signals: void signalAppIsLoaded(); void signalRequestFinishedAndProcessed(); private: void showEvent(QShowEvent *e); void checkForQNetworkAccessManagerTimeout(QNetworkReply *reply); QNetworkReply* processHttpRequest( const UtilFRequest::RequestType requestType, const QString &fullPath, const QString &bodyType, const QString &requestBody, const QVector& requestHeaders ); QString getDownloadFileName(const QNetworkReply * const reply); void updateWindowTitle(); void setNewProject(); void saveProjectState(const QString &filePath); void loadProjectState(const QString &filePath); void updateTreeWidgetItemContent(FRequestTreeWidgetRequestItem * const requestItem); void reloadRequest(FRequestTreeWidgetRequestItem * const item); FRequestTreeWidgetProjectItem *addProjectItem(const QString &projectName, const QString &projectUuid); FRequestTreeWidgetRequestItem *addRequestItem(const QString &requestName, const QString &projectUuid, FRequestTreeWidgetProjectItem * const currentProject); void closeEvent(QCloseEvent *event); void loadRecentProjects(); void addNewRecentProject(const QString &filePath); void reloadRecentProjectsMenu(); void saveRecentProjects(); QVector getRequestHeaders(); QVector getRequestForm(); void buildFullPath(); void setProjectHasChanged(); QMessageBox::StandardButton askToSaveCurrentProject(); void clearOlderResponse(); void clearRequestAndResponse(); void clearEverything(); void addDefaultHeaders(); void setRequestType(UtilFRequest::RequestType requestType); void formatRequestBody(const UtilFRequest::SerializationFormatType serializationType); void formatResponseBody(const UtilFRequest::SerializationFormatType serializationType); bool loadAndValidateFRequestProjectFile(const QString &filePath, pugi::xml_document &doc); void setIconForRequest(FRequestTreeWidgetRequestItem * const item); void setAllRequestIcons(bool showIcon); ProjectFileFRequest::ProjectData fetchCurrentProjectData(); bool formKeyValueInBodyIsValid(); bool formKeyValueInBodyHasFiles(); bool noDuplicatedKeyExistsInRequestHeaders(const QVector &headers); void removeAllFilesRowsFromFormKeyValueInBody(); UtilFRequest::SerializationFormatType getRequestCurrentSerializationFormatType(); UtilFRequest::SerializationFormatType getResponseCurrentSerializationFormatType(); QString getNewUuid(); QString getFullPathFromMainUrlAndPath(const QString & mainUrl, const QString & path); void applyRequestAuthentication(); void openProjectProperties(); void removeRequest(FRequestTreeWidgetRequestItem * const itemToDelete); void setThemePaletteForCustomWidgets(); void setFilterThemePalette(); void setTheme(); void downloadResponseAsFile(QNetworkReply *reply, QByteArray &totalLoadedData, QByteArray ¤tData, const int maxBytesForBufferAndDisplay); void addGlobalHeaders(); public: static constexpr int recentProjectsMaxSize=6; private: Ui::MainWindow *ui; QDateTime lastStartTime; FRequestTreeWidgetProjectItem *currentProjectItem = nullptr; FRequestTreeWidgetRequestItem *currentItem = nullptr; QSet uuidsInUse; QVector uuidsToCleanUp; // this vector stores the uuids of deleted items in the application, its used to clean them in the project file bool applicationIsFullyLoaded = false; bool unsavedChangesExist = false; // This conditional semaphore allow us to tell to the interface to ignore changes (not mark project as unsaved) within some time interval Cosemaphore::ConditionalSemaphore ignoreAnyChangesToProject; QString lastProjectFilePath; QList recentProjectsList; QString lastResponseFileName; int lastReplyStatusError = 0; ConfigFileFRequest configFileManager = ConfigFileFRequest(Util::FileSystem::getAppPath() + "/" + GlobalVars::AppConfigFileName); ConfigFileFRequest::Settings currentSettings; const QSize auxMinimumSize = QSize(0,0); const QSize auxMaximumSize = QSize(16777215,16777215); QProgressBar pbRequestProgress; QToolButton tbAbortRequest; QLabel lbRequestInfo; QLabel lbProjectInfo; std::experimental::optional currentReply; QMap generatedIconCache; QNetworkAccessManager networkAccessManager; const QString operatingSystemDefaultStyle; // Requests Highlighters FRequestJSONHighlighter jsonRequestBodyHighligher; FRequestJSONHighlighter jsonResponseBodyHighligher; FRequestXMLHighlighter xmlRequestBodyHighligher; FRequestXMLHighlighter xmlResponseBodyHighligher; bool currentProjectAuthenticationWasMade = false; bool authenticationIsRunning = false; }; #endif // MAINWINDOW_H ================================================ FILE: mainwindow.ui ================================================ MainWindow 0 0 803 861 FRequest :/icons/frequest_icon.png:/icons/frequest_icon.png Qt::Horizontal Project Requests Filter true 0 0 150 0 16777215 16777215 0 0 Qt::CustomContextMenu Requests Qt::ScrollBarAsNeeded true 0 0 470 780 Request Override Main Url: false Path: Full Path: true Type: GET POST PUT DELETE PATCH HEAD TRACE OPTIONS Qt::Vertical 0 Body Body Type: false raw form-data x-form-www-urlencoded false Courier New false Courier New true true Key Value Type false Add row ... :/icons/plus.png:/icons/plus.png false Add file row ... :/icons/plus_file.png:/icons/plus_file.png false Remove selected rows ... :/icons/minus.png:/icons/minus.png Headers Select a Header to Add Content-type: application/json Content-type: application/xml Content-type: multipart/form-data Content-type: application/x-www-form-urlencoded Courier New true true true Key Value Add new row ... :/icons/plus.png:/icons/plus.png Remove selected rows ... :/icons/minus.png:/icons/minus.png Click to disable global headers for THIS request. Useful if you do not want to send them. Disable global headers true Copy to clipboard ... :/icons/clipboard_icon.png:/icons/clipboard_icon.png true Response Status Code: Description: Time Elapsed: 0 Body 0 0 16 16 If you pretend to see all the data, increase the value in preferences or alternatively just download the response as file. :/icons/warning_icon.png true 7 If you pretend to see all the data, increase the value in preferences or alternatively just download the response as file. Return data size is greater than 200 KB, only displaying the first 200 KB. Courier New true Headers Courier New true Copy to clipboard ... :/icons/clipboard_icon.png:/icons/clipboard_icon.png true Download Response as File Qt::Horizontal 0 0 0 50 Send the request Send Request :/icons/send_request_icon.png:/icons/send_request_icon.png 32 32 Ctrl+Return 0 0 803 20 File Recent Projects Help Options Edit TopToolBarArea false Exit About New Project Save Project Ctrl+S Save Project As... Load Project... Project 1 Project 2 Project 3 Project 4 Project 5 Project 6 true true Format Response Body true true Format Request Body true Use Last Download Location Preferences true Open File After Download true true Show Request Types Icons Project Properties Check for updates FRequestTreeWidget QTreeWidget
Widgets/frequesttreewidget.h
================================================ FILE: preferences.cpp ================================================ /* * 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 . * */ #include "preferences.h" #include "ui_preferences.h" Preferences::Preferences(QWidget *parent, ConfigFileFRequest::Settings ¤tSettings) : QDialog(parent), ui(new Ui::Preferences), currentSettings(currentSettings) { ui->setupUi(this); this->setAttribute(Qt::WA_DeleteOnClose,true ); //destroy itself once finished. ui->lbProjAuthDataNote->setText( "Note: These authentications are only the ones that were saved as \"FRequest Configuration File\", " "that is the ones saved in your FRequest configuration (the ones saved as " "\"FRequest Project File\" are not shown here).

" "You can see and delete here the authentications for projects that you no longer use." ); ui->lbProjAuthDataNote->adjustSize(); // to show all the text (resize label automatically to fit) fillConfigProjAuthDataTable(); ui->twConfigProjAuthData->resizeColumnsToContents(); } Preferences::~Preferences() { delete ui; } void Preferences::showEvent(QShowEvent *e) { if(!this->preferencesAreFullyLoaded) { // Apparently Qt doesn't contains a slot to when the Preferences was fully load. So we do our own implementation instead. connect(this, SIGNAL(signalPreferencesAreLoaded()), this, SLOT(preferencesHaveLoaded()), Qt::ConnectionType::QueuedConnection); emit signalPreferencesAreLoaded(); } e->accept(); } // Called only when the Preferences was fully loaded and painted on the screen. This slot is only called once. void Preferences::preferencesHaveLoaded(){ loadExistingSettings(); this->preferencesAreFullyLoaded = true; } // Need to override to do the verification // http://stackoverflow.com/questions/3261676/how-to-make-qdialogbuttonbox-not-close-its-parent-qdialog void Preferences::accept (){ if(ui->cbProxyUseProxy->isChecked()){ if(ui->cbProxyType->currentText() != "Automatic"){ QString proxyHostname = ui->leProxyHostname->text(); QString proxyPortNumber = ui->leProxyPort->text(); if(Util::Validation::checkEmptySpaces(QStringList() << proxyHostname << proxyPortNumber)){ Util::Dialogs::showError("Please fill the proxy hostname and port number."); return; } if(Util::Validation::checkIfIntegers(QStringList() << proxyPortNumber)){ Util::Dialogs::showError("Proxy port must be a number."); return; } } } // https://stackoverflow.com/a/16487964/1499019 this->currentSettings.requestTimeout = QTime(0, 0, 0).secsTo(ui->teRequestTimeout->time()); this->currentSettings.maxRequestResponseDataSizeToDisplay = ui->sbMaxRequestResponseDataSizeToDisplay->value(); if(ui->cbOnStartup->currentText() == "Load last project"){ this->currentSettings.onStartupSelectedOption = ConfigFileFRequest::OnStartupOption::LOAD_LAST_PROJECT; } else if(ui->cbOnStartup->currentText() == "Ask to load last project"){ this->currentSettings.onStartupSelectedOption = ConfigFileFRequest::OnStartupOption::ASK_TO_LOAD_LAST_PROJECT; } else if(ui->cbOnStartup->currentText() == "Do nothing"){ this->currentSettings.onStartupSelectedOption = ConfigFileFRequest::OnStartupOption::DO_NOTHING; } else{ QString errorMessage = "Unrecognized cbOnStartup option selected! The On startup option will not be saved!"; Util::Dialogs::showError(errorMessage); LOG_ERROR << errorMessage; } this->currentSettings.windowsGeometry.saveWindowsGeometryWhenExiting = ui->cbSaveWindowGeometryWhenExiting->isChecked(); this->currentSettings.defaultHeaders.useDefaultHeaders = ui->cbUseDefaultHeaders->isChecked(); this->currentSettings.useProxy = ui->cbProxyUseProxy->isChecked(); bool differentThanAutomaticProxy = true; if(ui->cbProxyType->currentText() == "Automatic"){ this->currentSettings.proxySettings.type = ConfigFileFRequest::ProxyType::AUTOMATIC; differentThanAutomaticProxy = false; } else if(ui->cbProxyType->currentText() == "Http Transparent Proxy"){ this->currentSettings.proxySettings.type = ConfigFileFRequest::ProxyType::HTTP_TRANSPARENT; } else if(ui->cbProxyType->currentText() == "Http Proxy"){ this->currentSettings.proxySettings.type = ConfigFileFRequest::ProxyType::HTTP; } else if(ui->cbProxyType->currentText() == "Socks5 Proxy"){ this->currentSettings.proxySettings.type = ConfigFileFRequest::ProxyType::SOCKS5; } else{ QString errorMessage = "Tried to save unreconized proxy type! '" + QString::number(static_cast(this->currentSettings.proxySettings.type)) + "'. Please choose a valid type."; Util::Dialogs::showWarning(errorMessage); LOG_ERROR << errorMessage; return; } if(differentThanAutomaticProxy){ this->currentSettings.proxySettings.hostName = ui->leProxyHostname->text(); this->currentSettings.proxySettings.portNumber = ui->leProxyPort->text().toUInt(); } updateCurrentDefaultHeaders(); // Remove the requested config proj authentications for(const QString &currProjUuid : this->configProjAuthsToDelete){ this->currentSettings.mapOfConfigAuths_UuidToConfigAuth.remove(currProjUuid); } ConfigFileFRequest::FRequestTheme newTheme = ConfigFileFRequest::geFRequestThemeByString(ui->cbTheme->currentText()); bool giveThemeWarningToRestart = false; if(this->currentSettings.theme != newTheme){ giveThemeWarningToRestart = true; } this->currentSettings.theme = newTheme; this->currentSettings.hideProjectSavedDialog = ui->cbHideProjectSavedDialog->isChecked(); emit saveSettings(); QDialog::accept(); if(giveThemeWarningToRestart){ Util::Dialogs::showWarning("The theme will only be applied once you restart " + GlobalVars::AppName + "."); } Util::Dialogs::showInfo("Settings saved with success!"); } void Preferences::on_buttonBox_rejected() { // nothing todo (it auto closes) } void Preferences::on_cbUseDefaultHeaders_toggled(bool checked) { ui->gbRequest->setEnabled(checked); if(checked){ on_cbRequestType_currentIndexChanged(ui->cbRequestType->currentText()); } } void Preferences::on_cbRequestType_currentIndexChanged(const QString &arg1) { ui->cbRequestBodyType->setEnabled(true); // Indicates if body can be set or not depending on the given option switch(UtilFRequest::getRequestTypeByString(ui->cbRequestType->currentText())){ case UtilFRequest::RequestType::GET_OPTION: case UtilFRequest::RequestType::DELETE_OPTION: case UtilFRequest::RequestType::HEAD_OPTION: case UtilFRequest::RequestType::TRACE_OPTION: { ui->cbRequestBodyType->setEnabled(false); break; } case UtilFRequest::RequestType::POST_OPTION: case UtilFRequest::RequestType::PUT_OPTION: case UtilFRequest::RequestType::PATCH_OPTION: case UtilFRequest::RequestType::OPTIONS_OPTION: { ui->cbRequestBodyType->setEnabled(true); break; } default: { QString errorMessage = "Request type unknown: '" + arg1 + "'. Program can't proceed."; Util::Dialogs::showError(errorMessage); LOG_FATAL << errorMessage; exit(1); } } if(this->preferencesAreFullyLoaded){ updateCurrentDefaultHeaders(); loadCurrentDefaultHeaders(); } this->previousRequestType = arg1; } void Preferences::on_tbRequestBodyKeyValueAdd_clicked() { Util::TableWidget::addRow(ui->twRequestBodyKeyValue, QStringList() << "" << ""); } void Preferences::on_tbRequestBodyKeyValueRemove_clicked() { int size = Util::TableWidget::getSelectedRows(ui->twRequestBodyKeyValue).size(); if(size==0){ Util::Dialogs::showInfo("Select a row first!"); return; } if(Util::Dialogs::showQuestion(this, "Are you sure you want to remove all selected rows?")){ for(int i=0; i < size; i++){ ui->twRequestBodyKeyValue->removeRow(Util::TableWidget::getSelectedRows(ui->twRequestBodyKeyValue).at(size-i-1).row()); } Util::Dialogs::showInfo("Key-Value rows deleted"); } } void Preferences::loadExistingSettings(){ ui->teRequestTimeout->setTime(QTime(0,0).addSecs(this->currentSettings.requestTimeout)); ui->sbMaxRequestResponseDataSizeToDisplay->setValue(this->currentSettings.maxRequestResponseDataSizeToDisplay); ui->cbUseDefaultHeaders->setChecked(this->currentSettings.defaultHeaders.useDefaultHeaders); ui->cbSaveWindowGeometryWhenExiting->setChecked(this->currentSettings.windowsGeometry.saveWindowsGeometryWhenExiting); ui->cbProxyUseProxy->setChecked(this->currentSettings.useProxy); ui->cbHideProjectSavedDialog->setChecked(this->currentSettings.hideProjectSavedDialog); // TODO Check if there's a better alternative to do this switches / ifs (maybe using enums??) // (without do direct string comparisons), because as it is, it is easy to break if we change any of the strings switch(this->currentSettings.onStartupSelectedOption){ case ConfigFileFRequest::OnStartupOption::LOAD_LAST_PROJECT: { ui->cbOnStartup->setCurrentText("Load last project"); break; } case ConfigFileFRequest::OnStartupOption::ASK_TO_LOAD_LAST_PROJECT: { ui->cbOnStartup->setCurrentText("Ask to load last project"); break; } case ConfigFileFRequest::OnStartupOption::DO_NOTHING: { ui->cbOnStartup->setCurrentText("Do nothing"); break; } default: { ui->cbProxyType->setCurrentText("Ask to load last project"); QString warningMessage = "Unknown on startup option loaded! '" + QString::number(static_cast(this->currentSettings.onStartupSelectedOption)) + "'. Using 'Ask to load last project' instead."; Util::Dialogs::showWarning(warningMessage); LOG_WARNING << warningMessage; } } switch(this->currentSettings.proxySettings.type){ case ConfigFileFRequest::ProxyType::AUTOMATIC: { ui->cbProxyType->setCurrentText("Automatic"); break; } case ConfigFileFRequest::ProxyType::HTTP_TRANSPARENT: { ui->cbProxyType->setCurrentText("Http Transparent Proxy"); break; } case ConfigFileFRequest::ProxyType::HTTP: { ui->cbProxyType->setCurrentText("Http Proxy"); break; } case ConfigFileFRequest::ProxyType::SOCKS5: { ui->cbProxyType->setCurrentText("Socks5 Proxy"); break; } default: { ui->cbProxyType->setCurrentText("Automatic"); QString warningMessage = "Unknown proxy type loaded! '" + QString::number(static_cast(this->currentSettings.proxySettings.type)) + "'. Using 'automatic' instead."; Util::Dialogs::showWarning(warningMessage); LOG_WARNING << warningMessage; } } ui->leProxyHostname->setText(this->currentSettings.proxySettings.hostName); ui->leProxyPort->setText(QString::number(this->currentSettings.proxySettings.portNumber)); loadCurrentDefaultHeaders(); ui->cbTheme->setCurrentText(ConfigFileFRequest::getFRequestThemeString(this->currentSettings.theme)); } void Preferences::loadCurrentDefaultHeaders(){ Util::TableWidget::clearContentsNoPrompt(ui->twRequestBodyKeyValue); UtilFRequest::RequestType currentRequestType = UtilFRequest::getRequestTypeByString(ui->cbRequestType->currentText()); std::experimental::optional ¤tProtocolHeader = ConfigFileFRequest::getSettingsHeaderForRequestType(currentRequestType, this->currentSettings); bool mayHaveBody = UtilFRequest::requestTypeMayHaveBody(currentRequestType); if(!mayHaveBody){ if(currentProtocolHeader.has_value()){ if(currentProtocolHeader.value().headers_Raw.has_value()){ for(const UtilFRequest::HttpHeader ¤tHeader : currentProtocolHeader.value().headers_Raw.value()) { Util::TableWidget::addRow(ui->twRequestBodyKeyValue, QStringList() << currentHeader.name << currentHeader.value); } } } } else{ if(currentProtocolHeader.has_value()){ std::experimental::optional> *currentProtocolHeaders = nullptr; if(ui->cbRequestBodyType->currentText() == "raw"){ currentProtocolHeaders = ¤tProtocolHeader.value().headers_Raw; } else if(ui->cbRequestBodyType->currentText() == "form-data"){ currentProtocolHeaders = ¤tProtocolHeader.value().headers_Form_Data; } else if(ui->cbRequestBodyType->currentText() == "x-form-www-urlencoded"){ currentProtocolHeaders = ¤tProtocolHeader.value().headers_X_form_www_urlencoded; } else{ QString errorMessage = "Error loading default headers! The type '" + ui->cbRequestBodyType->currentText() + "' is not being handled!"; LOG_ERROR << errorMessage; Util::Dialogs::showError(errorMessage); return; } if(currentProtocolHeaders->has_value()){ for(const UtilFRequest::HttpHeader ¤tHeader : currentProtocolHeaders->value()) { Util::TableWidget::addRow(ui->twRequestBodyKeyValue, QStringList() << currentHeader.name << currentHeader.value); } } } } } std::experimental::optional> Preferences::getRequestHeaders(){ std::experimental::optional> requestHeaders; if(ui->twRequestBodyKeyValue->rowCount() > 0){ requestHeaders = QVector(); } for(int i = 0; i < ui->twRequestBodyKeyValue->rowCount(); i++){ UtilFRequest::HttpHeader currentHeader; currentHeader.name = ui->twRequestBodyKeyValue->item(i, 0)->text(); currentHeader.value = ui->twRequestBodyKeyValue->item(i, 1)->text(); requestHeaders.value().append(currentHeader); } return requestHeaders; } void Preferences::on_cbRequestBodyType_currentIndexChanged(const QString &arg1) { if(this->preferencesAreFullyLoaded){ updateCurrentDefaultHeaders(); loadCurrentDefaultHeaders(); } this->previousRequestBodyType = arg1; } void Preferences::updateCurrentDefaultHeaders(){ std::experimental::optional> currentRequestDefaultHeaders = getRequestHeaders(); std::experimental::optional> *currentHeaders = nullptr; UtilFRequest::RequestType requestType = UtilFRequest::getRequestTypeByString(this->previousRequestType); std::experimental::optional ¤tProtocolHeader = ConfigFileFRequest::getSettingsHeaderForRequestType(requestType, this->currentSettings); bool mayHaveBody = UtilFRequest::requestTypeMayHaveBody(requestType); if(!mayHaveBody){ currentProtocolHeader = ConfigFileFRequest::ProtocolHeader(); currentHeaders = ¤tProtocolHeader.value().headers_Raw; } else{ // Create if not exist if(!currentProtocolHeader.has_value()){ currentProtocolHeader = ConfigFileFRequest::ProtocolHeader(); } if(this->previousRequestBodyType == "raw"){ currentHeaders = ¤tProtocolHeader.value().headers_Raw; } else if(this->previousRequestBodyType == "form-data"){ currentHeaders = ¤tProtocolHeader.value().headers_Form_Data; } else if(this->previousRequestBodyType == "x-form-www-urlencoded"){ currentHeaders = ¤tProtocolHeader.value().headers_X_form_www_urlencoded; } else{ QString errorMessage = "Error loading default headers! The type '" + ui->cbRequestBodyType->currentText() + "' is not being handled!"; LOG_ERROR << errorMessage; Util::Dialogs::showError(errorMessage); return; } } (*currentHeaders) = currentRequestDefaultHeaders; } void Preferences::on_cbProxyUseProxy_toggled(bool checked) { ui->gbProxy->setEnabled(checked); } void Preferences::on_cbProxyType_currentIndexChanged(const QString &arg1) { if(arg1 == "Automatic"){ ui->leProxyHostname->setEnabled(false); ui->leProxyPort->setEnabled(false); } else{ ui->leProxyHostname->setEnabled(true); ui->leProxyPort->setEnabled(true); } } void Preferences::fillConfigProjAuthDataTable(){ for(const ConfigFileFRequest::ConfigurationProjectAuthentication &currAuthData : this->currentSettings.mapOfConfigAuths_UuidToConfigAuth){ Util::TableWidget::addRow(ui->twConfigProjAuthData, QStringList() << currAuthData.lastProjectName << currAuthData.projectUuid << FRequestAuthentication::getAuthenticationString(currAuthData.authData->type) ); } // Disable editing on our table for(int i=0; itwConfigProjAuthData->rowCount(); i++){ for(int j=0; jtwConfigProjAuthData->columnCount(); j++){ ui->twConfigProjAuthData->item(i,j)->setFlags(ui->twConfigProjAuthData->item(i,j)->flags() & (~Qt::ItemIsEditable)); } } } void Preferences::on_tbConfigProjDataRemove_clicked() { int size = Util::TableWidget::getSelectedRows(ui->twConfigProjAuthData).size(); if(size==0){ Util::Dialogs::showInfo("Select a row first!"); return; } if(Util::Dialogs::showQuestion(this, "Are you sure you want to remove all selected rows?")){ for(int i=0; i < size; i++){ this->configProjAuthsToDelete.append(ui->twConfigProjAuthData->item(Util::TableWidget::getSelectedRows(ui->twConfigProjAuthData).at(size-i-1).row(),1)->text()); // TODO: replace 1 by an index enum ui->twConfigProjAuthData->removeRow(Util::TableWidget::getSelectedRows(ui->twConfigProjAuthData).at(size-i-1).row()); } Util::Dialogs::showInfo("Authentications rows deleted"); } } ================================================ FILE: preferences.h ================================================ /* * 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 . * */ #ifndef PREFERENCES_H #define PREFERENCES_H #include #include #include #include #include "util.h" #include "XmlParsers/configfilefrequest.h" namespace Ui { class Preferences; } class Preferences : public QDialog { Q_OBJECT public: Preferences(QWidget *parent, ConfigFileFRequest::Settings ¤tSettings); ~Preferences(); private slots: void accept (); void on_buttonBox_rejected(); void on_cbUseDefaultHeaders_toggled(bool checked); void on_cbRequestType_currentIndexChanged(const QString &arg1); void on_tbRequestBodyKeyValueAdd_clicked(); void on_tbRequestBodyKeyValueRemove_clicked(); void on_cbRequestBodyType_currentIndexChanged(const QString &arg1); void preferencesHaveLoaded(); void on_cbProxyUseProxy_toggled(bool checked); void on_cbProxyType_currentIndexChanged(const QString &arg1); void on_tbConfigProjDataRemove_clicked(); signals: void signalPreferencesAreLoaded(); void saveSettings(); private: Ui::Preferences *ui; ConfigFileFRequest::Settings ¤tSettings; QString previousRequestType = "GET"; // by default QString previousRequestBodyType = "raw"; bool preferencesAreFullyLoaded = false; QVector configProjAuthsToDelete; private: void showEvent(QShowEvent *e); void loadExistingSettings(); std::experimental::optional > getRequestHeaders(); void loadCurrentDefaultHeaders(); void updateCurrentDefaultHeaders(); void fillConfigProjAuthDataTable(); }; #endif // PREFERENCES_H ================================================ FILE: preferences.ui ================================================ Preferences 0 0 800 600 Preferences 0 General Minutes - Seconds (00:00 means no timeout) Request timeout: Minutes - Seconds (00:00 means no timeout) mm:ss Use default headers false 0 0 Request Request type: GET POST PUT DELETE PATCH HEAD TRACE OPTIONS Headers Body Type: raw form-data x-form-www-urlencoded true Key Value Add new row ... :/icons/plus.png:/icons/plus.png Remove selected rows ... :/icons/minus.png:/icons/minus.png Warning: Setting this value too high can slown down or even crash FRequest (since it parses all the received data). As alternative try to download the response as file (since this way it writes all the data to a file). (Default value = 200 KB) Max request response data size to display: On startup: Ask to load last project Load last project Do nothing Theme: OS Default Jorgen's Dark Theme Warning: Setting this value too high can slown down or even crash FRequest (since it parses all the received data). As alternative try to download the response as file (since this way it writes all the data to a file). (Default value = 200 KB) QAbstractSpinBox::NoButtons KB 50 512000 200 Save window geometry when exiting Hide confirmation dialog when saving a project Network Use proxy false Proxy Proxy Type: Automatic Http Transparent Proxy Http Proxy Socks5 Proxy Hostname: false Port: false 3128 Projects Authentications Data Note: true Qt::Vertical QSizePolicy::Fixed 20 20 FRequest Configuration Projects Authentications true true Project Last Name Project Uuid Authentication Type Remove selected rows ... :/icons/minus.png:/icons/minus.png Qt::Horizontal QDialogButtonBox::Cancel|QDialogButtonBox::Ok buttonBox accepted() Preferences accept() 248 254 157 274 buttonBox rejected() Preferences reject() 316 260 286 274 ================================================ FILE: projectproperties.cpp ================================================ /* * 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 . * */ #include "projectproperties.h" #include "ui_projectproperties.h" ProjectProperties::ProjectProperties(QWidget *parent, FRequestTreeWidgetProjectItem * const projectItem) : QDialog(parent), ui(new Ui::ProjectProperties), projectItem(projectItem) { ui->setupUi(this); this->setAttribute(Qt::WA_DeleteOnClose,true); //destroy itself once finished. fillInterface(); if(this->projectItem->authData != nullptr){ fillAuthenticationData(*this->projectItem->authData); } if(this->currentPasswordSalt.isEmpty()){ // Unix time as sha256 this->currentPasswordSalt = QCryptographicHash::hash(QByteArray().setNum(QDateTime::currentDateTime().toSecsSinceEpoch()), QCryptographicHash::Sha256).toHex(); } setRequestAuthenticationNote(); ui->lbProjectPropertiesNote->setText( "Note: Request authentication works by selecting one of your requests as the one for the authentication.

" "If you have a website you can find the request that you need by checking in your browser the one that authenticates you " "(normally you could find it in a \"network\" tab), " "then just replicate that request in FRequest and select it for the authentication here.

" "Currently FRequest can only use a single request for the authentication.

" "You should add in your authentication request the FRequest placeholders for the username and password, they are respectively " "{{FREQUEST_AUTH_USERNAME}} and {{FREQUEST_AUTH_PASSWORD}}.

" "You can add these placeholders either in the body of the request or in the headers. " "FRequest will replace them automatically when authenticating by the username and password that you input above." ); } void ProjectProperties::fillInterface(){ ui->leProjectName->setText(this->projectItem->projectName); ui->leProjectMainUrl->setText(this->projectItem->projectMainUrl); // Get all requests name to fill request combobox for(int i=0; i < this->projectItem->childCount(); i++){ FRequestTreeWidgetRequestItem* currentRequest = FRequestTreeWidgetRequestItem::fromQTreeWidgetItem(this->projectItem->child(i)); ui->cbRequestForAuthentication->addItem(getComboBoxNameForRequest(currentRequest), QVariant::fromValue(currentRequest)); } ui->cbIdentCharacter->setCurrentText(UtilFRequest::getIdentCharacterString(this->projectItem->saveIdentCharacter)); for (int i = 0; i < this->projectItem->globalHeaders.size(); i++) { const UtilFRequest::HttpHeader &currGlobalHeader = this->projectItem->globalHeaders.at(i); Util::TableWidget::addRow(ui->twGlobalHeaderKeyValue, QStringList() << currGlobalHeader.name << currGlobalHeader.value); } } ProjectProperties::~ProjectProperties() { delete ui; } void ProjectProperties::on_cbRequestType_currentIndexChanged(const QString &arg1) { ui->cbRequestForAuthentication->setEnabled(false); if(arg1 == "Request Authentication"){ ui->cbRequestForAuthentication->setEnabled(true); } setRequestAuthenticationNote(); } // Need to override to do the verification // http://stackoverflow.com/questions/3261676/how-to-make-qdialogbuttonbox-not-close-its-parent-qdialog void ProjectProperties::accept (){ // Validations if(Util::Validation::checkEmptySpaces( QStringList() << ui->leProjectName->text() << ui->leProjectMainUrl->text() )){ Util::Dialogs::showError("Please fill the project name and main url."); return; } if(ui->cbUseAuthentication->isChecked() && Util::Validation::checkEmptySpaces( QStringList() << ui->leUsername->text() )){ Util::Dialogs::showError("Please fill the authorization username and authorization password."); return; } this->projectItem->projectName = ui->leProjectName->text(); this->projectItem->setText(0, this->projectItem->projectName); // todo replace column with enum this->projectItem->projectMainUrl = ui->leProjectMainUrl->text(); if(ui->cbUseAuthentication->isChecked()){ switch(FRequestAuthentication::getAuthenticationTypeByString(ui->cbRequestType->currentText())){ case FRequestAuthentication::AuthenticationType::REQUEST_AUTHENTICATION: { this->projectItem->authData = std::make_shared( ui->rbSaveProjectAuthToConfigurationFile->isChecked(), ui->cbRetryLoginIfError401->isChecked(), ui->leUsername->text(), this->currentPasswordSalt, ui->lePassword->text(), qvariant_cast(ui->cbRequestForAuthentication->itemData(ui->cbRequestForAuthentication->currentIndex()))->itemContent.uuid ); break; } case FRequestAuthentication::AuthenticationType::BASIC_AUTHENTICATION: { this->projectItem->authData = std::make_shared(BasicAuthentication(ui->rbSaveProjectAuthToConfigurationFile->isChecked(), ui->cbRetryLoginIfError401->isChecked(), ui->leUsername->text(), this->currentPasswordSalt, ui->lePassword->text() )); break; } default: { QString errorMessage = "Authentication type unknown: '" + ui->cbRequestType->currentText() + "'. Program can't proceed."; Util::Dialogs::showError(errorMessage); LOG_FATAL << errorMessage; exit(1); } } } else{ this->projectItem->authData = nullptr; // clear the old authentication data } UtilFRequest::IdentCharacter identCharacter = UtilFRequest::getIdentCharacterByString(ui->cbIdentCharacter->currentText()); switch(identCharacter){ case UtilFRequest::IdentCharacter::SPACE: case UtilFRequest::IdentCharacter::TAB: { this->projectItem->saveIdentCharacter = identCharacter; break; } default: { QString errorMessage = "Ident character unknown: '" + ui->cbIdentCharacter->currentText() + "'. Program can't proceed."; Util::Dialogs::showError(errorMessage); LOG_FATAL << errorMessage; exit(1); } } // Save global headers this->projectItem->globalHeaders.clear(); for (int i = 0; i < ui->twGlobalHeaderKeyValue->rowCount(); i++) { UtilFRequest::HttpHeader currentHeader; currentHeader.name = ui->twGlobalHeaderKeyValue->item(i, 0)->text(); currentHeader.value = ui->twGlobalHeaderKeyValue->item(i, 1)->text(); this->projectItem->globalHeaders.append(currentHeader); } QDialog::accept(); emit signalSaveProjectProperties(); } void ProjectProperties::on_cbUseAuthentication_toggled(bool checked) { ui->gbAuthentication->setEnabled(checked); } void ProjectProperties::on_tbGlobalHeaderKeyValueAdd_clicked() { Util::TableWidget::addRow(ui->twGlobalHeaderKeyValue, QStringList() << "" << ""); } void ProjectProperties::on_tbGlobalHeaderKeyValueRemove_clicked() { int size = Util::TableWidget::getSelectedRows(ui->twGlobalHeaderKeyValue).size(); if(size==0){ Util::Dialogs::showInfo("Select a row first!"); return; } if(Util::Dialogs::showQuestion(this, "Are you sure you want to remove all selected rows?")){ for(int i=0; i < size; i++){ ui->twGlobalHeaderKeyValue->removeRow(Util::TableWidget::getSelectedRows(ui->twGlobalHeaderKeyValue).at(size-i-1).row()); } Util::Dialogs::showInfo("Key-Value rows deleted"); } } void ProjectProperties::fillAuthenticationData(FRequestAuthentication &auth){ ui->cbUseAuthentication->setChecked(true); if(auth.saveAuthToConfigFile){ ui->rbSaveProjectAuthToConfigurationFile->setChecked(true); } else{ ui->rbSaveProjectAuthToProjectFile->setChecked(true); } ui->cbRequestType->setCurrentText(FRequestAuthentication::getAuthenticationString(auth.type)); switch(auth.type){ case FRequestAuthentication::AuthenticationType::REQUEST_AUTHENTICATION: { // https://stackoverflow.com/a/43572369/1499019 RequestAuthentication &concreteAuth = static_cast(auth); ui->leUsername->setText(concreteAuth.username); ui->lePassword->setText(concreteAuth.password); ui->cbRequestForAuthentication->setCurrentIndex( ui->cbRequestForAuthentication->findData(QVariant::fromValue(this->projectItem->getChildRequestByUuid(concreteAuth.requestForAuthenticationUuid))) ); this->currentPasswordSalt = concreteAuth.passwordSalt; break; } case FRequestAuthentication::AuthenticationType::BASIC_AUTHENTICATION: { BasicAuthentication &concreteAuth = static_cast(auth); ui->leUsername->setText(concreteAuth.username); ui->lePassword->setText(concreteAuth.password); this->currentPasswordSalt = concreteAuth.passwordSalt; break; } default: { QString errorMessage = "Invalid authentication type " + QString::number(static_cast(auth.type)) + "'. Program can't proceed."; Util::Dialogs::showError(errorMessage); LOG_FATAL << errorMessage; exit(1); } } ui->cbRetryLoginIfError401->setChecked(auth.retryLoginIfError401); } QString ProjectProperties::getComboBoxNameForRequest(const FRequestTreeWidgetRequestItem* const currentRequest){ return currentRequest->itemContent.name + " (" + UtilFRequest::getRequestTypeString(currentRequest->itemContent.requestType) + ")"; } void ProjectProperties::setRequestAuthenticationNote(){ if(ui->cbRequestType->currentText() == "Request Authentication"){ ui->saProjectPropertiesNote->setVisible(true); } else{ ui->saProjectPropertiesNote->setVisible(false); } } ================================================ FILE: projectproperties.h ================================================ /* * 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 . * */ #ifndef PROJECTPROPERTIES_H #define PROJECTPROPERTIES_H #include #include #include "customtreewidget.h" #include "Widgets/frequesttreewidgetprojectitem.h" #include "Authentications/basicauthentication.h" #include "Authentications/requestauthentication.h" namespace Ui { class ProjectProperties; } class ProjectProperties : public QDialog { Q_OBJECT public: explicit ProjectProperties(QWidget *parent, FRequestTreeWidgetProjectItem * const projectItem); ~ProjectProperties(); signals: void signalSaveProjectProperties(); private slots: void on_cbRequestType_currentIndexChanged(const QString &arg1); void accept (); void on_cbUseAuthentication_toggled(bool checked); void on_tbGlobalHeaderKeyValueAdd_clicked(); void on_tbGlobalHeaderKeyValueRemove_clicked(); private: void fillInterface(); void fillAuthenticationData(FRequestAuthentication &auth); QString getComboBoxNameForRequest(const FRequestTreeWidgetRequestItem* const currentRequest); void setRequestAuthenticationNote(); private: Ui::ProjectProperties *ui; FRequestTreeWidgetProjectItem* const projectItem; // not const because we can update its name in this class QString currentPasswordSalt; }; #endif // PROJECTPROPERTIES_H ================================================ FILE: projectproperties.ui ================================================ ProjectProperties 0 0 689 675 Project Properties 0 QLayout::SetMaximumSize 9 9 9 9 0 General 0 0 true Project Properties Qt::AlignJustify|Qt::AlignVCenter QLayout::SetMaximumSize General Project Name: Project Main Url: On Save Specifies the type of white space to use when identing the project xml file (on save). Ident character: Specifies the type of white space to use when identing the project xml file (on save). Space Tab Qt::Vertical 20 40 Global Headers 0 20 Any header added here will be appended to all requests in this project. They will be shown in the request table as disabled rows. Their values can be overwritten if a header with the same key is added to the specific request headers. true QLayout::SetMaximumSize 0 0 true true Key Value Add new row ... :/icons/plus.png:/icons/plus.png Remove selected rows ... :/icons/minus.png:/icons/minus.png Authentication Use Authentication false Authentication Save Project Authentication to: Saves the authentication data to Frequest configuration file, even if you share the project file the authentication data is not shared FRequest Configuration File true Saves the authentication data to the Frequest project file, so if you share your project file the authentication data is also shared FRequest Project File Authentication Type: Request Authentication Basic Authentication Request for Authentication: Username: Password: QLineEdit::Password Retry login if the HTTP error 401 (Unauthorized) is received on a request true true 0 0 623 175 Note: true Qt::LinksAccessibleByMouse|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse Qt::Vertical 20 40 Qt::Horizontal QDialogButtonBox::Cancel|QDialogButtonBox::Ok buttonBox accepted() ProjectProperties accept() 248 254 157 274 buttonBox rejected() ProjectProperties reject() 316 260 286 274 ================================================ FILE: proxysetup.cpp ================================================ /* * 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 . * */ #include "proxysetup.h" void ProxySetup::setupProxyForNetworkManager(const ConfigFileFRequest::Settings &settings, QNetworkAccessManager * const networkAccessManager){ QNetworkProxy proxy; if(settings.useProxy){ switch (settings.proxySettings.type) { case ConfigFileFRequest::ProxyType::AUTOMATIC: { QNetworkProxyFactory::setUseSystemConfiguration(true); break; } case ConfigFileFRequest::ProxyType::HTTP_TRANSPARENT: { proxy.setType(QNetworkProxy::HttpProxy); break; } case ConfigFileFRequest::ProxyType::HTTP: { proxy.setType(QNetworkProxy::HttpCachingProxy); break; } case ConfigFileFRequest::ProxyType::SOCKS5: { proxy.setType(QNetworkProxy::Socks5Proxy); break; } default: { QString errorMessage = "Unknown proxy type set! '" + QString::number(static_cast(settings.proxySettings.type)) + "'. Check the proxy settings."; Util::Dialogs::showError(errorMessage); LOG_ERROR << errorMessage; return; } } if(settings.proxySettings.type != ConfigFileFRequest::ProxyType::AUTOMATIC){ QNetworkProxyFactory::setUseSystemConfiguration(false); proxy.setHostName(settings.proxySettings.hostName); proxy.setPort(settings.proxySettings.portNumber); } } else{ proxy.setType(QNetworkProxy::NoProxy); } networkAccessManager->setProxy(proxy); } ================================================ FILE: proxysetup.h ================================================ /* * 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 . * */ #ifndef PROXYSETUP_H #define PROXYSETUP_H #include #include #include "XmlParsers/configfilefrequest.h" class ProxySetup { public: static void setupProxyForNetworkManager(const ConfigFileFRequest::Settings &settings, QNetworkAccessManager * const networkAccessManager); }; #endif // PROXYSETUP_H ================================================ FILE: readme.txt ================================================ readme.txt ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ FRequest v1.2a ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ---------------------------------- Description: ---------------------------------- FRequest is a fast, lightweight and opensource Windows / macOS / Linux desktop program to make HTTP(s) requests (e.g. call REST apis). The main motivation for the program is to create a similar working software to an IDE but for HTTP(s) apis. It should be fast, cross platform, lightweight, practical with a native look. Also it is important that project files can be easily shared and work seamless with Version Control System (VCS) for collaborative work. The current features of FRequest are: - Make GET / POST / PUT / DELETE / PATCH / HEAD / TRACE / OPTIONS HTTP(s) requests - Make HTTP requests with RAW / Form Data or X-Form-WWW-UrlEncoded body types - Send file uploads over the HTTP body type Form Data - Analyze the requests response body and headers - Requests are contained in a project, this project is then saved in XML file on user's desired location - Ability to override a project main url, so you can make requests to different domain name addresses within the same project - Ability to download files from the requests - Automatically beautify and apply syntax highlighting for JSON and XML - Support for authentication (HTTP Basic authentication and Request based authentication) which can be saved either in the program configuration file (for private use) or the project file itself (for shared use) - The FRequest project files are stored in a way which allow easy collaboration via a VCS like Git, Svn or Team Foundation Server - Ability to add any kind of custom HTTP headers to the requests (automatically by taking the type in account or adding them manually) - Global headers, headers that are applied to every request in the project - Network proxy support FRequest is licensed under GPL 3.0 (https://www.gnu.org/licenses/gpl-3.0.en.html). ---------------------------------- Supported operating system: ---------------------------------- - Windows 7 SP1 and above - macOS High Sierra (10.13) and above - Ubuntu 18.04 and above (other Linux distributions dated similar should likely work but are not tested) ---------------------------------- Installation: ---------------------------------- Windows / macOS: Just extract the inner FRequest folder to any place in your computer. Run the executable. Linux: Extract the inner FRequest folder to any place in your computer, make it executable (chmod +x) and run the executable. You may need to install openssl 1.1.1 to get the ssl requests to work properly (and also to check for updates within the program). In ubuntu (18.04) you can do it like this: sudo apt-get install openssl ---------------------------------- Upgrading: ---------------------------------- Windows / macOS: You should make a backup of your previous installation folder, just in case. After this backup, extract the files from this zip version to your previous FRequest installation folder (replace all files). Linux: You should make a backup of your previous installation folder, just in case. After this backup, just replace the previous AppImage with the new one. ---------------------------------- Contacts: ---------------------------------- Author: fabiobento512 (https://github.com/fabiobento512) Official page: https://fabiobento512.github.io/FRequest/ GitHub code page: https://github.com/fabiobento512/FRequest ---------------------------------- Change Log: ---------------------------------- 1.2a, 13-03-2022 - Upgraded Qt version on all platforms to 15.5.2, this fixes the openssl issue for linux users (the problem that 1.0.1 is not the repositories anymore) and provides support for TLS 1.3 - Added github actions builds, which simplifies the building on the three supported operating systems a lot - Minor code refactoring ---------------------------------- 1.2, 18-05-2021 - Added global headers feature (thanks alevalv) - Now request/reponse area is scrollabled (thanks fcolecumberri) - Now request/reponse text uses courier new font (monospace) (thanks KaKi87 for the monospace suggestion) ---------------------------------- 1.1c, 20-01-2019 - Added official support for Linux (tests are made in Ubuntu LTS and the program is distributed using an appimage) - Fixed not showing body/headers response when an HTTP status code error is received like (500) (issue #7) - Fixed timeout status code/message, when the internal FRequest timeout for a request is reached (issue #8) - Added option in project settings to specify the type of character identation to use (space or tab) in the project xml file (issue #9) ---------------------------------- 1.1b, 04-03-2018 - Added dark theme (thanks Jorgen-VikingGod!) - Added a clear button for the filter text box - Fixed possible system implementation of passwords obfuscation (you may need to re-enter your project passwords) - Some code refactoring (using now override C++ keyword for instance) ---------------------------------- 1.1a, 03-02-2018 - Added rename request / project to requests tree context menu (thanks pingzing!) - Added shortcut to delete requests (DEL) - Added an icon to delete request context menu - Improved config/project files upgrade code - Now it is possible to set the maximum response data size for display - Fixed bug: on a new project, after saving the project properties the body data of the selected request may be cleared - Now macOS users are warned about "App Translocation" when the application can't create its .config file - Added check for updates option in help menu ---------------------------------- 1.1, 28-01-2018 - Morphed the QTextEdits to QPlainTextEdits in order to increase render performance for requests and responses data - Now when the data is bigger than 200 kb only the first 200 kb are displayed in the interface, the remaining data is written to the disk if the request is marked to download (avoids slowdowns and possible crashes) - Fixed bug where if the first request being loaded had overridden url the url didn't loaded - Fixed bug where timeout 0 instead of mean no timeout, meant instant timeout - Fixed bug where the first item loaded, if changed and then the project was saved, it wouldn't get properly saved - Fixed bug where form-data were sending data in the format of x-www-form-urlencoded instead of form-data - Now it is possible to cancel a running request - Added icons for request types - Some code refactoring - Added icon to clone context menu - Now when the project is selected in the requests tree the number of the requests for that project is displayed in the status bar - Added support for file uploads - Upgraded to Qt 5.10.0 - Now TRACE method should allow send of form and raw content - Added support for XML highlighting - Now cookies received by each request are saved by default (so they may be sent in next requests) - Added requests filter so you can quickly find your requests - Added authentication support (starting with Request authentication and HTTP Basic Authentication) - Fixed the save of proxy settings - Hide toolbar since it is unused ---------------------------------- 1.0, 18-08-2017 - Initial Version ================================================ FILE: updatechecker.cpp ================================================ /* * 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 . * */ #include "updatechecker.h" UpdateChecker::UpdateChecker(const ConfigFileFRequest::Settings &settings) :settings(settings) { this->networkRequest.setUrl(QUrl(this->updateCheckApiUrl)); } void UpdateChecker::startNewInstance(const ConfigFileFRequest::Settings &settings){ UpdateChecker *newInstance = new UpdateChecker(settings); newInstance->checkForUpdates(); // this deletes itself once finished } void UpdateChecker::checkForUpdates(){ // Apply proxy type ProxySetup::setupProxyForNetworkManager(this->settings, &this->networkAccessManager); connect(&this->networkAccessManager, &QNetworkAccessManager::finished, this, &UpdateChecker::replyFinished); // do the request and also check for timeout checkForQNetworkAccessManagerTimeout(this->networkAccessManager.get(this->networkRequest)); this->deleteLater(); // delete when signal / slots are finished } void UpdateChecker::replyFinished(QNetworkReply *reply){ try{ if(!this->replyHasFinished){ if (reply->error()) { throw std::runtime_error(QSTR_TO_TEMPORARY_CSTR(reply->errorString())); } QString answer = reply->readAll(); QJsonDocument doc = QJsonDocument::fromJson(answer.toUtf8()); if(!doc.isObject()){ throw std::runtime_error("(http api error) json is not an object."); } QJsonObject jsonObj = doc.object(); QJsonValue jsonProgramLastVersion = jsonObj.value("tag_name"); if(jsonProgramLastVersion.isUndefined()){ throw std::runtime_error("(http api error) json tag_name doesn't exist."); } QString newVersion = jsonProgramLastVersion.toString(); // remove v (from v1.0 for example) if it exists if(newVersion.startsWith("v")){ newVersion.remove(0,1); // remove first character } if(newVersion != GlobalVars::AppVersion){ Util::Dialogs::showInfo ( "There's a new version of " + GlobalVars::AppName + "! (v" + newVersion + ")

"+ "You can download it here.", true ); } else{ Util::Dialogs::showInfo("You are using last version."); } } } catch(const std::exception& e){ QString errorMessage = "An error ocurred while checking for updates: " + QString(e.what()); LOG_ERROR << errorMessage; Util::Dialogs::showError(errorMessage); } this->replyHasFinished = true; } // Since QNetworkReply doesn't have a way to set a timeout we need implement it by ourselves // http://stackoverflow.com/a/13229926 void UpdateChecker::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(10 * 1000); // 10 seconds hardcoded timeout loop.exec(); if(timer.isActive()) // request didn't timeout { timer.stop(); } else if(!this->replyHasFinished) { // timeout // TODO this class is a bit confusing, // especially when we are using a boolean to check if the reply has already finished // (we are doing that because if user doesn't close success dialog, a second call is emitted to replyFinished function // after 10 secs (timeout) // If possible this should be refactored to a simpler method this->replyHasFinished = true; disconnect(reply, SIGNAL(finished()), &loop, SLOT(quit())); reply->abort(); QString errorMessage = "Timeout while checking for updates.

You still can check manually, by clicking here."; Util::Dialogs::showError(errorMessage, true); LOG_ERROR << errorMessage; } reply->deleteLater(); } ================================================ FILE: updatechecker.h ================================================ /* * 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 . * */ #ifndef UPDATECHECKER_H #define UPDATECHECKER_H #include #include #include #include #include #include "utilglobalvars.h" #include "proxysetup.h" class UpdateChecker: public QObject /* inheritance needed for signal / slots */ { Q_OBJECT /* Q_OBJECT needed for signal / slots */ public: static void startNewInstance(const ConfigFileFRequest::Settings &settings); private: // not meant to be instantiated directly, use startNewInstance instead UpdateChecker(const ConfigFileFRequest::Settings &settings); private: void checkForUpdates(); void replyFinished(QNetworkReply *reply); void checkForQNetworkAccessManagerTimeout(QNetworkReply *reply); private: QNetworkAccessManager networkAccessManager; QNetworkRequest networkRequest; const ConfigFileFRequest::Settings settings; const QString updateCheckApiUrl = "https://api.github.com/repos/fabiobento512/FRequest/releases/latest"; const QString releasesUrl = "https://github.com/fabiobento512/FRequest/releases"; bool replyHasFinished = false; }; #endif // UPDATECHECKER_H ================================================ FILE: utilfrequest.cpp ================================================ /* * 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 . * */ #include "utilfrequest.h" namespace UtilFRequest{ QString getDocumentsFolder(){ QString result = Util::FileSystem::normalizePath(QStandardPaths::locate(QStandardPaths::DocumentsLocation, QString(), QStandardPaths::LocateDirectory)); if(result.endsWith("/")){ result = result.remove(result.size()-1,1); } return result; } RequestType getRequestTypeByString(const QString ¤tRequestText){ if(currentRequestText == "GET"){ return RequestType::GET_OPTION; } else if(currentRequestText == "POST"){ return RequestType::POST_OPTION; } else if(currentRequestText == "PUT"){ return RequestType::PUT_OPTION; } else if(currentRequestText == "DELETE"){ return RequestType::DELETE_OPTION; } else if(currentRequestText == "PATCH"){ return RequestType::PATCH_OPTION; } else if(currentRequestText == "HEAD"){ return RequestType::HEAD_OPTION; } else if(currentRequestText == "TRACE"){ return RequestType::TRACE_OPTION; } else if(currentRequestText == "OPTIONS"){ return RequestType::OPTIONS_OPTION; } else{ QString errorMessage = "Request type unknown: '" + currentRequestText + "'. Program can't proceed."; Util::Dialogs::showError(errorMessage); LOG_FATAL << errorMessage; exit(1); } } QString getRequestTypeString(const RequestType currentRequestType){ switch(currentRequestType){ case UtilFRequest::RequestType::GET_OPTION: return "GET"; case UtilFRequest::RequestType::POST_OPTION: return "POST"; case UtilFRequest::RequestType::PUT_OPTION: return "PUT"; case UtilFRequest::RequestType::DELETE_OPTION: return "DELETE"; case UtilFRequest::RequestType::PATCH_OPTION: return "PATCH"; case UtilFRequest::RequestType::HEAD_OPTION: return "HEAD"; case UtilFRequest::RequestType::TRACE_OPTION: return "TRACE"; case UtilFRequest::RequestType::OPTIONS_OPTION: return "OPTIONS"; default: { QString errorMessage = "Invalid request type " + QString::number(static_cast(currentRequestType)) + "'. Program can't proceed."; Util::Dialogs::showError(errorMessage); LOG_FATAL << errorMessage; exit(1); } } } bool requestTypeMayHaveBody(RequestType currentRequestType){ bool mayHaveBody = false; switch(currentRequestType){ case UtilFRequest::RequestType::GET_OPTION: case UtilFRequest::RequestType::DELETE_OPTION: case UtilFRequest::RequestType::HEAD_OPTION: { mayHaveBody = false; break; } case UtilFRequest::RequestType::POST_OPTION: case UtilFRequest::RequestType::PUT_OPTION: case UtilFRequest::RequestType::PATCH_OPTION: case UtilFRequest::RequestType::OPTIONS_OPTION: case UtilFRequest::RequestType::TRACE_OPTION: { mayHaveBody = true; break; } default: { QString errorMessage = "Request type unknown: '" + QString::number(static_cast(currentRequestType)) + "'. Program can't proceed."; Util::Dialogs::showError(errorMessage); LOG_FATAL << errorMessage; exit(1); } } return mayHaveBody; } QString getDateTimeFormatForFilename(const QDateTime ¤tDateTime){ return currentDateTime.toString("yyyy-MM-dd_hh-mm-ss"); } FormKeyValueType getFormKeyTypeByString(const QString ¤tFormKeyValueString){ if(currentFormKeyValueString == "Text"){ return FormKeyValueType::TEXT; } else if(currentFormKeyValueString == "File"){ return FormKeyValueType::FILE; } else{ QString errorMessage = "FormKeyValue type unknown: '" + currentFormKeyValueString + "'. Program can't proceed."; Util::Dialogs::showError(errorMessage); LOG_FATAL << errorMessage; exit(1); } } QString getFormKeyTypeString(const FormKeyValueType currentFormKeyValueType){ switch(currentFormKeyValueType){ case UtilFRequest::FormKeyValueType::TEXT: return "Text"; case UtilFRequest::FormKeyValueType::FILE: return "File"; default: { QString errorMessage = "Invalid form key type " + QString::number(static_cast(currentFormKeyValueType)) + "'. Program can't proceed."; Util::Dialogs::showError(errorMessage); LOG_FATAL << errorMessage; exit(1); } } } BodyType getBodyTypeByString(const QString ¤tBodyTypeText){ if(currentBodyTypeText == "raw"){ return BodyType::RAW; } else if(currentBodyTypeText == "form-data"){ return BodyType::FORM_DATA; } else if(currentBodyTypeText == "x-form-www-urlencoded"){ return BodyType::X_FORM_WWW_URLENCODED; } else{ QString errorMessage = "BodyType type unknown: '" + currentBodyTypeText + "'. Program can't proceed."; Util::Dialogs::showError(errorMessage); LOG_FATAL << errorMessage; exit(1); } } QString getBodyTypeString(const BodyType currentBodyType){ switch(currentBodyType){ case UtilFRequest::BodyType::RAW: { return "raw"; } case UtilFRequest::BodyType::FORM_DATA: { return "form-data"; } case UtilFRequest::BodyType::X_FORM_WWW_URLENCODED: { return "x-form-www-urlencoded"; } default: { QString errorMessage = "Invalid body type " + QString::number(static_cast(currentBodyType)) + "'. Program can't proceed."; Util::Dialogs::showError(errorMessage); LOG_FATAL << errorMessage; exit(1); } } } IdentCharacter getIdentCharacterByString(const QString ¤tIdentCharacterText){ if(currentIdentCharacterText == "Space"){ return IdentCharacter::SPACE; } else if(currentIdentCharacterText == "Tab"){ return IdentCharacter::TAB; } else{ QString errorMessage = "Ident character unknown: '" + currentIdentCharacterText + "'. Program can't proceed."; Util::Dialogs::showError(errorMessage); LOG_FATAL << errorMessage; exit(1); } } QString getIdentCharacterString(const IdentCharacter currentIdentCharacter){ switch(currentIdentCharacter){ case IdentCharacter::SPACE: return "Space"; case IdentCharacter::TAB: return "Tab"; default: { QString errorMessage = "Invalid ident character " + QString::number(static_cast(currentIdentCharacter)) + "'. Program can't proceed."; Util::Dialogs::showError(errorMessage); LOG_FATAL << errorMessage; exit(1); } } } void addRequestFormBodyRow(QTableWidget * const myTable, const QString &key, const QString &value, const UtilFRequest::FormKeyValueType type){ Util::TableWidget::addRow(myTable, QStringList() << key << value << UtilFRequest::getFormKeyTypeString(type)); // Set type as not editable int tableSize = myTable->rowCount(); QTableWidgetItem* const addedRowTypeItem = myTable->item(tableSize-1, 2); addedRowTypeItem->setFlags(addedRowTypeItem->flags() & (~Qt::ItemIsEditable)); // If it is a file, change the row color to blue in order to differentiate if(type == UtilFRequest::FormKeyValueType::FILE){ myTable->item(tableSize-1, 0)->setForeground(Qt::blue); myTable->item(tableSize-1, 1)->setForeground(Qt::blue); addedRowTypeItem->setForeground(Qt::blue); } } // Return original content in case of error QString getStringFormattedForSerializationType(const QString &content, const SerializationFormatType serializationType){ switch(serializationType){ case UtilFRequest::SerializationFormatType::JSON: { QJsonParseError parseError; QJsonDocument auxJsonDoc = QJsonDocument::fromJson(content.toUtf8(), &parseError); if(parseError.error != QJsonParseError::NoError){ QString errorMessage = "An error occurred while formatting the content as Json: " + content.left(10); Util::Dialogs::showError(errorMessage); LOG_ERROR << errorMessage; return content; } return auxJsonDoc.toJson(); } case UtilFRequest::SerializationFormatType::XML: { pugi::xml_document doc; pugi::xml_parse_result result = doc.load_string(QSTR_TO_TEMPORARY_CSTR(content)); if(result.status != pugi::xml_parse_status::status_ok){ QString errorMessage = "An error occurred while formatting the content as XML: " + content.left(10); Util::Dialogs::showError(errorMessage); LOG_ERROR << errorMessage; return content; } std::stringstream xmlFormattedText; doc.save(xmlFormattedText); return QString::fromStdString(xmlFormattedText.str()); } case UtilFRequest::SerializationFormatType::UNKNOWN: { return content; } default: { QString errorMessage = "Invalid currRequestFormatType " + QString::number(static_cast(serializationType)) + "'. Program can't proceed."; Util::Dialogs::showError(errorMessage); LOG_FATAL << errorMessage; exit(1); } } } SerializationFormatType getSerializationFormatTypeForString(const QString &content){ // Try to parse the response as json, if it fails try xml, otherwise return unknown QJsonParseError parseError; QJsonDocument auxJsonDoc = QJsonDocument::fromJson(content.toUtf8(), &parseError); if(parseError.error == QJsonParseError::NoError){ return UtilFRequest::SerializationFormatType::JSON; } pugi::xml_document doc; pugi::xml_parse_result result = doc.load_string(QSTR_TO_TEMPORARY_CSTR(content)); if(result.status == pugi::xml_parse_status::status_ok){ return UtilFRequest::SerializationFormatType::XML; } return UtilFRequest::SerializationFormatType::UNKNOWN; } QByteArray simpleStringObfuscationDeobfuscation(const QString& ofuscationSalt, const QString &input){ QByteArray saltByteArray = ofuscationSalt.toUtf8(); QByteArray inputByteArray = input.toUtf8(); // Using unsigned types as they have a defined truncation in iso c++: // https://stackoverflow.com/a/34886065 // (so the static_cast below works the same in all different systems) uint32_t saltByteArraySize = static_cast(saltByteArray.size()); uint32_t inputByteArraySize = static_cast(inputByteArray.size()); for(uint32_t i=0; i< inputByteArraySize; i++){ inputByteArray[i] = inputByteArray[i] ^ (i < saltByteArraySize ? saltByteArray[i] : static_cast(i)); } return inputByteArray; } QString replaceFRequestAuthenticationPlaceholders(const QString &textToReplace, const QString &username, const QString &password){ return QString(textToReplace). replace(GlobalVars::FRequestAuthenticationPlaceholderUsername, username). replace(GlobalVars::FRequestAuthenticationPlaceholderPassword, password); } void setGlobalHeaderTableWidgetRow(QTableWidget *myTable, const int rowNumber){ for(int i=0; icolumnCount(); i++){ QTableWidgetItem * const currentItem = myTable->item(rowNumber, i); currentItem->setFlags(currentItem->flags() & ~Qt::ItemIsEditable); currentItem->setBackground(getTableWidgetRowDisabledBackStyle()); currentItem->setForeground(getTableWidgetRowDisabledTextStyle()); // Add tooltip to make clear that it is a global header currentItem->setToolTip("[global header] " + currentItem->toolTip()); } } //Reset a item to its initial style void resetGlobalTableWidgetRow(QTableWidget *myTable, const int rowNumber){ for(int i=0; icolumnCount(); i++){ QTableWidgetItem * const currentItem = myTable->item(rowNumber, i); currentItem->setFlags(currentItem->flags() & Qt::ItemIsEditable); if((currentItem->row()+1)%2==0){ //if the row number is par it use the alternate color scheme currentItem->setBackground(QPalette().brush(QPalette::Normal,QPalette::AlternateBase)); } else{ currentItem->setBackground(QPalette().brush(QPalette::Normal,QPalette::Base)); } currentItem->setForeground(QPalette().brush(QPalette::Normal,QPalette::WindowText)); } } bool isGlobalHeaderTableWidgetRow(QTableWidget *myTable, const int rowNumber){ if(myTable->columnCount() <= 0){ return true; } const QTableWidgetItem * const currItem = myTable->item(rowNumber, 0); return currItem->background() == getTableWidgetRowDisabledBackStyle() && currItem->foreground() == getTableWidgetRowDisabledTextStyle(); } QBrush getTableWidgetRowDisabledBackStyle(){ return QTableWidget().palette().brush(QPalette::Disabled,QPalette::Base); } QBrush getTableWidgetRowDisabledTextStyle(){ return QTableWidget().palette().brush(QPalette::Disabled,QPalette::WindowText); } } ================================================ FILE: utilfrequest.h ================================================ /* * 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 . * */ #ifndef UTILFREQUEST_H #define UTILFREQUEST_H #include "util.h" // PLog library (log library) // https://github.com/SergiusTheBest/plog #include #include #include #include #include #include #include #include #include #include "Authentications/frequestauthentication.h" #include "utilglobalvars.h" namespace UtilFRequest{ struct HttpHeader{ QString name; QString value; }; // Update the vector bellow always that you update this enum enum class RequestType{ GET_OPTION = 0, POST_OPTION = 1, PUT_OPTION = 2, DELETE_OPTION = 3, PATCH_OPTION = 4, HEAD_OPTION = 5, TRACE_OPTION = 6, OPTIONS_OPTION = 7 }; const QVector possibleRequestTypes = { UtilFRequest::RequestType::GET_OPTION, UtilFRequest::RequestType::POST_OPTION, UtilFRequest::RequestType::PUT_OPTION, UtilFRequest::RequestType::DELETE_OPTION, UtilFRequest::RequestType::PATCH_OPTION, UtilFRequest::RequestType::HEAD_OPTION, UtilFRequest::RequestType::TRACE_OPTION, UtilFRequest::RequestType::OPTIONS_OPTION }; enum class BodyType{ RAW = 0, FORM_DATA = 1, X_FORM_WWW_URLENCODED = 2 }; enum class FormKeyValueType{ TEXT = 0, FILE = 1 }; enum class SerializationFormatType{ UNKNOWN = 0, JSON = 1, XML = 2 }; enum class IdentCharacter{ SPACE = 0, TAB = 1 }; struct HttpFormKeyValueType{ QString key; QString value; FormKeyValueType type; HttpFormKeyValueType(){} HttpFormKeyValueType(const QString &key, const QString &value, const FormKeyValueType type){ this->key = key; this->value = value; this->type = type; } }; struct RequestInfo{ bool bOverridesMainUrl = false; QString overrideMainUrl; QString name; QString path; RequestType requestType = RequestType::GET_OPTION; BodyType bodyType = BodyType::RAW; QString body; QVector bodyForm; QVector headers; bool bDownloadResponseAsFile = false; QString uuid; unsigned long long int order = 0; bool bDisableGlobalHeaders = true; }; static QMimeDatabase mimeDatabase; QString getDocumentsFolder(); bool requestTypeMayHaveBody(RequestType currentRequestType); RequestType getRequestTypeByString(const QString ¤tRequestText); QString getRequestTypeString(const RequestType currentRequestType); FormKeyValueType getFormKeyTypeByString(const QString ¤tFormKeyValueString); QString getFormKeyTypeString(const FormKeyValueType currentFormKeyValueType); BodyType getBodyTypeByString(const QString ¤tBodyTypeText); QString getBodyTypeString(const BodyType currentBodyType); IdentCharacter getIdentCharacterByString(const QString ¤tIdentCharacterText); QString getIdentCharacterString(const IdentCharacter currentIdentCharacter); QString getDateTimeFormatForFilename(const QDateTime ¤tDateTime); void addRequestFormBodyRow(QTableWidget * const myTable, const QString &key, const QString &value, const UtilFRequest::FormKeyValueType type); // Return original content in case of error QString getStringFormattedForSerializationType(const QString &content, const SerializationFormatType serializationType); SerializationFormatType getSerializationFormatTypeForString(const QString &content); // Simply ofuscation just to not store password string as plain text in project / configuration files // (it does not protect the password, just obfuscates so can't be read directly) // Applies a simple xor with the given salt QByteArray simpleStringObfuscationDeobfuscation(const QString& ofuscationSalt, const QString &input); // Replaces the textToReplace string with the actual username and password given (uses the FRequest Auth Placeholders for the replace) QString replaceFRequestAuthenticationPlaceholders(const QString &textToReplace, const QString &username, const QString &password); void setGlobalHeaderTableWidgetRow(QTableWidget *myTable, const int rowNumber); void resetGlobalTableWidgetRow(QTableWidget *myTable, const int rowNumber); bool isGlobalHeaderTableWidgetRow(QTableWidget *myTable, const int rowNumber); // we can't use a static object for this because we will receive an error: // "QWidget: Must construct a QApplication before a QWidget" QBrush getTableWidgetRowDisabledBackStyle(); QBrush getTableWidgetRowDisabledTextStyle(); } #endif // UTILFREQUEST_H ================================================ FILE: utilglobalvars.h ================================================ /* * 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 . * */ #ifndef UTILGLOBALVARS_H #define UTILGLOBALVARS_H namespace GlobalVars{ static const QString AppName = "FRequest"; static const QString AppVersion = "1.2a"; static const QString LastCompatibleVersionConfig = "1.2"; static const QString LastCompatibleVersionProjects= "1.2"; static const QString AppConfigFileName = AppName + ".cfg"; static const QString AppLogFileName = AppName.toLower() + ".log"; static const QString FRequestAuthenticationPlaceholderUsername = "{{FREQUEST_AUTH_USERNAME}}"; static const QString FRequestAuthenticationPlaceholderPassword = "{{FREQUEST_AUTH_PASSWORD}}"; static constexpr int AppRecentProjectsMaxSize=6; } #endif // UTILGLOBALVARS_H