mirror of
https://github.com/amnezia-vpn/amnezia-client.git
synced 2026-07-03 14:07:39 +02:00
Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 7e6f029e18 | |||
| 4f8e1da751 | |||
| eb1188ccd7 | |||
| 10289fdb26 | |||
| 511ce6f62a | |||
| 3a7d285e55 | |||
| 6123268846 | |||
| 49d111d1fe | |||
| b591dd7445 | |||
| a45bb5ea4f |
@@ -10,10 +10,10 @@ env:
|
||||
|
||||
jobs:
|
||||
Build-Linux-Ubuntu:
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: 4-core
|
||||
|
||||
env:
|
||||
QT_VERSION: 6.9.2
|
||||
QT_VERSION: 6.8.3
|
||||
QIF_VERSION: 4.7
|
||||
PROD_AGW_PUBLIC_KEY: ${{ secrets.PROD_AGW_PUBLIC_KEY }}
|
||||
PROD_S3_ENDPOINT: ${{ secrets.PROD_S3_ENDPOINT }}
|
||||
@@ -30,13 +30,15 @@ jobs:
|
||||
version: ${{ env.QT_VERSION }}
|
||||
host: 'linux'
|
||||
target: 'desktop'
|
||||
arch: 'gcc_64'
|
||||
arch: 'linux_gcc_64'
|
||||
modules: 'qtremoteobjects qt5compat qtshadertools'
|
||||
dir: ${{ runner.temp }}
|
||||
setup-python: 'true'
|
||||
tools: 'tools_ifw'
|
||||
set-env: 'true'
|
||||
extra: '--external 7z --base ${{ env.QT_MIRROR }}'
|
||||
aqtversion: '==3.3.0'
|
||||
py7zrversion: '==0.22.*'
|
||||
extra: '--base ${{ env.QT_MIRROR }}'
|
||||
|
||||
- name: 'Get sources'
|
||||
uses: actions/checkout@v4
|
||||
@@ -51,8 +53,8 @@ jobs:
|
||||
echo "VERSION=$VERSION" >> $GITHUB_ENV
|
||||
echo "Version: $VERSION"
|
||||
|
||||
- name: 'Setup ccache'
|
||||
uses: hendrikmuhs/ccache-action@v1.2
|
||||
# - name: 'Setup ccache'
|
||||
# uses: hendrikmuhs/ccache-action@v1.2
|
||||
|
||||
- name: 'Build project'
|
||||
run: |
|
||||
@@ -91,7 +93,7 @@ jobs:
|
||||
runs-on: windows-latest
|
||||
|
||||
env:
|
||||
QT_VERSION: 6.9.2
|
||||
QT_VERSION: 6.10.1
|
||||
QIF_VERSION: 4.7
|
||||
BUILD_ARCH: 64
|
||||
PROD_AGW_PUBLIC_KEY: ${{ secrets.PROD_AGW_PUBLIC_KEY }}
|
||||
@@ -117,8 +119,8 @@ jobs:
|
||||
echo "VERSION=$VERSION" >> $GITHUB_ENV
|
||||
echo "Version: $VERSION"
|
||||
|
||||
- name: 'Setup ccache'
|
||||
uses: hendrikmuhs/ccache-action@v1.2
|
||||
# - name: 'Setup ccache'
|
||||
# uses: hendrikmuhs/ccache-action@v1.2
|
||||
|
||||
- name: 'Install Qt'
|
||||
uses: jurplel/install-qt-action@v3
|
||||
@@ -126,13 +128,15 @@ jobs:
|
||||
version: ${{ env.QT_VERSION }}
|
||||
host: 'windows'
|
||||
target: 'desktop'
|
||||
arch: 'win64_msvc2019_64'
|
||||
arch: 'win64_msvc2022_64'
|
||||
modules: 'qtremoteobjects qt5compat qtshadertools'
|
||||
dir: ${{ runner.temp }}
|
||||
setup-python: 'true'
|
||||
tools: 'tools_ifw'
|
||||
set-env: 'true'
|
||||
extra: '--external 7z --base ${{ env.QT_MIRROR }}'
|
||||
aqtversion: '==3.3.0'
|
||||
py7zrversion: '==0.22.*'
|
||||
extra: '--base ${{ env.QT_MIRROR }}'
|
||||
|
||||
- name: 'Setup mvsc'
|
||||
uses: ilammy/msvc-dev-cmd@v1
|
||||
@@ -158,7 +162,7 @@ jobs:
|
||||
shell: cmd
|
||||
run: |
|
||||
set BUILD_ARCH=${{ env.BUILD_ARCH }}
|
||||
set QT_BIN_DIR="${{ runner.temp }}\\Qt\\${{ env.QT_VERSION }}\\msvc2019_64\\bin"
|
||||
set QT_BIN_DIR="${{ runner.temp }}\\Qt\\${{ env.QT_VERSION }}\\msvc2022_64\\bin"
|
||||
set QIF_BIN_DIR="${{ runner.temp }}\\Qt\\Tools\\QtInstallerFramework\\${{ env.QIF_VERSION }}\\bin"
|
||||
set WIX_BIN_DIR=%USERPROFILE%\.dotnet\tools
|
||||
call deploy\\build_windows.bat
|
||||
@@ -195,7 +199,7 @@ jobs:
|
||||
runs-on: macos-latest
|
||||
|
||||
env:
|
||||
QT_VERSION: 6.9.2
|
||||
QT_VERSION: 6.10.1
|
||||
CC: cc
|
||||
CXX: c++
|
||||
PROD_AGW_PUBLIC_KEY: ${{ secrets.PROD_AGW_PUBLIC_KEY }}
|
||||
@@ -254,8 +258,8 @@ jobs:
|
||||
submodules: 'true'
|
||||
fetch-depth: 10
|
||||
|
||||
- name: 'Setup ccache'
|
||||
uses: hendrikmuhs/ccache-action@v1.2
|
||||
# - name: 'Setup ccache'
|
||||
# uses: hendrikmuhs/ccache-action@v1.2
|
||||
|
||||
- name: 'Install dependencies'
|
||||
run: pip install jsonschema jinja2
|
||||
@@ -346,8 +350,8 @@ jobs:
|
||||
submodules: 'true'
|
||||
fetch-depth: 10
|
||||
|
||||
- name: 'Setup ccache'
|
||||
uses: hendrikmuhs/ccache-action@v1.2
|
||||
# - name: 'Setup ccache'
|
||||
# uses: hendrikmuhs/ccache-action@v1.2
|
||||
|
||||
- name: 'Build project'
|
||||
run: |
|
||||
@@ -374,7 +378,7 @@ jobs:
|
||||
runs-on: macos-latest
|
||||
|
||||
env:
|
||||
QT_VERSION: 6.9.2
|
||||
QT_VERSION: 6.10.1
|
||||
|
||||
MAC_TEAM_ID: ${{ secrets.MAC_TEAM_ID }}
|
||||
|
||||
@@ -412,15 +416,11 @@ jobs:
|
||||
arch: 'clang_64'
|
||||
modules: 'qtremoteobjects qt5compat qtshadertools'
|
||||
dir: ${{ runner.temp }}
|
||||
#setup-python: 'true'
|
||||
#set-env: 'true'
|
||||
#extra: '--external 7z --base ${{ env.QT_MIRROR }}'
|
||||
setup-python: 'true'
|
||||
set-env: 'true'
|
||||
aqtversion: '==3.3.0'
|
||||
py7zrversion: '==0.22.*'
|
||||
extra: '--base ${{ env.QT_MIRROR }}'
|
||||
cache: 'true'
|
||||
|
||||
- name: 'Get sources'
|
||||
uses: actions/checkout@v4
|
||||
@@ -435,8 +435,8 @@ jobs:
|
||||
echo "VERSION=$VERSION" >> $GITHUB_ENV
|
||||
echo "Version: $VERSION"
|
||||
|
||||
- name: 'Setup ccache'
|
||||
uses: hendrikmuhs/ccache-action@v1.2
|
||||
# - name: 'Setup ccache'
|
||||
# uses: hendrikmuhs/ccache-action@v1.2
|
||||
|
||||
- name: 'Build project'
|
||||
run: |
|
||||
@@ -467,7 +467,7 @@ jobs:
|
||||
runs-on: macos-latest
|
||||
|
||||
env:
|
||||
QT_VERSION: 6.9.2
|
||||
QT_VERSION: 6.10.1
|
||||
|
||||
MAC_TEAM_ID: ${{ secrets.MAC_TEAM_ID }}
|
||||
|
||||
@@ -519,8 +519,8 @@ jobs:
|
||||
submodules: 'true'
|
||||
fetch-depth: 10
|
||||
|
||||
- name: 'Setup ccache'
|
||||
uses: hendrikmuhs/ccache-action@v1.2
|
||||
# - name: 'Setup ccache'
|
||||
# uses: hendrikmuhs/ccache-action@v1.2
|
||||
|
||||
- name: 'Build project'
|
||||
run: |
|
||||
@@ -537,7 +537,7 @@ jobs:
|
||||
# ------------------------------------------------------
|
||||
|
||||
Build-Android:
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: 4-core
|
||||
|
||||
env:
|
||||
ANDROID_BUILD_PLATFORM: android-36
|
||||
@@ -629,15 +629,15 @@ jobs:
|
||||
echo "VERSION=$VERSION" >> $GITHUB_ENV
|
||||
echo "Version: $VERSION"
|
||||
|
||||
- name: 'Setup ccache'
|
||||
uses: hendrikmuhs/ccache-action@v1.2
|
||||
# - name: 'Setup ccache'
|
||||
# uses: hendrikmuhs/ccache-action@v1.2
|
||||
|
||||
- name: 'Setup Java'
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version: '17'
|
||||
cache: 'gradle'
|
||||
# cache: 'gradle'
|
||||
|
||||
- name: 'Setup Android NDK'
|
||||
id: setup-ndk
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
# User settings
|
||||
*.user
|
||||
|
||||
# Gateway configs (contains sensitive endpoints)
|
||||
gateway.json
|
||||
client/gateway.json
|
||||
macOSPackage/
|
||||
AmneziaVPN.dmg
|
||||
AmneziaVPN.exe
|
||||
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
cmake_minimum_required(VERSION 3.25.0 FATAL_ERROR)
|
||||
|
||||
set(PROJECT AmneziaVPN)
|
||||
set(AMNEZIAVPN_VERSION 4.8.12.5)
|
||||
set(AMNEZIAVPN_VERSION 4.8.12.8)
|
||||
|
||||
project(${PROJECT} VERSION ${AMNEZIAVPN_VERSION}
|
||||
DESCRIPTION "AmneziaVPN"
|
||||
@@ -12,7 +12,7 @@ string(TIMESTAMP CURRENT_DATE "%Y-%m-%d")
|
||||
set(RELEASE_DATE "${CURRENT_DATE}")
|
||||
|
||||
set(APP_MAJOR_VERSION ${CMAKE_PROJECT_VERSION_MAJOR}.${CMAKE_PROJECT_VERSION_MINOR}.${CMAKE_PROJECT_VERSION_PATCH})
|
||||
set(APP_ANDROID_VERSION_CODE 2101)
|
||||
set(APP_ANDROID_VERSION_CODE 2104)
|
||||
|
||||
if(${CMAKE_SYSTEM_NAME} STREQUAL "Linux")
|
||||
set(MZ_PLATFORM_NAME "linux")
|
||||
|
||||
+1
-1
Submodule client/3rd-prebuilt updated: adf5eb920f...51bb4703a4
+22
-4
@@ -33,6 +33,21 @@ add_definitions(-DDEV_S3_ENDPOINT="$ENV{DEV_S3_ENDPOINT}")
|
||||
add_definitions(-DFREE_V2_ENDPOINT="$ENV{FREE_V2_ENDPOINT}")
|
||||
add_definitions(-DPREM_V1_ENDPOINT="$ENV{PREM_V1_ENDPOINT}")
|
||||
|
||||
add_definitions(-DAGW_DNS_SERVER="$ENV{AGW_DNS_SERVER}")
|
||||
add_definitions(-DAGW_DNS_DOMAIN="$ENV{AGW_DNS_DOMAIN}")
|
||||
add_definitions(-DAGW_DNS_PRIMARY="$ENV{AGW_DNS_PRIMARY}")
|
||||
add_definitions(-DAGW_DNS_PORT_UDP="$ENV{AGW_DNS_PORT_UDP}")
|
||||
add_definitions(-DAGW_DNS_PORT_DOT="$ENV{AGW_DNS_PORT_DOT}")
|
||||
add_definitions(-DAGW_DNS_PORT_DOH="$ENV{AGW_DNS_PORT_DOH}")
|
||||
add_definitions(-DAGW_DNS_PORT_DOQ="$ENV{AGW_DNS_PORT_DOQ}")
|
||||
add_definitions(-DAGW_DNS_DOH_PATH="$ENV{AGW_DNS_DOH_PATH}")
|
||||
add_definitions(-DAGW_DNS_RETRY_COUNT="$ENV{AGW_DNS_RETRY_COUNT}")
|
||||
add_definitions(-DAGW_DNS_TIMEOUT_MS="$ENV{AGW_DNS_TIMEOUT_MS}")
|
||||
|
||||
if(DEFINED ENV{AGW_INSECURE_SSL} AND NOT "$ENV{AGW_INSECURE_SSL}" STREQUAL "" AND NOT "$ENV{AGW_INSECURE_SSL}" STREQUAL "0")
|
||||
add_definitions(-DAGW_INSECURE_SSL=1)
|
||||
endif()
|
||||
|
||||
if(WIN32 OR (APPLE AND NOT IOS) OR (LINUX AND NOT ANDROID))
|
||||
set(PACKAGES ${PACKAGES} Widgets)
|
||||
endif()
|
||||
@@ -105,9 +120,6 @@ endif()
|
||||
include(${CMAKE_CURRENT_LIST_DIR}/cmake/3rdparty.cmake)
|
||||
include(${CMAKE_CURRENT_LIST_DIR}/cmake/sources.cmake)
|
||||
|
||||
# Add webview module
|
||||
add_subdirectory(${CMAKE_CURRENT_LIST_DIR}/core/webview)
|
||||
|
||||
include_directories(
|
||||
${CMAKE_CURRENT_LIST_DIR}/../ipc
|
||||
${CMAKE_CURRENT_LIST_DIR}/../common/logger
|
||||
@@ -197,7 +209,7 @@ elseif(APPLE)
|
||||
include(cmake/macos.cmake)
|
||||
endif()
|
||||
|
||||
target_link_libraries(${PROJECT} PRIVATE ${LIBS} webview)
|
||||
target_link_libraries(${PROJECT} PRIVATE ${LIBS})
|
||||
target_compile_definitions(${PROJECT} PRIVATE "MZ_$<UPPER_CASE:${MZ_PLATFORM_NAME}>")
|
||||
|
||||
# deploy artifacts required to run the application to the debug build folder
|
||||
@@ -232,3 +244,9 @@ endif()
|
||||
|
||||
target_sources(${PROJECT} PRIVATE ${SOURCES} ${HEADERS} ${RESOURCES} ${QRC} ${I18NQRC})
|
||||
qt_finalize_target(${PROJECT})
|
||||
|
||||
option(BUILD_TESTS "Build transport integration tests" OFF)
|
||||
if(BUILD_TESTS)
|
||||
enable_testing()
|
||||
add_subdirectory(tests)
|
||||
endif()
|
||||
|
||||
@@ -15,11 +15,6 @@
|
||||
#include <QEvent>
|
||||
#include <QDir>
|
||||
#include <QSettings>
|
||||
#include <QQmlExtensionPlugin>
|
||||
#include <QtPlugin>
|
||||
#include "core/webview/plugin.h"
|
||||
|
||||
Q_IMPORT_PLUGIN(WebViewPlugin)
|
||||
|
||||
#include "logger.h"
|
||||
#include "ui/controllers/pageController.h"
|
||||
@@ -66,10 +61,10 @@ AmneziaApplication::AmneziaApplication(int &argc, char *argv[]) : AMNEZIA_BASE_C
|
||||
AmneziaApplication::~AmneziaApplication()
|
||||
{
|
||||
#ifdef AMNEZIA_DESKTOP
|
||||
if (m_vpnConnection) {
|
||||
QMetaObject::invokeMethod(m_vpnConnection.get(), "disconnectSlots", Qt::QueuedConnection);
|
||||
QMetaObject::invokeMethod(m_vpnConnection.get(), "disconnectFromVpn", Qt::QueuedConnection);
|
||||
QThread::msleep(2000);
|
||||
if (m_vpnConnection && m_vpnConnectionThread.isRunning()) {
|
||||
QMetaObject::invokeMethod(m_vpnConnection.get(), "disconnectSlots", Qt::BlockingQueuedConnection);
|
||||
|
||||
QMetaObject::invokeMethod(m_vpnConnection.get(), "disconnectFromVpn", Qt::BlockingQueuedConnection);
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -82,7 +77,6 @@ AmneziaApplication::~AmneziaApplication()
|
||||
}
|
||||
|
||||
if (m_engine) {
|
||||
QObject::disconnect(m_engine, 0, 0, 0);
|
||||
delete m_engine;
|
||||
}
|
||||
}
|
||||
@@ -104,14 +98,6 @@ void AmneziaApplication::init()
|
||||
{
|
||||
m_engine = new QQmlApplicationEngine;
|
||||
|
||||
// Register AmneziaWebView plugin explicitly
|
||||
QObject *pluginInstance = qt_static_plugin_WebViewPlugin().instance();
|
||||
QQmlExtensionPlugin *p = qobject_cast<QQmlExtensionPlugin*>(pluginInstance);
|
||||
if (p) {
|
||||
p->registerTypes("AmneziaWebView");
|
||||
p->initializeEngine(m_engine, "AmneziaWebView");
|
||||
}
|
||||
|
||||
const QUrl url(QStringLiteral("qrc:/ui/qml/main2.qml"));
|
||||
QObject::connect(
|
||||
m_engine, &QQmlApplicationEngine::objectCreated, this,
|
||||
@@ -143,7 +129,6 @@ void AmneziaApplication::init()
|
||||
m_coreController.reset(new CoreController(m_vpnConnection, m_settings, m_engine));
|
||||
|
||||
m_engine->addImportPath("qrc:/ui/qml/Modules/");
|
||||
m_engine->addImportPath("qrc:/");
|
||||
|
||||
if (m_parser.isSet(m_optImport)) {
|
||||
const QString data = m_parser.value(m_optImport);
|
||||
|
||||
@@ -1,609 +0,0 @@
|
||||
package org.amnezia.vpn;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.app.Activity;
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.Canvas;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.os.SystemClock;
|
||||
import android.util.Log;
|
||||
import android.util.DisplayMetrics;
|
||||
import android.view.ViewGroup;
|
||||
import android.view.MotionEvent;
|
||||
import android.webkit.*;
|
||||
import android.net.http.SslError;
|
||||
import android.os.Message;
|
||||
import org.qtproject.qt.android.WebViewControllerEx;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
import java.net.URLDecoder;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.util.concurrent.Semaphore;
|
||||
import android.app.Activity;
|
||||
import android.view.View;
|
||||
import android.widget.FrameLayout;
|
||||
|
||||
public class WebViewController
|
||||
{
|
||||
private interface RequestFinished {
|
||||
void onRequestCompleted();
|
||||
}
|
||||
|
||||
private String baseUrl = "";
|
||||
private static final String INTERNAL_BASE_URL = "file:///";
|
||||
private static final long GEOMETRY_STABLE_INTERVAL = 150; //ms wait geometry settle
|
||||
|
||||
private final Activity m_activity;
|
||||
private final long m_id;
|
||||
private WebView m_webView = null;
|
||||
private ViewGroup m_layout = null;
|
||||
private boolean m_loading = true;
|
||||
private long mLastGeometryChange = 0L;
|
||||
|
||||
private float m_displayDensity = (float) 1.0;
|
||||
|
||||
public native void urlChanged(long viewId, String url);
|
||||
public native byte[] dataForUrl(long viewId, String url, StringBuilder mimeType, StringBuilder encoding);
|
||||
public native boolean canHandleUrl(long viewId, String url);
|
||||
private final Handler m_handler;
|
||||
|
||||
private native void pageFinished(long id, String url);
|
||||
private native void pageStarted(long id, String url);
|
||||
private static final String TAG = WebViewController.class.getSimpleName();
|
||||
|
||||
private class AndroidWebChromeClient extends WebChromeClient {
|
||||
@Override
|
||||
public boolean onCreateWindow(WebView view, boolean dialog, boolean userGesture, Message resultMsg)
|
||||
{
|
||||
// Prevent opening new windows/tabs - load URLs in the same WebView instead
|
||||
// This handles links with target="_blank" or window.open()
|
||||
// Return false to prevent creating new windows - URLs will be handled by shouldOverrideUrlLoading
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public WebViewController(final Activity activity, final long id) {
|
||||
m_activity = activity;
|
||||
m_id = id;
|
||||
|
||||
ViewGroup root = (ViewGroup)(((ViewGroup)(m_activity.findViewById(android.R.id.content))).getChildAt(0));
|
||||
if (root != null) {
|
||||
m_layout = root;
|
||||
}
|
||||
|
||||
m_displayDensity = m_activity.getResources().getDisplayMetrics().density;
|
||||
|
||||
m_handler = new Handler(Looper.getMainLooper());
|
||||
m_handler.post(new Runnable() {
|
||||
@SuppressLint("SetJavaScriptEnabled")
|
||||
@Override
|
||||
public void run() {
|
||||
m_webView = new WebView(m_activity);
|
||||
m_webView.setFocusable(true);
|
||||
|
||||
m_webView.setFocusableInTouchMode(true);
|
||||
m_webView.getSettings().setJavaScriptEnabled(true);
|
||||
m_webView.getSettings().setAllowFileAccess(true);
|
||||
m_webView.getSettings().setAllowFileAccessFromFileURLs(true);
|
||||
m_webView.getSettings().setAllowUniversalAccessFromFileURLs(true);
|
||||
m_webView.getSettings().setAllowContentAccess(true);
|
||||
m_webView.getSettings().setBuiltInZoomControls(true);
|
||||
m_webView.getSettings().setDisplayZoomControls(false);
|
||||
m_webView.getSettings().setLoadWithOverviewMode(true);
|
||||
|
||||
m_webView.getSettings().setSupportMultipleWindows(false); // Prevent opening new windows
|
||||
m_webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
|
||||
|
||||
m_webView.getSettings().setUseWideViewPort(true);
|
||||
m_webView.getSettings().setLoadWithOverviewMode(true);
|
||||
m_webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
|
||||
|
||||
m_webView.getSettings().setSupportZoom(true);
|
||||
m_webView.getSettings().setBuiltInZoomControls(true);
|
||||
m_webView.getSettings().setDisplayZoomControls(false);
|
||||
|
||||
m_webView.setInitialScale(0);
|
||||
m_webView.setVisibility(android.view.View.INVISIBLE);
|
||||
|
||||
// Ensure WebView can receive and handle touch events for link clicks
|
||||
m_webView.setClickable(true);
|
||||
m_webView.setLongClickable(true);
|
||||
m_webView.setHapticFeedbackEnabled(false);
|
||||
|
||||
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
|
||||
m_webView.setElevation(0f);
|
||||
}
|
||||
|
||||
m_webView.setWebViewClient(buildWebViewClient());
|
||||
m_webView.setWebChromeClient(buildWebChromeClient());
|
||||
|
||||
// Ensure IME appears on tap when focusing editable content
|
||||
m_webView.setOnTouchListener(new android.view.View.OnTouchListener() {
|
||||
@Override
|
||||
public boolean onTouch(android.view.View v, MotionEvent event) {
|
||||
// Let WebView handle touch events normally for link clicks
|
||||
// Only request focus on ACTION_UP to allow IME to appear for input fields
|
||||
if (event.getAction() == MotionEvent.ACTION_UP) {
|
||||
v.requestFocus();
|
||||
// Do not show IME if app temporarily suppresses it
|
||||
try {
|
||||
android.view.inputmethod.InputMethodManager imm = (android.view.inputmethod.InputMethodManager) v.getContext().getSystemService(android.content.Context.INPUT_METHOD_SERVICE);
|
||||
if (imm != null) {
|
||||
imm.showSoftInput(v, 0);
|
||||
}
|
||||
} catch (Throwable ignore) {}
|
||||
}
|
||||
// Return false to let WebView handle the touch event (for link clicks, etc.)
|
||||
return false;
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private WebViewClient buildWebViewClient() {
|
||||
return new WebViewClient() {
|
||||
@Override
|
||||
public void onReceivedSslError (WebView view, SslErrorHandler handler, SslError error) {
|
||||
handler.proceed();
|
||||
Log.e(TAG, "SSL certificate error");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPageStarted (WebView view, String url, Bitmap favicon) {
|
||||
m_loading = true;
|
||||
|
||||
String dataUrl = updateUrl(url);
|
||||
urlChanged(m_id, dataUrl);
|
||||
pageStarted(m_id, dataUrl);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPageFinished(WebView view, String url) {
|
||||
m_loading = false;
|
||||
|
||||
String dataUrl = updateUrl(url);
|
||||
pageFinished(m_id, dataUrl);
|
||||
urlChanged(m_id, dataUrl);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean shouldOverrideUrlLoading(WebView view, String url) {
|
||||
Log.d(TAG, "shouldOverrideUrlLoading (deprecated): " + url);
|
||||
if (url == null || url.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
urlChanged(m_id, url);
|
||||
|
||||
// Always load URLs within WebView, don't open in external browser
|
||||
// Explicitly load the URL in the WebView and return true to indicate we handled it
|
||||
view.loadUrl(url);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean shouldOverrideUrlLoading(WebView view, android.webkit.WebResourceRequest request) {
|
||||
String url = request.getUrl().toString();
|
||||
Log.d(TAG, "shouldOverrideUrlLoading (new): " + url + ", isMainFrame: " + request.isForMainFrame() + ", method: " + request.getMethod());
|
||||
|
||||
if (url == null || url.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
urlChanged(m_id, url);
|
||||
|
||||
// Always load URLs within WebView, don't open in external browser
|
||||
// Handle main frame navigation (link clicks, form submissions, etc.)
|
||||
// For sub-resources (images, CSS, JS), let WebView handle normally by returning false
|
||||
if (request.isForMainFrame()) {
|
||||
view.loadUrl(url);
|
||||
return true;
|
||||
}
|
||||
// For sub-resources, let WebView handle normally
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
|
||||
|
||||
if (url.startsWith("data:") || !canHandleUrl(m_id, url)) {
|
||||
return super.shouldInterceptRequest(view, url);
|
||||
}
|
||||
|
||||
StringBuilder mimeType = new StringBuilder();
|
||||
StringBuilder encoding = new StringBuilder();
|
||||
byte[] data = dataForUrl(m_id, url, mimeType, encoding);
|
||||
|
||||
boolean isDataInvalid = (data == null) || (data.length == 0);
|
||||
if (isDataInvalid) {
|
||||
Log.w(TAG, String.format("Invalid data received for url: %s", url));
|
||||
return null;
|
||||
}
|
||||
if ((mimeType.length() == 0) || mimeType.toString().isEmpty()) {
|
||||
Log.w(TAG, String.format("Invalid mimeType received for url: %s", url));
|
||||
}
|
||||
if ((encoding.length() == 0) || encoding.toString().isEmpty()) {
|
||||
Log.w(TAG, String.format("Invalid encoding received for url: %s", url));
|
||||
}
|
||||
|
||||
ByteArrayInputStream dataStream = new ByteArrayInputStream(data);
|
||||
return new WebResourceResponse(mimeType.toString(), encoding.toString(), dataStream);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private WebChromeClient buildWebChromeClient() {
|
||||
return new AndroidWebChromeClient() {
|
||||
@Override
|
||||
public void onProgressChanged(WebView view, int newProgress) {
|
||||
super.onProgressChanged(view, newProgress);
|
||||
if (newProgress == 100) {
|
||||
m_loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
|
||||
callback.invoke(origin, true, false);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private String updateUrl(String url) {
|
||||
if (!url.startsWith(INTERNAL_BASE_URL)) {
|
||||
return url;
|
||||
}
|
||||
|
||||
String dataUrl = url;
|
||||
|
||||
try {
|
||||
dataUrl = URLDecoder.decode(url.substring(INTERNAL_BASE_URL.length()), "UTF-8");
|
||||
if ((dataUrl.length() == 1) && dataUrl.endsWith("#")) {
|
||||
dataUrl = baseUrl;
|
||||
} else {
|
||||
dataUrl = baseUrl + dataUrl;
|
||||
}
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
Log.e(TAG, e.toString());
|
||||
}
|
||||
|
||||
return dataUrl;
|
||||
}
|
||||
|
||||
public void release() {
|
||||
if (m_handler == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
m_handler.post(() -> {
|
||||
if (m_webView == null) {
|
||||
return;
|
||||
}
|
||||
m_webView.setVisibility(android.view.View.INVISIBLE);
|
||||
m_layout.removeView(m_webView);
|
||||
m_webView.stopLoading();
|
||||
m_webView.setWebViewClient(new WebViewClient());
|
||||
m_webView.setWebChromeClient(null);
|
||||
m_webView = null;
|
||||
});
|
||||
}
|
||||
|
||||
public void setGeometry(final int x, final int y, final int width, final int height) {
|
||||
|
||||
|
||||
Log.d(TAG, String.format(
|
||||
"setGeometry called: x=%d, y=%d, width=%d, height=%d",
|
||||
x, y, width, height));
|
||||
|
||||
|
||||
if (m_handler == null)
|
||||
return;
|
||||
|
||||
m_handler.post(() -> {
|
||||
if (m_webView == null || m_layout == null)
|
||||
return;
|
||||
|
||||
if (m_layout.indexOfChild(m_webView) < 0) {
|
||||
m_layout.addView(m_webView);
|
||||
}
|
||||
|
||||
float scale = m_activity.getResources().getDisplayMetrics().density;
|
||||
|
||||
int pxX = Math.round(x * scale);
|
||||
int pxY = Math.round(y * scale);
|
||||
int pxW = Math.round(width * scale);
|
||||
int pxH = Math.round(height * scale);
|
||||
|
||||
Log.d(TAG, String.format(
|
||||
"density=%.2f qml: x=%d y=%d w=%d h=%d -> px: x=%d y=%d w=%d h=%d",
|
||||
scale, x, y, width, height, pxX, pxY, pxW, pxH));
|
||||
|
||||
ViewGroup.LayoutParams params =
|
||||
WebViewControllerEx.createQtLayoutParams(
|
||||
pxW,
|
||||
pxH,
|
||||
pxX,
|
||||
pxY
|
||||
);
|
||||
|
||||
m_webView.setLayoutParams(params);
|
||||
m_webView.setInitialScale(0);
|
||||
|
||||
Log.d(TAG, String.format(
|
||||
"WebView positioned (QtLayout) at px: x=%d, y=%d, w=%d, h=%d",
|
||||
pxX, pxY, pxW, pxH));
|
||||
|
||||
m_layout.requestLayout();
|
||||
m_webView.requestLayout();
|
||||
|
||||
mLastGeometryChange = SystemClock.uptimeMillis();
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
public void show() {
|
||||
if (m_handler == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
m_handler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (m_webView == null) {
|
||||
return;
|
||||
}
|
||||
if (m_webView.getVisibility() != android.view.View.VISIBLE) {
|
||||
m_webView.setVisibility(android.view.View.VISIBLE);
|
||||
}
|
||||
// Don't bring WebView to front - let QML elements render on top
|
||||
// Set low elevation so QML elements can appear above WebView
|
||||
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
|
||||
m_webView.setElevation(0f);
|
||||
}
|
||||
m_webView.requestLayout();
|
||||
m_layout.requestLayout();
|
||||
m_layout.postInvalidate();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void hide() {
|
||||
hideWebView();
|
||||
long now = SystemClock.uptimeMillis();
|
||||
}
|
||||
|
||||
private void hideWebView() {
|
||||
if (m_handler == null) {
|
||||
return;
|
||||
}
|
||||
m_handler.post(() -> {
|
||||
if (m_webView == null) {
|
||||
return;
|
||||
}
|
||||
if (m_webView.getVisibility() == android.view.View.VISIBLE) {
|
||||
m_webView.setVisibility(android.view.View.INVISIBLE);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void loadUrl(String url) {
|
||||
final String newUrl;
|
||||
if ((baseUrl.length() > 0) && url.startsWith(baseUrl)) {
|
||||
newUrl = INTERNAL_BASE_URL + url.substring(baseUrl.length());
|
||||
} else {
|
||||
newUrl = url;
|
||||
}
|
||||
|
||||
if (m_handler == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
m_handler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (m_webView == null) {
|
||||
return;
|
||||
}
|
||||
m_webView.loadUrl(newUrl);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void loadDataWithBaseURL(final String url, final String html, final String mime, final String encoding) {
|
||||
baseUrl = url.trim();
|
||||
if (m_handler == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
m_handler.postDelayed(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (m_webView == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
m_webView.loadUrl("about:blank");
|
||||
m_webView.loadDataWithBaseURL(INTERNAL_BASE_URL, html, mime, encoding, null);
|
||||
}
|
||||
}, 100);
|
||||
}
|
||||
|
||||
public void evaluateJavaScript(final String script) {
|
||||
if (m_handler == null || script == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
m_handler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (m_webView == null) {
|
||||
return;
|
||||
}
|
||||
m_webView.evaluateJavascript(script, null);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public boolean canGoBack() {
|
||||
final WebView view = m_webView;
|
||||
if (view == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
final boolean[] ret = new boolean[1];
|
||||
ret[0] = false;
|
||||
boolean can = false;
|
||||
|
||||
final Semaphore semaphore = new Semaphore(0);
|
||||
if (m_activity != null) {
|
||||
m_activity.runOnUiThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
ret[0] = view.canGoBack();
|
||||
semaphore.release();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
semaphore.acquire(1);
|
||||
can = ret[0];
|
||||
} catch (InterruptedException e) {
|
||||
Log.e(TAG, e.toString());
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
return can;
|
||||
}
|
||||
|
||||
public void goBack() {
|
||||
if (m_handler == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
m_handler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (m_webView == null) {
|
||||
return;
|
||||
}
|
||||
m_webView.goBack();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public boolean canGoForward() {
|
||||
final WebView view = m_webView;
|
||||
if (view == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
final boolean[] ret = new boolean[1];
|
||||
ret[0] = false;
|
||||
boolean can = false;
|
||||
|
||||
final Semaphore semaphore = new Semaphore(0);
|
||||
if (m_activity != null) {
|
||||
m_activity.runOnUiThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
ret[0] = view.canGoForward();
|
||||
semaphore.release();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
semaphore.acquire(1);
|
||||
can = ret[0];
|
||||
} catch (InterruptedException e) {
|
||||
Log.e(TAG, e.toString());
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
return can;
|
||||
}
|
||||
|
||||
public void goForward() {
|
||||
if (m_handler == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
m_handler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (m_webView == null) {
|
||||
return;
|
||||
}
|
||||
m_webView.goForward();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void setBackgroundColor(final int color) {
|
||||
if (m_handler == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
m_handler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (m_webView == null) {
|
||||
return;
|
||||
}
|
||||
m_webView.setBackgroundColor(color);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void setTextZoom(final int percent) {
|
||||
if (m_handler == null) {
|
||||
return;
|
||||
}
|
||||
final int clamped = Math.max(25, Math.min(500, percent));
|
||||
m_handler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (m_webView == null) {
|
||||
return;
|
||||
}
|
||||
m_webView.getSettings().setTextZoom(clamped);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private int convertToDp(int input) {
|
||||
return (int)(input / m_displayDensity + 0.5f);
|
||||
}
|
||||
|
||||
public void setDefaultFontSize(int size) {
|
||||
if (m_handler == null) {
|
||||
return;
|
||||
}
|
||||
final int fontSize = size;
|
||||
m_handler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
m_webView.getSettings().setDefaultFontSize(convertToDp(fontSize));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void setStandardFontFamily(String family) {
|
||||
if (m_handler == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
final String fontFamily = family;
|
||||
m_handler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
m_webView.getSettings().setStandardFontFamily(fontFamily);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package org.qtproject.qt.android;
|
||||
|
||||
import android.view.ViewGroup;
|
||||
|
||||
public class WebViewControllerEx {
|
||||
|
||||
public static ViewGroup.LayoutParams createQtLayoutParams(int width, int height, int x, int y) {
|
||||
return new QtLayout.LayoutParams(width, height, x, y);
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,12 @@ set(HEADERS ${HEADERS}
|
||||
${CMAKE_CURRENT_BINARY_DIR}/version.h
|
||||
${CLIENT_ROOT_DIR}/core/sshclient.h
|
||||
${CLIENT_ROOT_DIR}/core/networkUtilities.h
|
||||
${CLIENT_ROOT_DIR}/core/transport/igatewaytransport.h
|
||||
${CLIENT_ROOT_DIR}/core/transport/httpGatewayTransport.h
|
||||
${CLIENT_ROOT_DIR}/core/transport/dnsGatewayTransport.h
|
||||
${CLIENT_ROOT_DIR}/core/transport/dns/dnsResolver.h
|
||||
${CLIENT_ROOT_DIR}/core/transport/dns/dnsTunnel.h
|
||||
${CLIENT_ROOT_DIR}/core/transport/dns/dnsPacket_p.h
|
||||
${CLIENT_ROOT_DIR}/core/serialization/serialization.h
|
||||
${CLIENT_ROOT_DIR}/core/serialization/transfer.h
|
||||
${CLIENT_ROOT_DIR}/../common/logger/logger.h
|
||||
@@ -68,6 +74,11 @@ set(SOURCES ${SOURCES}
|
||||
${CLIENT_ROOT_DIR}/protocols/vpnprotocol.cpp
|
||||
${CLIENT_ROOT_DIR}/core/sshclient.cpp
|
||||
${CLIENT_ROOT_DIR}/core/networkUtilities.cpp
|
||||
${CLIENT_ROOT_DIR}/core/transport/httpGatewayTransport.cpp
|
||||
${CLIENT_ROOT_DIR}/core/transport/dnsGatewayTransport.cpp
|
||||
${CLIENT_ROOT_DIR}/core/transport/dns/dnsResolver.cpp
|
||||
${CLIENT_ROOT_DIR}/core/transport/dns/dnsTunnel.cpp
|
||||
${CLIENT_ROOT_DIR}/core/transport/dns/dnsPacket.cpp
|
||||
${CLIENT_ROOT_DIR}/core/serialization/outbound.cpp
|
||||
${CLIENT_ROOT_DIR}/core/serialization/inbound.cpp
|
||||
${CLIENT_ROOT_DIR}/core/serialization/ss.cpp
|
||||
|
||||
@@ -127,7 +127,8 @@ QMap<DockerContainer, QString> ContainerProps::containerDescriptions()
|
||||
QObject::tr("WireGuard - popular VPN protocol with high performance, high speed and low power "
|
||||
"consumption.") },
|
||||
{ DockerContainer::Awg,
|
||||
QObject::tr("AmneziaWG Legacy is a outdated version of AmneziaWG protocol. To upgrade, install AmneziaWG and recreate users.") },
|
||||
QObject::tr("AmneziaWG is a special protocol from Amnezia based on WireGuard. "
|
||||
"It provides high connection speed and ensures stable operation even in the most challenging network conditions.") },
|
||||
{ DockerContainer::Awg2,
|
||||
QObject::tr("AmneziaWG is a special protocol from Amnezia based on WireGuard. "
|
||||
"It provides high connection speed and ensures stable operation even in the most challenging network conditions.") },
|
||||
|
||||
@@ -79,7 +79,7 @@ namespace apiDefs
|
||||
constexpr QLatin1String adEndpoint("ad_endpoint");
|
||||
}
|
||||
|
||||
const int requestTimeoutMsecs = 12 * 1000; // 12 secs
|
||||
const int requestTimeoutMsecs = 30 * 1000; // 30 secs (increased for DNS transport testing)
|
||||
}
|
||||
|
||||
#endif // APIDEFS_H
|
||||
|
||||
@@ -154,9 +154,6 @@ void CoreController::initControllers()
|
||||
m_apiConfigsController.reset(new ApiConfigsController(m_serversModel, m_apiServicesModel, m_settings));
|
||||
m_engine->rootContext()->setContextProperty("ApiConfigsController", m_apiConfigsController.get());
|
||||
|
||||
m_apiPremV1MigrationController.reset(new ApiPremV1MigrationController(m_serversModel, m_settings, this));
|
||||
m_engine->rootContext()->setContextProperty("ApiPremV1MigrationController", m_apiPremV1MigrationController.get());
|
||||
|
||||
m_apiNewsController.reset(new ApiNewsController(m_newsModel, m_settings, m_serversModel, this));
|
||||
m_engine->rootContext()->setContextProperty("ApiNewsController", m_apiNewsController.get());
|
||||
}
|
||||
@@ -231,8 +228,6 @@ void CoreController::initSignalHandlers()
|
||||
initAutoConnectHandler();
|
||||
initAmneziaDnsToggledHandler();
|
||||
initPrepareConfigHandler();
|
||||
initImportPremiumV2VpnKeyHandler();
|
||||
initShowMigrationDrawerHandler();
|
||||
initStrictKillSwitchHandler();
|
||||
}
|
||||
|
||||
@@ -382,25 +377,6 @@ void CoreController::initPrepareConfigHandler()
|
||||
});
|
||||
}
|
||||
|
||||
void CoreController::initImportPremiumV2VpnKeyHandler()
|
||||
{
|
||||
connect(m_apiPremV1MigrationController.get(), &ApiPremV1MigrationController::importPremiumV2VpnKey, this, [this](const QString &vpnKey) {
|
||||
m_importController->extractConfigFromData(vpnKey);
|
||||
m_importController->importConfig();
|
||||
|
||||
emit m_apiPremV1MigrationController->migrationFinished();
|
||||
});
|
||||
}
|
||||
|
||||
void CoreController::initShowMigrationDrawerHandler()
|
||||
{
|
||||
QTimer::singleShot(1000, this, [this]() {
|
||||
if (m_apiPremV1MigrationController->isPremV1MigrationReminderActive() && m_apiPremV1MigrationController->hasConfigsToMigration()) {
|
||||
m_apiPremV1MigrationController->showMigrationDrawer();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void CoreController::initStrictKillSwitchHandler()
|
||||
{
|
||||
connect(m_settingsController.get(), &SettingsController::strictKillSwitchEnabledChanged, m_vpnConnection.get(),
|
||||
|
||||
@@ -11,7 +11,6 @@
|
||||
|
||||
#include "ui/controllers/api/apiConfigsController.h"
|
||||
#include "ui/controllers/api/apiSettingsController.h"
|
||||
#include "ui/controllers/api/apiPremV1MigrationController.h"
|
||||
#include "ui/controllers/api/apiNewsController.h"
|
||||
#include "ui/controllers/appSplitTunnelingController.h"
|
||||
#include "ui/controllers/allowedDnsController.h"
|
||||
@@ -93,8 +92,6 @@ private:
|
||||
void initAutoConnectHandler();
|
||||
void initAmneziaDnsToggledHandler();
|
||||
void initPrepareConfigHandler();
|
||||
void initImportPremiumV2VpnKeyHandler();
|
||||
void initShowMigrationDrawerHandler();
|
||||
void initStrictKillSwitchHandler();
|
||||
|
||||
QQmlApplicationEngine *m_engine {}; // TODO use parent child system here?
|
||||
@@ -122,7 +119,6 @@ private:
|
||||
|
||||
QScopedPointer<ApiSettingsController> m_apiSettingsController;
|
||||
QScopedPointer<ApiConfigsController> m_apiConfigsController;
|
||||
QScopedPointer<ApiPremV1MigrationController> m_apiPremV1MigrationController;
|
||||
QScopedPointer<ApiNewsController> m_apiNewsController;
|
||||
|
||||
QSharedPointer<ContainersModel> m_containersModel;
|
||||
|
||||
@@ -1,29 +1,22 @@
|
||||
#include "gatewayController.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <functional>
|
||||
#include <random>
|
||||
|
||||
#include <QCryptographicHash>
|
||||
#include <QDebug>
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QNetworkReply>
|
||||
#include <QPromise>
|
||||
#include <QUrl>
|
||||
#include <QMutexLocker>
|
||||
#include <QSharedPointer>
|
||||
#include <QThread>
|
||||
#include <QtConcurrent>
|
||||
|
||||
#include "QBlockCipher.h"
|
||||
#include "QRsa.h"
|
||||
|
||||
#include "amnezia_application.h"
|
||||
#include "core/api/apiUtils.h"
|
||||
#include "core/networkUtilities.h"
|
||||
#include "core/transport/dnsGatewayTransport.h"
|
||||
#include "core/transport/httpGatewayTransport.h"
|
||||
#include "utilities.h"
|
||||
|
||||
#ifdef AMNEZIA_DESKTOP
|
||||
#include "core/ipcclient.h"
|
||||
#endif
|
||||
|
||||
namespace
|
||||
{
|
||||
namespace configKey
|
||||
@@ -36,630 +29,330 @@ namespace
|
||||
constexpr char keyPayload[] = "key_payload";
|
||||
}
|
||||
|
||||
constexpr QLatin1String errorResponsePattern1("No active configuration found for");
|
||||
constexpr QLatin1String errorResponsePattern2("No non-revoked public key found for");
|
||||
constexpr QLatin1String errorResponsePattern3("Account not found.");
|
||||
|
||||
constexpr QLatin1String updateRequestResponsePattern("client version update is required");
|
||||
|
||||
constexpr int httpStatusCodeNotFound = 404;
|
||||
constexpr int httpStatusCodeConflict = 409;
|
||||
|
||||
constexpr int httpStatusCodeNotImplemented = 501;
|
||||
}
|
||||
|
||||
GatewayController::GatewayController(const QString &gatewayEndpoint, const bool isDevEnvironment, const int requestTimeoutMsecs,
|
||||
const bool isStrictKillSwitchEnabled, QObject *parent)
|
||||
: QObject(parent),
|
||||
m_gatewayEndpoint(gatewayEndpoint),
|
||||
m_isDevEnvironment(isDevEnvironment),
|
||||
m_requestTimeoutMsecs(requestTimeoutMsecs),
|
||||
m_isStrictKillSwitchEnabled(isStrictKillSwitchEnabled)
|
||||
{
|
||||
}
|
||||
|
||||
GatewayController::EncryptedRequestData GatewayController::prepareRequest(const QString &endpoint, const QJsonObject &apiPayload)
|
||||
{
|
||||
EncryptedRequestData encRequestData;
|
||||
encRequestData.errorCode = ErrorCode::NoError;
|
||||
|
||||
#ifdef Q_OS_IOS
|
||||
IosController::Instance()->requestInetAccess();
|
||||
QThread::msleep(10);
|
||||
#endif
|
||||
|
||||
encRequestData.request.setTransferTimeout(m_requestTimeoutMsecs);
|
||||
encRequestData.request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
|
||||
encRequestData.request.setRawHeader(QString("X-Client-Request-ID").toUtf8(), QUuid::createUuid().toString(QUuid::WithoutBraces).toUtf8());
|
||||
encRequestData.request.setUrl(endpoint.arg(m_proxyUrl.isEmpty() ? m_gatewayEndpoint : m_proxyUrl));
|
||||
|
||||
// bypass killSwitch exceptions for API-gateway
|
||||
#ifdef AMNEZIA_DESKTOP
|
||||
if (m_isStrictKillSwitchEnabled) {
|
||||
QString host = QUrl(encRequestData.request.url()).host();
|
||||
QString ip = NetworkUtilities::getIPAddress(host);
|
||||
if (!ip.isEmpty()) {
|
||||
IpcClient::withInterface([&](QSharedPointer<IpcInterfaceReplica> iface) {
|
||||
QRemoteObjectPendingReply<bool> reply = iface->addKillSwitchAllowedRange(QStringList { ip });
|
||||
if (!reply.waitForFinished(1000) || !reply.returnValue())
|
||||
qWarning() << "GatewayController::prepareRequest(): Failed to execute remote addKillSwitchAllowedRange call";
|
||||
});
|
||||
amnezia::transport::dns::DnsProtocol dnsProtocolFromPrimary(PrimaryTransport p)
|
||||
{
|
||||
switch (p) {
|
||||
case PrimaryTransport::DnsUdp: return amnezia::transport::dns::DnsProtocol::Udp;
|
||||
case PrimaryTransport::DnsTcp: return amnezia::transport::dns::DnsProtocol::Tcp;
|
||||
case PrimaryTransport::DnsDot: return amnezia::transport::dns::DnsProtocol::Tls;
|
||||
case PrimaryTransport::DnsDoh: return amnezia::transport::dns::DnsProtocol::Https;
|
||||
case PrimaryTransport::DnsDoq: return amnezia::transport::dns::DnsProtocol::Quic;
|
||||
default: return amnezia::transport::dns::DnsProtocol::Udp;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
} // namespace
|
||||
|
||||
TransportsConfig TransportsConfig::fromJson(const QJsonObject &json)
|
||||
{
|
||||
using amnezia::transport::dns::DnsProtocol;
|
||||
|
||||
TransportsConfig config;
|
||||
|
||||
QString primaryStr = json.value("primary").toString("http").toLower();
|
||||
if (primaryStr == "http") {
|
||||
config.primary = PrimaryTransport::Http;
|
||||
} else if (primaryStr == "dns_udp" || primaryStr == "udp") {
|
||||
config.primary = PrimaryTransport::DnsUdp;
|
||||
} else if (primaryStr == "dns_tcp" || primaryStr == "tcp") {
|
||||
config.primary = PrimaryTransport::DnsTcp;
|
||||
} else if (primaryStr == "dns_dot" || primaryStr == "dot") {
|
||||
config.primary = PrimaryTransport::DnsDot;
|
||||
} else if (primaryStr == "dns_doh" || primaryStr == "doh") {
|
||||
config.primary = PrimaryTransport::DnsDoh;
|
||||
} else if (primaryStr == "dns_doq" || primaryStr == "doq") {
|
||||
config.primary = PrimaryTransport::DnsDoq;
|
||||
}
|
||||
|
||||
config.retryCount = json.value("retry_count").toInt(3);
|
||||
config.timeoutMs = json.value("timeout_ms").toInt(10000);
|
||||
|
||||
if (json.contains("http")) {
|
||||
QJsonObject httpObj = json["http"].toObject();
|
||||
config.httpEnabled = httpObj.value("enabled").toBool(true);
|
||||
config.httpEndpoint = httpObj.value("endpoint").toString();
|
||||
}
|
||||
|
||||
if (json.contains("dns_transports")) {
|
||||
QJsonArray transportsArray = json["dns_transports"].toArray();
|
||||
for (const auto &transportVal : transportsArray) {
|
||||
QJsonObject transportObj = transportVal.toObject();
|
||||
DnsTransportEntry entry;
|
||||
|
||||
entry.server = transportObj.value("server").toString();
|
||||
entry.domain = transportObj.value("domain").toString();
|
||||
entry.port = static_cast<quint16>(transportObj.value("port").toInt(15353));
|
||||
entry.dohPath = transportObj.value("path").toString("/dns-query");
|
||||
|
||||
QString typeStr = transportObj.value("type").toString().toLower();
|
||||
if (typeStr == "udp") {
|
||||
entry.type = DnsProtocol::Udp;
|
||||
} else if (typeStr == "tcp") {
|
||||
entry.type = DnsProtocol::Tcp;
|
||||
} else if (typeStr == "dot" || typeStr == "tls") {
|
||||
entry.type = DnsProtocol::Tls;
|
||||
if (!transportObj.contains("port")) entry.port = 8853;
|
||||
} else if (typeStr == "doh" || typeStr == "https") {
|
||||
entry.type = DnsProtocol::Https;
|
||||
if (!transportObj.contains("port")) entry.port = 443;
|
||||
} else if (typeStr == "doq" || typeStr == "quic") {
|
||||
entry.type = DnsProtocol::Quic;
|
||||
if (!transportObj.contains("port")) entry.port = 8853;
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (entry.isValid()) {
|
||||
config.dnsTransports.append(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return config;
|
||||
}
|
||||
|
||||
GatewayController::GatewayController(const QString &gatewayEndpoint,
|
||||
const bool isDevEnvironment,
|
||||
const int requestTimeoutMsecs,
|
||||
const bool isStrictKillSwitchEnabled,
|
||||
QObject *parent)
|
||||
: QObject(parent),
|
||||
m_requestTimeoutMsecs(requestTimeoutMsecs),
|
||||
m_gatewayEndpoint(gatewayEndpoint),
|
||||
m_isDevEnvironment(isDevEnvironment),
|
||||
m_isStrictKillSwitchEnabled(isStrictKillSwitchEnabled)
|
||||
{
|
||||
auto httpTransport = std::make_shared<amnezia::transport::HttpGatewayTransport>(
|
||||
m_gatewayEndpoint, m_isDevEnvironment, m_requestTimeoutMsecs, m_isStrictKillSwitchEnabled);
|
||||
{
|
||||
QMutexLocker lock(&m_transportMutex);
|
||||
m_transport = std::move(httpTransport);
|
||||
}
|
||||
}
|
||||
|
||||
std::shared_ptr<amnezia::transport::IGatewayTransport> GatewayController::buildTransport(
|
||||
const TransportsConfig &config, int requestTimeoutMsecs, bool isDevEnvironment, bool isStrictKillSwitchEnabled)
|
||||
{
|
||||
using namespace amnezia::transport;
|
||||
|
||||
auto makeHttp = [&](const QString &httpEndpoint) {
|
||||
return std::make_shared<HttpGatewayTransport>(
|
||||
httpEndpoint, isDevEnvironment, requestTimeoutMsecs, isStrictKillSwitchEnabled);
|
||||
};
|
||||
|
||||
if (config.primary == PrimaryTransport::Http) {
|
||||
return makeHttp(config.httpEndpoint);
|
||||
}
|
||||
|
||||
const auto wantedProtocol = dnsProtocolFromPrimary(config.primary);
|
||||
for (const auto &entry : config.dnsTransports) {
|
||||
if (entry.type == wantedProtocol && entry.isValid()) {
|
||||
return std::make_shared<DnsGatewayTransport>(
|
||||
entry.type, entry.server, entry.domain, entry.port,
|
||||
requestTimeoutMsecs, isStrictKillSwitchEnabled, entry.dohPath);
|
||||
}
|
||||
}
|
||||
|
||||
return makeHttp(config.httpEndpoint);
|
||||
}
|
||||
|
||||
void GatewayController::setTransportsConfig(const TransportsConfig &config)
|
||||
{
|
||||
if (config.timeoutMs > 0) {
|
||||
m_requestTimeoutMsecs = config.timeoutMs;
|
||||
}
|
||||
if (!config.httpEndpoint.isEmpty()) {
|
||||
m_gatewayEndpoint = config.httpEndpoint;
|
||||
}
|
||||
|
||||
TransportsConfig effective = config;
|
||||
if (effective.httpEndpoint.isEmpty()) {
|
||||
effective.httpEndpoint = m_gatewayEndpoint;
|
||||
}
|
||||
|
||||
auto newTransport = buildTransport(effective, m_requestTimeoutMsecs, m_isDevEnvironment, m_isStrictKillSwitchEnabled);
|
||||
QString activeName;
|
||||
{
|
||||
QMutexLocker lock(&m_transportMutex);
|
||||
m_transport = std::move(newTransport);
|
||||
activeName = m_transport ? m_transport->name() : QStringLiteral("none");
|
||||
}
|
||||
|
||||
qDebug() << "[Transport] Active transport set to" << activeName;
|
||||
}
|
||||
|
||||
TransportsConfig GatewayController::buildTransportsConfig()
|
||||
{
|
||||
using amnezia::transport::dns::DnsProtocol;
|
||||
|
||||
TransportsConfig config;
|
||||
|
||||
QString server = QString(AGW_DNS_SERVER).trimmed();
|
||||
QString domain = QString(AGW_DNS_DOMAIN).trimmed();
|
||||
|
||||
if (server.isEmpty() || domain.isEmpty()) {
|
||||
qDebug() << "[Transport] DNS server/domain not configured, HTTP only";
|
||||
return config;
|
||||
}
|
||||
|
||||
QString primaryStr = QString(AGW_DNS_PRIMARY).trimmed().toLower();
|
||||
if (primaryStr == "udp" || primaryStr == "dns_udp") {
|
||||
config.primary = PrimaryTransport::DnsUdp;
|
||||
} else if (primaryStr == "tcp" || primaryStr == "dns_tcp") {
|
||||
config.primary = PrimaryTransport::DnsTcp;
|
||||
} else if (primaryStr == "dot" || primaryStr == "dns_dot") {
|
||||
config.primary = PrimaryTransport::DnsDot;
|
||||
} else if (primaryStr == "doh" || primaryStr == "dns_doh") {
|
||||
config.primary = PrimaryTransport::DnsDoh;
|
||||
} else if (primaryStr == "doq" || primaryStr == "dns_doq") {
|
||||
config.primary = PrimaryTransport::DnsDoq;
|
||||
} else {
|
||||
config.primary = PrimaryTransport::Http;
|
||||
}
|
||||
|
||||
int retryCount = QString(AGW_DNS_RETRY_COUNT).trimmed().toInt();
|
||||
config.retryCount = (retryCount > 0) ? retryCount : 3;
|
||||
|
||||
int timeoutMs = QString(AGW_DNS_TIMEOUT_MS).trimmed().toInt();
|
||||
config.timeoutMs = (timeoutMs > 0) ? timeoutMs : 10000;
|
||||
|
||||
config.httpEnabled = true;
|
||||
|
||||
auto addTransport = [&](DnsProtocol type, const char *portDefine, quint16 defaultPort,
|
||||
const QString &dohPath = QString()) {
|
||||
DnsTransportEntry entry;
|
||||
entry.type = type;
|
||||
entry.server = server;
|
||||
entry.domain = domain;
|
||||
quint16 port = QString(portDefine).trimmed().toUShort();
|
||||
entry.port = (port > 0) ? port : defaultPort;
|
||||
if (!dohPath.isEmpty()) entry.dohPath = dohPath;
|
||||
config.dnsTransports.append(entry);
|
||||
};
|
||||
|
||||
addTransport(DnsProtocol::Udp, AGW_DNS_PORT_UDP, 5353);
|
||||
addTransport(DnsProtocol::Tcp, AGW_DNS_PORT_UDP, 5353);
|
||||
addTransport(DnsProtocol::Tls, AGW_DNS_PORT_DOT, 853);
|
||||
|
||||
QString dohPath = QString(AGW_DNS_DOH_PATH).trimmed();
|
||||
if (dohPath.isEmpty()) dohPath = "/dns-query";
|
||||
addTransport(DnsProtocol::Https, AGW_DNS_PORT_DOH, 443, dohPath);
|
||||
|
||||
addTransport(DnsProtocol::Quic, AGW_DNS_PORT_DOQ, 8853);
|
||||
|
||||
qDebug() << "[Transport] Built config from env: server=" << server << "domain=" << domain
|
||||
<< "transports=" << config.dnsTransports.size() << "primary=" << static_cast<int>(config.primary);
|
||||
|
||||
return config;
|
||||
}
|
||||
|
||||
GatewayController::EncryptedRequest GatewayController::encryptRequest(const QJsonObject &apiPayload)
|
||||
{
|
||||
EncryptedRequest result;
|
||||
result.errorCode = amnezia::ErrorCode::NoError;
|
||||
|
||||
QSimpleCrypto::QBlockCipher blockCipher;
|
||||
encRequestData.key = blockCipher.generatePrivateSalt(32);
|
||||
encRequestData.iv = blockCipher.generatePrivateSalt(32);
|
||||
encRequestData.salt = blockCipher.generatePrivateSalt(8);
|
||||
result.key = blockCipher.generatePrivateSalt(32);
|
||||
result.iv = blockCipher.generatePrivateSalt(16);
|
||||
result.salt = blockCipher.generatePrivateSalt(8);
|
||||
|
||||
QJsonObject keyPayload;
|
||||
keyPayload[configKey::aesKey] = QString(encRequestData.key.toBase64());
|
||||
keyPayload[configKey::aesIv] = QString(encRequestData.iv.toBase64());
|
||||
keyPayload[configKey::aesSalt] = QString(encRequestData.salt.toBase64());
|
||||
keyPayload[configKey::aesKey] = QString(result.key.toBase64());
|
||||
keyPayload[configKey::aesIv] = QString(result.iv.toBase64());
|
||||
keyPayload[configKey::aesSalt] = QString(result.salt.toBase64());
|
||||
|
||||
QByteArray encryptedKeyPayload;
|
||||
QByteArray encryptedApiPayload;
|
||||
try {
|
||||
QSimpleCrypto::QRsa rsa;
|
||||
|
||||
EVP_PKEY *publicKey = nullptr;
|
||||
try {
|
||||
QByteArray rsaKey = m_isDevEnvironment ? DEV_AGW_PUBLIC_KEY : PROD_AGW_PUBLIC_KEY;
|
||||
QSimpleCrypto::QRsa rsa;
|
||||
rsaKey = rsaKey.trimmed();
|
||||
rsaKey.replace("\\n", "\n");
|
||||
publicKey = rsa.getPublicKeyFromByteArray(rsaKey);
|
||||
} catch (...) {
|
||||
Utils::logException();
|
||||
qCritical() << "error loading public key from environment variables";
|
||||
encRequestData.errorCode = ErrorCode::ApiMissingAgwPublicKey;
|
||||
return encRequestData;
|
||||
result.errorCode = amnezia::ErrorCode::ApiMissingAgwPublicKey;
|
||||
return result;
|
||||
}
|
||||
|
||||
encryptedKeyPayload = rsa.encrypt(QJsonDocument(keyPayload).toJson(), publicKey, RSA_PKCS1_PADDING);
|
||||
encryptedKeyPayload = rsa.encrypt(QJsonDocument(keyPayload).toJson(QJsonDocument::Compact),
|
||||
publicKey, RSA_PKCS1_PADDING);
|
||||
EVP_PKEY_free(publicKey);
|
||||
|
||||
encryptedApiPayload = blockCipher.encryptAesBlockCipher(QJsonDocument(apiPayload).toJson(), encRequestData.key, encRequestData.iv,
|
||||
"", encRequestData.salt);
|
||||
encryptedApiPayload = blockCipher.encryptAesBlockCipher(QJsonDocument(apiPayload).toJson(QJsonDocument::Compact),
|
||||
result.key, result.iv, "", result.salt);
|
||||
} catch (...) {
|
||||
Utils::logException();
|
||||
qCritical() << "error when encrypting the request body";
|
||||
encRequestData.errorCode = ErrorCode::ApiConfigDecryptionError;
|
||||
return encRequestData;
|
||||
result.errorCode = amnezia::ErrorCode::ApiConfigDecryptionError;
|
||||
return result;
|
||||
}
|
||||
|
||||
QJsonObject requestBody;
|
||||
requestBody[configKey::keyPayload] = QString(encryptedKeyPayload.toBase64());
|
||||
requestBody[configKey::apiPayload] = QString(encryptedApiPayload.toBase64());
|
||||
|
||||
encRequestData.requestBody = QJsonDocument(requestBody).toJson();
|
||||
return encRequestData;
|
||||
result.body = QJsonDocument(requestBody).toJson(QJsonDocument::Compact);
|
||||
return result;
|
||||
}
|
||||
|
||||
GatewayController::DecryptionResult GatewayController::tryDecryptResponseBody(const QByteArray &encryptedResponseBody,
|
||||
QNetworkReply::NetworkError replyError, const QByteArray &key,
|
||||
const QByteArray &iv, const QByteArray &salt)
|
||||
amnezia::transport::DecryptionResult GatewayController::decryptResponse(const QByteArray &encryptedResponseBody,
|
||||
const QByteArray &key,
|
||||
const QByteArray &iv,
|
||||
const QByteArray &salt) const
|
||||
{
|
||||
DecryptionResult result;
|
||||
result.decryptedBody = encryptedResponseBody;
|
||||
result.isDecryptionSuccessful = false;
|
||||
amnezia::transport::DecryptionResult result;
|
||||
result.decrypted = encryptedResponseBody;
|
||||
result.isOk = false;
|
||||
|
||||
if (encryptedResponseBody.isEmpty()) {
|
||||
return result;
|
||||
}
|
||||
|
||||
try {
|
||||
QSimpleCrypto::QBlockCipher blockCipher;
|
||||
result.decryptedBody = blockCipher.decryptAesBlockCipher(encryptedResponseBody, key, iv, "", salt);
|
||||
result.isDecryptionSuccessful = true;
|
||||
result.decrypted = blockCipher.decryptAesBlockCipher(encryptedResponseBody, key, iv, "", salt);
|
||||
result.isOk = true;
|
||||
} catch (...) {
|
||||
result.decryptedBody = encryptedResponseBody;
|
||||
result.isDecryptionSuccessful = false;
|
||||
result.decrypted = encryptedResponseBody;
|
||||
result.isOk = false;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
ErrorCode GatewayController::post(const QString &endpoint, const QJsonObject apiPayload, QByteArray &responseBody)
|
||||
std::shared_ptr<amnezia::transport::IGatewayTransport> GatewayController::currentTransport() const
|
||||
{
|
||||
EncryptedRequestData encRequestData = prepareRequest(endpoint, apiPayload);
|
||||
if (encRequestData.errorCode != ErrorCode::NoError) {
|
||||
return encRequestData.errorCode;
|
||||
}
|
||||
|
||||
QNetworkReply *reply = amnApp->networkManager()->post(encRequestData.request, encRequestData.requestBody);
|
||||
|
||||
QEventLoop wait;
|
||||
connect(reply, &QNetworkReply::finished, &wait, &QEventLoop::quit);
|
||||
|
||||
QList<QSslError> sslErrors;
|
||||
connect(reply, &QNetworkReply::sslErrors, [this, &sslErrors](const QList<QSslError> &errors) { sslErrors = errors; });
|
||||
wait.exec(QEventLoop::ExcludeUserInputEvents);
|
||||
|
||||
QByteArray encryptedResponseBody = reply->readAll();
|
||||
QString replyErrorString = reply->errorString();
|
||||
auto replyError = reply->error();
|
||||
int httpStatusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
|
||||
|
||||
reply->deleteLater();
|
||||
|
||||
auto decryptionResult =
|
||||
tryDecryptResponseBody(encryptedResponseBody, replyError, encRequestData.key, encRequestData.iv, encRequestData.salt);
|
||||
|
||||
if (sslErrors.isEmpty() && shouldBypassProxy(replyError, decryptionResult.decryptedBody, decryptionResult.isDecryptionSuccessful)) {
|
||||
auto requestFunction = [&encRequestData, &encryptedResponseBody](const QString &url) {
|
||||
encRequestData.request.setUrl(url);
|
||||
return amnApp->networkManager()->post(encRequestData.request, encRequestData.requestBody);
|
||||
};
|
||||
|
||||
auto replyProcessingFunction = [&encryptedResponseBody, &replyErrorString, &replyError, &httpStatusCode, &sslErrors, &encRequestData,
|
||||
&decryptionResult, this](QNetworkReply *reply, const QList<QSslError> &nestedSslErrors) {
|
||||
encryptedResponseBody = reply->readAll();
|
||||
replyErrorString = reply->errorString();
|
||||
replyError = reply->error();
|
||||
httpStatusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
|
||||
|
||||
decryptionResult =
|
||||
tryDecryptResponseBody(encryptedResponseBody, replyError, encRequestData.key, encRequestData.iv, encRequestData.salt);
|
||||
|
||||
if (!sslErrors.isEmpty()
|
||||
|| shouldBypassProxy(replyError, decryptionResult.decryptedBody, decryptionResult.isDecryptionSuccessful)) {
|
||||
sslErrors = nestedSslErrors;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
auto serviceType = apiPayload.value(apiDefs::key::serviceType).toString("");
|
||||
auto userCountryCode = apiPayload.value(apiDefs::key::userCountryCode).toString("");
|
||||
bypassProxy(endpoint, serviceType, userCountryCode, requestFunction, replyProcessingFunction);
|
||||
}
|
||||
|
||||
auto errorCode =
|
||||
apiUtils::checkNetworkReplyErrors(sslErrors, replyErrorString, replyError, httpStatusCode, decryptionResult.decryptedBody);
|
||||
if (errorCode) {
|
||||
return errorCode;
|
||||
}
|
||||
|
||||
if (!decryptionResult.isDecryptionSuccessful) {
|
||||
qCritical() << "error when decrypting the request body";
|
||||
return ErrorCode::ApiConfigDecryptionError;
|
||||
}
|
||||
|
||||
responseBody = decryptionResult.decryptedBody;
|
||||
return ErrorCode::NoError;
|
||||
QMutexLocker lock(&m_transportMutex);
|
||||
return m_transport;
|
||||
}
|
||||
|
||||
QFuture<QPair<ErrorCode, QByteArray>> GatewayController::postAsync(const QString &endpoint, const QJsonObject apiPayload)
|
||||
amnezia::ErrorCode GatewayController::post(const QString &endpoint, const QJsonObject apiPayload, QByteArray &responseBody)
|
||||
{
|
||||
auto promise = QSharedPointer<QPromise<QPair<ErrorCode, QByteArray>>>::create();
|
||||
promise->start();
|
||||
|
||||
EncryptedRequestData encRequestData = prepareRequest(endpoint, apiPayload);
|
||||
if (encRequestData.errorCode != ErrorCode::NoError) {
|
||||
promise->addResult(qMakePair(encRequestData.errorCode, QByteArray()));
|
||||
promise->finish();
|
||||
return promise->future();
|
||||
EncryptedRequest enc = encryptRequest(apiPayload);
|
||||
if (enc.errorCode != amnezia::ErrorCode::NoError) {
|
||||
return enc.errorCode;
|
||||
}
|
||||
|
||||
QNetworkReply *reply = amnApp->networkManager()->post(encRequestData.request, encRequestData.requestBody);
|
||||
|
||||
auto sslErrors = QSharedPointer<QList<QSslError>>::create();
|
||||
|
||||
connect(reply, &QNetworkReply::sslErrors, [sslErrors](const QList<QSslError> &errors) { *sslErrors = errors; });
|
||||
|
||||
connect(reply, &QNetworkReply::finished, reply, [promise, sslErrors, encRequestData, endpoint, apiPayload, reply, this]() mutable {
|
||||
QByteArray encryptedResponseBody = reply->readAll();
|
||||
QString replyErrorString = reply->errorString();
|
||||
auto replyError = reply->error();
|
||||
int httpStatusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
|
||||
|
||||
reply->deleteLater();
|
||||
|
||||
auto decryptionResult =
|
||||
tryDecryptResponseBody(encryptedResponseBody, replyError, encRequestData.key, encRequestData.iv, encRequestData.salt);
|
||||
|
||||
auto processResponse = [promise, encRequestData](const GatewayController::DecryptionResult &decryptionResult,
|
||||
const QList<QSslError> &sslErrors, QNetworkReply::NetworkError replyError,
|
||||
const QString &replyErrorString, int httpStatusCode) {
|
||||
auto errorCode = apiUtils::checkNetworkReplyErrors(sslErrors, replyErrorString, replyError, httpStatusCode,
|
||||
decryptionResult.decryptedBody);
|
||||
if (errorCode) {
|
||||
promise->addResult(qMakePair(errorCode, QByteArray()));
|
||||
promise->finish();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!decryptionResult.isDecryptionSuccessful) {
|
||||
Utils::logException();
|
||||
qCritical() << "error when decrypting the request body";
|
||||
promise->addResult(qMakePair(ErrorCode::ApiConfigDecryptionError, QByteArray()));
|
||||
promise->finish();
|
||||
return;
|
||||
}
|
||||
|
||||
promise->addResult(qMakePair(ErrorCode::NoError, decryptionResult.decryptedBody));
|
||||
promise->finish();
|
||||
};
|
||||
|
||||
if (sslErrors->isEmpty() && shouldBypassProxy(replyError, decryptionResult.decryptedBody, decryptionResult.isDecryptionSuccessful)) {
|
||||
auto serviceType = apiPayload.value(apiDefs::key::serviceType).toString("");
|
||||
auto userCountryCode = apiPayload.value(apiDefs::key::userCountryCode).toString("");
|
||||
|
||||
QStringList baseUrls;
|
||||
if (m_isDevEnvironment) {
|
||||
baseUrls = QString(DEV_S3_ENDPOINT).split(", ");
|
||||
} else {
|
||||
baseUrls = QString(PROD_S3_ENDPOINT).split(", ");
|
||||
}
|
||||
|
||||
QStringList proxyStorageUrls;
|
||||
if (!serviceType.isEmpty()) {
|
||||
for (const auto &baseUrl : baseUrls) {
|
||||
QByteArray path = ("endpoints-" + serviceType + "-" + userCountryCode).toUtf8();
|
||||
proxyStorageUrls.push_back(baseUrl + path.toBase64(QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals)
|
||||
+ ".json");
|
||||
}
|
||||
}
|
||||
for (const auto &baseUrl : baseUrls)
|
||||
proxyStorageUrls.push_back(baseUrl + "endpoints.json");
|
||||
|
||||
getProxyUrlsAsync(proxyStorageUrls, 0, [this, encRequestData, endpoint, processResponse](const QStringList &proxyUrls) {
|
||||
getProxyUrlAsync(proxyUrls, 0, [this, encRequestData, endpoint, processResponse](const QString &proxyUrl) {
|
||||
bypassProxyAsync(endpoint, proxyUrl, encRequestData,
|
||||
[processResponse, this](const QByteArray &decryptedBody, bool isDecryptionSuccessful,
|
||||
const QList<QSslError> &sslErrors, QNetworkReply::NetworkError replyError,
|
||||
const QString &replyErrorString, int httpStatusCode) {
|
||||
GatewayController::DecryptionResult result;
|
||||
result.decryptedBody = decryptedBody;
|
||||
result.isDecryptionSuccessful = isDecryptionSuccessful;
|
||||
processResponse(result, sslErrors, replyError, replyErrorString, httpStatusCode);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
} else {
|
||||
processResponse(decryptionResult, *sslErrors, replyError, replyErrorString, httpStatusCode);
|
||||
}
|
||||
});
|
||||
|
||||
return promise->future();
|
||||
}
|
||||
|
||||
QStringList GatewayController::getProxyUrls(const QString &serviceType, const QString &userCountryCode)
|
||||
{
|
||||
QNetworkRequest request;
|
||||
request.setTransferTimeout(m_requestTimeoutMsecs);
|
||||
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
|
||||
|
||||
QEventLoop wait;
|
||||
QList<QSslError> sslErrors;
|
||||
QNetworkReply *reply;
|
||||
|
||||
QStringList baseUrls;
|
||||
if (m_isDevEnvironment) {
|
||||
baseUrls = QString(DEV_S3_ENDPOINT).split(", ");
|
||||
} else {
|
||||
baseUrls = QString(PROD_S3_ENDPOINT).split(", ");
|
||||
auto transport = currentTransport();
|
||||
if (!transport) {
|
||||
return amnezia::ErrorCode::AmneziaServiceConnectionFailed;
|
||||
}
|
||||
|
||||
QByteArray key = m_isDevEnvironment ? DEV_AGW_PUBLIC_KEY : PROD_AGW_PUBLIC_KEY;
|
||||
|
||||
QStringList proxyStorageUrls;
|
||||
if (!serviceType.isEmpty()) {
|
||||
for (const auto &baseUrl : baseUrls) {
|
||||
QByteArray path = ("endpoints-" + serviceType + "-" + userCountryCode).toUtf8();
|
||||
proxyStorageUrls.push_back(baseUrl + path.toBase64(QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals) + ".json");
|
||||
}
|
||||
}
|
||||
for (const auto &baseUrl : baseUrls) {
|
||||
proxyStorageUrls.push_back(baseUrl + "endpoints.json");
|
||||
}
|
||||
|
||||
for (const auto &proxyStorageUrl : proxyStorageUrls) {
|
||||
request.setUrl(proxyStorageUrl);
|
||||
reply = amnApp->networkManager()->get(request);
|
||||
|
||||
connect(reply, &QNetworkReply::finished, &wait, &QEventLoop::quit);
|
||||
connect(reply, &QNetworkReply::sslErrors, [this, &sslErrors](const QList<QSslError> &errors) { sslErrors = errors; });
|
||||
wait.exec(QEventLoop::ExcludeUserInputEvents);
|
||||
|
||||
if (reply->error() == QNetworkReply::NetworkError::NoError) {
|
||||
auto encryptedResponseBody = reply->readAll();
|
||||
reply->deleteLater();
|
||||
|
||||
EVP_PKEY *privateKey = nullptr;
|
||||
QByteArray responseBody;
|
||||
try {
|
||||
if (!m_isDevEnvironment) {
|
||||
QCryptographicHash hash(QCryptographicHash::Sha512);
|
||||
hash.addData(key);
|
||||
QByteArray hashResult = hash.result().toHex();
|
||||
|
||||
QByteArray key = QByteArray::fromHex(hashResult.left(64));
|
||||
QByteArray iv = QByteArray::fromHex(hashResult.mid(64, 32));
|
||||
|
||||
QByteArray ba = QByteArray::fromBase64(encryptedResponseBody);
|
||||
|
||||
QSimpleCrypto::QBlockCipher blockCipher;
|
||||
responseBody = blockCipher.decryptAesBlockCipher(ba, key, iv);
|
||||
} else {
|
||||
responseBody = encryptedResponseBody;
|
||||
}
|
||||
} catch (...) {
|
||||
Utils::logException();
|
||||
qCritical() << "error loading private key from environment variables or decrypting payload" << encryptedResponseBody;
|
||||
continue;
|
||||
}
|
||||
|
||||
auto endpointsArray = QJsonDocument::fromJson(responseBody).array();
|
||||
|
||||
QStringList endpoints;
|
||||
for (const auto &endpoint : endpointsArray) {
|
||||
endpoints.push_back(endpoint.toString());
|
||||
}
|
||||
return endpoints;
|
||||
} else {
|
||||
auto replyError = reply->error();
|
||||
int httpStatusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
|
||||
qDebug() << replyError;
|
||||
qDebug() << httpStatusCode;
|
||||
qDebug() << "go to the next storage endpoint";
|
||||
|
||||
reply->deleteLater();
|
||||
}
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
bool GatewayController::shouldBypassProxy(const QNetworkReply::NetworkError &replyError, const QByteArray &decryptedResponseBody,
|
||||
bool isDecryptionSuccessful)
|
||||
{
|
||||
const QByteArray &responseBody = decryptedResponseBody;
|
||||
|
||||
int httpStatus = -1;
|
||||
if (isDecryptionSuccessful) {
|
||||
QJsonDocument jsonDoc = QJsonDocument::fromJson(responseBody);
|
||||
if (jsonDoc.isObject()) {
|
||||
QJsonObject jsonObj = jsonDoc.object();
|
||||
httpStatus = jsonObj.value("http_status").toInt(-1);
|
||||
}
|
||||
} else {
|
||||
qDebug() << "failed to decrypt the data";
|
||||
return true;
|
||||
}
|
||||
|
||||
if (replyError == QNetworkReply::NetworkError::OperationCanceledError || replyError == QNetworkReply::NetworkError::TimeoutError) {
|
||||
qDebug() << "timeout occurred";
|
||||
qDebug() << replyError;
|
||||
return true;
|
||||
} else if (responseBody.contains("html")) {
|
||||
qDebug() << "the response contains an html tag";
|
||||
return true;
|
||||
} else if (httpStatus == httpStatusCodeNotFound) {
|
||||
if (responseBody.contains(errorResponsePattern1) || responseBody.contains(errorResponsePattern2)
|
||||
|| responseBody.contains(errorResponsePattern3)) {
|
||||
return false;
|
||||
} else {
|
||||
qDebug() << replyError;
|
||||
return true;
|
||||
}
|
||||
} else if (httpStatus == httpStatusCodeNotImplemented) {
|
||||
if (responseBody.contains(updateRequestResponsePattern)) {
|
||||
return false;
|
||||
} else {
|
||||
qDebug() << replyError;
|
||||
return true;
|
||||
}
|
||||
} else if (httpStatus == httpStatusCodeConflict) {
|
||||
return false;
|
||||
} else if (replyError != QNetworkReply::NetworkError::NoError) {
|
||||
qDebug() << replyError;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void GatewayController::bypassProxy(const QString &endpoint, const QString &serviceType, const QString &userCountryCode,
|
||||
std::function<QNetworkReply *(const QString &url)> requestFunction,
|
||||
std::function<bool(QNetworkReply *reply, const QList<QSslError> &sslErrors)> replyProcessingFunction)
|
||||
{
|
||||
QStringList proxyUrls = getProxyUrls(serviceType, userCountryCode);
|
||||
std::random_device randomDevice;
|
||||
std::mt19937 generator(randomDevice());
|
||||
std::shuffle(proxyUrls.begin(), proxyUrls.end(), generator);
|
||||
|
||||
QByteArray responseBody;
|
||||
|
||||
auto bypassFunction = [this](const QString &endpoint, const QString &proxyUrl,
|
||||
std::function<QNetworkReply *(const QString &url)> requestFunction,
|
||||
std::function<bool(QNetworkReply * reply, const QList<QSslError> &sslErrors)> replyProcessingFunction) {
|
||||
QEventLoop wait;
|
||||
QList<QSslError> sslErrors;
|
||||
|
||||
qDebug() << "go to the next proxy endpoint";
|
||||
QNetworkReply *reply = requestFunction(endpoint.arg(proxyUrl));
|
||||
|
||||
QObject::connect(reply, &QNetworkReply::finished, &wait, &QEventLoop::quit);
|
||||
connect(reply, &QNetworkReply::sslErrors, [this, &sslErrors](const QList<QSslError> &errors) { sslErrors = errors; });
|
||||
wait.exec(QEventLoop::ExcludeUserInputEvents);
|
||||
|
||||
auto result = replyProcessingFunction(reply, sslErrors);
|
||||
reply->deleteLater();
|
||||
return result;
|
||||
auto decryptionHook = [this, key = enc.key, iv = enc.iv, salt = enc.salt](const QByteArray &encrypted) {
|
||||
return decryptResponse(encrypted, key, iv, salt);
|
||||
};
|
||||
|
||||
if (m_proxyUrl.isEmpty()) {
|
||||
QNetworkRequest request;
|
||||
request.setTransferTimeout(1000);
|
||||
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
|
||||
|
||||
QEventLoop wait;
|
||||
QList<QSslError> sslErrors;
|
||||
QNetworkReply *reply;
|
||||
|
||||
for (const QString &proxyUrl : proxyUrls) {
|
||||
request.setUrl(proxyUrl + "lmbd-health");
|
||||
reply = amnApp->networkManager()->get(request);
|
||||
|
||||
connect(reply, &QNetworkReply::finished, &wait, &QEventLoop::quit);
|
||||
connect(reply, &QNetworkReply::sslErrors, [this, &sslErrors](const QList<QSslError> &errors) { sslErrors = errors; });
|
||||
wait.exec(QEventLoop::ExcludeUserInputEvents);
|
||||
|
||||
if (reply->error() == QNetworkReply::NetworkError::NoError) {
|
||||
reply->deleteLater();
|
||||
|
||||
m_proxyUrl = proxyUrl;
|
||||
if (!m_proxyUrl.isEmpty()) {
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
reply->deleteLater();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!m_proxyUrl.isEmpty()) {
|
||||
if (bypassFunction(endpoint, m_proxyUrl, requestFunction, replyProcessingFunction)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
for (const QString &proxyUrl : proxyUrls) {
|
||||
if (bypassFunction(endpoint, proxyUrl, requestFunction, replyProcessingFunction)) {
|
||||
m_proxyUrl = proxyUrl;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return transport->send(endpoint, enc.body, responseBody, decryptionHook);
|
||||
}
|
||||
|
||||
void GatewayController::getProxyUrlsAsync(const QStringList proxyStorageUrls, const int currentProxyStorageIndex,
|
||||
std::function<void(const QStringList &)> onComplete)
|
||||
QFuture<QPair<amnezia::ErrorCode, QByteArray>> GatewayController::postAsync(const QString &endpoint, const QJsonObject apiPayload)
|
||||
{
|
||||
if (currentProxyStorageIndex >= proxyStorageUrls.size()) {
|
||||
onComplete({});
|
||||
return;
|
||||
}
|
||||
|
||||
QNetworkRequest request;
|
||||
request.setTransferTimeout(m_requestTimeoutMsecs);
|
||||
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
|
||||
request.setUrl(proxyStorageUrls[currentProxyStorageIndex]);
|
||||
|
||||
QNetworkReply *reply = amnApp->networkManager()->get(request);
|
||||
|
||||
// connect(reply, &QNetworkReply::sslErrors, this, [state](const QList<QSslError> &e) { *(state->sslErrors) = e; });
|
||||
|
||||
connect(reply, &QNetworkReply::finished, this, [this, proxyStorageUrls, currentProxyStorageIndex, onComplete, reply]() {
|
||||
if (reply->error() == QNetworkReply::NoError) {
|
||||
QByteArray encrypted = reply->readAll();
|
||||
reply->deleteLater();
|
||||
|
||||
QByteArray responseBody;
|
||||
try {
|
||||
QByteArray key = m_isDevEnvironment ? DEV_AGW_PUBLIC_KEY : PROD_AGW_PUBLIC_KEY;
|
||||
if (!m_isDevEnvironment) {
|
||||
QCryptographicHash hash(QCryptographicHash::Sha512);
|
||||
hash.addData(key);
|
||||
QByteArray h = hash.result().toHex();
|
||||
|
||||
QByteArray decKey = QByteArray::fromHex(h.left(64));
|
||||
QByteArray iv = QByteArray::fromHex(h.mid(64, 32));
|
||||
QByteArray ba = QByteArray::fromBase64(encrypted);
|
||||
|
||||
QSimpleCrypto::QBlockCipher cipher;
|
||||
responseBody = cipher.decryptAesBlockCipher(ba, decKey, iv);
|
||||
} else {
|
||||
responseBody = encrypted;
|
||||
}
|
||||
} catch (...) {
|
||||
Utils::logException();
|
||||
qCritical() << "error decrypting payload";
|
||||
QMetaObject::invokeMethod(
|
||||
this, [=]() { getProxyUrlsAsync(proxyStorageUrls, currentProxyStorageIndex + 1, onComplete); }, Qt::QueuedConnection);
|
||||
return;
|
||||
}
|
||||
|
||||
QJsonArray endpointsArray = QJsonDocument::fromJson(responseBody).array();
|
||||
QStringList endpoints;
|
||||
for (const QJsonValue &endpoint : endpointsArray)
|
||||
endpoints.push_back(endpoint.toString());
|
||||
|
||||
QStringList shuffled = endpoints;
|
||||
std::random_device randomDevice;
|
||||
std::mt19937 generator(randomDevice());
|
||||
std::shuffle(shuffled.begin(), shuffled.end(), generator);
|
||||
|
||||
onComplete(shuffled);
|
||||
return;
|
||||
}
|
||||
|
||||
int httpStatusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
|
||||
qDebug() << httpStatusCode;
|
||||
qDebug() << "go to the next storage endpoint";
|
||||
reply->deleteLater();
|
||||
QMetaObject::invokeMethod(
|
||||
this, [=]() { getProxyUrlsAsync(proxyStorageUrls, currentProxyStorageIndex + 1, onComplete); }, Qt::QueuedConnection);
|
||||
});
|
||||
}
|
||||
|
||||
void GatewayController::getProxyUrlAsync(const QStringList proxyUrls, const int currentProxyIndex,
|
||||
std::function<void(const QString &)> onComplete)
|
||||
{
|
||||
if (currentProxyIndex >= proxyUrls.size()) {
|
||||
onComplete("");
|
||||
return;
|
||||
}
|
||||
|
||||
QNetworkRequest request;
|
||||
request.setTransferTimeout(1000);
|
||||
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
|
||||
request.setUrl(proxyUrls[currentProxyIndex] + "lmbd-health");
|
||||
|
||||
QNetworkReply *reply = amnApp->networkManager()->get(request);
|
||||
|
||||
// connect(reply, &QNetworkReply::sslErrors, this, [state](const QList<QSslError> &e) {
|
||||
// *(state->sslErrors) = e;
|
||||
// });
|
||||
|
||||
connect(reply, &QNetworkReply::finished, this, [this, proxyUrls, currentProxyIndex, onComplete, reply]() {
|
||||
reply->deleteLater();
|
||||
|
||||
if (reply->error() == QNetworkReply::NoError) {
|
||||
m_proxyUrl = proxyUrls[currentProxyIndex];
|
||||
onComplete(m_proxyUrl);
|
||||
return;
|
||||
}
|
||||
|
||||
qDebug() << "go to the next proxy endpoint";
|
||||
QMetaObject::invokeMethod(this, [=]() { getProxyUrlAsync(proxyUrls, currentProxyIndex + 1, onComplete); }, Qt::QueuedConnection);
|
||||
});
|
||||
}
|
||||
|
||||
void GatewayController::bypassProxyAsync(
|
||||
const QString &endpoint, const QString &proxyUrl, EncryptedRequestData encRequestData,
|
||||
std::function<void(const QByteArray &, bool, const QList<QSslError> &, QNetworkReply::NetworkError, const QString &, int)> onComplete)
|
||||
{
|
||||
auto sslErrors = QSharedPointer<QList<QSslError>>::create();
|
||||
if (proxyUrl.isEmpty()) {
|
||||
onComplete(QByteArray(), false, *sslErrors, QNetworkReply::InternalServerError, "empty proxy url", 0);
|
||||
return;
|
||||
}
|
||||
|
||||
QNetworkRequest request = encRequestData.request;
|
||||
request.setUrl(endpoint.arg(proxyUrl));
|
||||
|
||||
QNetworkReply *reply = amnApp->networkManager()->post(request, encRequestData.requestBody);
|
||||
|
||||
connect(reply, &QNetworkReply::sslErrors, this, [sslErrors](const QList<QSslError> &errors) { *sslErrors = errors; });
|
||||
|
||||
connect(reply, &QNetworkReply::finished, this, [sslErrors, onComplete, encRequestData, reply, this]() {
|
||||
QByteArray encryptedResponseBody = reply->readAll();
|
||||
QString replyErrorString = reply->errorString();
|
||||
auto replyError = reply->error();
|
||||
int httpStatusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
|
||||
|
||||
reply->deleteLater();
|
||||
|
||||
auto decryptionResult =
|
||||
tryDecryptResponseBody(encryptedResponseBody, replyError, encRequestData.key, encRequestData.iv, encRequestData.salt);
|
||||
|
||||
onComplete(decryptionResult.decryptedBody, decryptionResult.isDecryptionSuccessful, *sslErrors, replyError, replyErrorString,
|
||||
httpStatusCode);
|
||||
return QtConcurrent::run([this, endpoint, apiPayload]() {
|
||||
QByteArray responseBody;
|
||||
amnezia::ErrorCode errorCode = post(endpoint, apiPayload, responseBody);
|
||||
return qMakePair(errorCode, responseBody);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -2,69 +2,87 @@
|
||||
#define GATEWAYCONTROLLER_H
|
||||
|
||||
#include <QFuture>
|
||||
#include <QNetworkReply>
|
||||
#include <QJsonArray>
|
||||
#include <QJsonObject>
|
||||
#include <QMutex>
|
||||
#include <QObject>
|
||||
#include <QPair>
|
||||
#include <QPromise>
|
||||
#include <QSharedPointer>
|
||||
#include <memory>
|
||||
|
||||
#include "core/defs.h"
|
||||
#include "core/transport/dns/dnsResolver.h"
|
||||
#include "core/transport/igatewaytransport.h"
|
||||
|
||||
#ifdef Q_OS_IOS
|
||||
#include "platforms/ios/ios_controller.h"
|
||||
#endif
|
||||
struct DnsTransportEntry
|
||||
{
|
||||
amnezia::transport::dns::DnsProtocol type = amnezia::transport::dns::DnsProtocol::Udp;
|
||||
QString server;
|
||||
QString domain;
|
||||
quint16 port = 15353;
|
||||
QString dohPath = "/dns-query";
|
||||
|
||||
bool isValid() const { return !server.isEmpty() && !domain.isEmpty(); }
|
||||
};
|
||||
|
||||
enum class PrimaryTransport { Http, DnsUdp, DnsTcp, DnsDot, DnsDoh, DnsDoq };
|
||||
|
||||
struct TransportsConfig
|
||||
{
|
||||
PrimaryTransport primary = PrimaryTransport::Http;
|
||||
bool httpEnabled = true;
|
||||
QString httpEndpoint;
|
||||
QList<DnsTransportEntry> dnsTransports;
|
||||
int retryCount = 3;
|
||||
int timeoutMs = 10000;
|
||||
|
||||
bool isValid() const { return httpEnabled || !dnsTransports.isEmpty(); }
|
||||
static TransportsConfig fromJson(const QJsonObject &json);
|
||||
};
|
||||
|
||||
class GatewayController : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
explicit GatewayController(const QString &gatewayEndpoint, const bool isDevEnvironment, const int requestTimeoutMsecs,
|
||||
const bool isStrictKillSwitchEnabled, QObject *parent = nullptr);
|
||||
explicit GatewayController(const QString &gatewayEndpoint,
|
||||
const bool isDevEnvironment,
|
||||
const int requestTimeoutMsecs,
|
||||
const bool isStrictKillSwitchEnabled,
|
||||
QObject *parent = nullptr);
|
||||
|
||||
amnezia::ErrorCode post(const QString &endpoint, const QJsonObject apiPayload, QByteArray &responseBody);
|
||||
QFuture<QPair<amnezia::ErrorCode, QByteArray>> postAsync(const QString &endpoint, const QJsonObject apiPayload);
|
||||
|
||||
static TransportsConfig buildTransportsConfig();
|
||||
void setTransportsConfig(const TransportsConfig &config);
|
||||
|
||||
private:
|
||||
struct EncryptedRequestData
|
||||
struct EncryptedRequest
|
||||
{
|
||||
QNetworkRequest request;
|
||||
QByteArray requestBody;
|
||||
QByteArray body;
|
||||
QByteArray key;
|
||||
QByteArray iv;
|
||||
QByteArray salt;
|
||||
amnezia::ErrorCode errorCode;
|
||||
amnezia::ErrorCode errorCode = amnezia::ErrorCode::NoError;
|
||||
};
|
||||
|
||||
struct DecryptionResult
|
||||
{
|
||||
QByteArray decryptedBody;
|
||||
bool isDecryptionSuccessful;
|
||||
};
|
||||
EncryptedRequest encryptRequest(const QJsonObject &apiPayload);
|
||||
amnezia::transport::DecryptionResult decryptResponse(const QByteArray &encryptedResponseBody,
|
||||
const QByteArray &key,
|
||||
const QByteArray &iv,
|
||||
const QByteArray &salt) const;
|
||||
|
||||
EncryptedRequestData prepareRequest(const QString &endpoint, const QJsonObject &apiPayload);
|
||||
DecryptionResult tryDecryptResponseBody(const QByteArray &encryptedResponseBody, QNetworkReply::NetworkError replyError,
|
||||
const QByteArray &key, const QByteArray &iv, const QByteArray &salt);
|
||||
|
||||
QStringList getProxyUrls(const QString &serviceType, const QString &userCountryCode);
|
||||
bool shouldBypassProxy(const QNetworkReply::NetworkError &replyError, const QByteArray &decryptedResponseBody, bool isDecryptionSuccessful);
|
||||
void bypassProxy(const QString &endpoint, const QString &serviceType, const QString &userCountryCode,
|
||||
std::function<QNetworkReply *(const QString &url)> requestFunction,
|
||||
std::function<bool(QNetworkReply *reply, const QList<QSslError> &sslErrors)> replyProcessingFunction);
|
||||
|
||||
void getProxyUrlsAsync(const QStringList proxyStorageUrls, const int currentProxyStorageIndex,
|
||||
std::function<void(const QStringList &)> onComplete);
|
||||
void getProxyUrlAsync(const QStringList proxyUrls, const int currentProxyIndex, std::function<void(const QString &)> onComplete);
|
||||
void bypassProxyAsync(
|
||||
const QString &endpoint, const QString &proxyUrl, EncryptedRequestData encRequestData,
|
||||
std::function<void(const QByteArray &, bool, const QList<QSslError> &, QNetworkReply::NetworkError, const QString &, int)> onComplete);
|
||||
std::shared_ptr<amnezia::transport::IGatewayTransport> currentTransport() const;
|
||||
static std::shared_ptr<amnezia::transport::IGatewayTransport> buildTransport(
|
||||
const TransportsConfig &config, int requestTimeoutMsecs, bool isDevEnvironment, bool isStrictKillSwitchEnabled);
|
||||
|
||||
int m_requestTimeoutMsecs;
|
||||
QString m_gatewayEndpoint;
|
||||
bool m_isDevEnvironment = false;
|
||||
bool m_isStrictKillSwitchEnabled = false;
|
||||
|
||||
inline static QString m_proxyUrl;
|
||||
mutable QMutex m_transportMutex;
|
||||
std::shared_ptr<amnezia::transport::IGatewayTransport> m_transport;
|
||||
};
|
||||
|
||||
#endif // GATEWAYCONTROLLER_H
|
||||
|
||||
@@ -44,6 +44,7 @@
|
||||
|
||||
#include <QHostAddress>
|
||||
#include <QHostInfo>
|
||||
#include <QDebug>
|
||||
|
||||
QRegularExpression NetworkUtilities::ipAddressRegExp()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
#include "dnsPacket_p.h"
|
||||
|
||||
#include <QHostInfo>
|
||||
#include <cstring>
|
||||
|
||||
namespace amnezia::transport::dns::detail
|
||||
{
|
||||
|
||||
QHostAddress resolveHostAddress(const QString &host)
|
||||
{
|
||||
QHostAddress addr(host);
|
||||
if (!addr.isNull()) return addr;
|
||||
QHostInfo info = QHostInfo::fromName(host);
|
||||
if (!info.addresses().isEmpty()) return info.addresses().first();
|
||||
return QHostAddress();
|
||||
}
|
||||
|
||||
QByteArray encodeDnsName(const QString &hostname)
|
||||
{
|
||||
QByteArray result;
|
||||
const QStringList parts = hostname.split('.');
|
||||
|
||||
for (const QString &part : parts) {
|
||||
if (part.length() > 63) {
|
||||
return QByteArray();
|
||||
}
|
||||
result.append(static_cast<char>(part.length()));
|
||||
result.append(part.toUtf8());
|
||||
}
|
||||
result.append(static_cast<char>(0));
|
||||
return result;
|
||||
}
|
||||
|
||||
QByteArray buildDnsQuery(const QString &hostname, quint16 transactionId)
|
||||
{
|
||||
QByteArray packet;
|
||||
|
||||
DnsHeader header;
|
||||
header.id = qToBigEndian(transactionId);
|
||||
header.flags = qToBigEndian<quint16>(0x0100);
|
||||
header.qdcount = qToBigEndian<quint16>(1);
|
||||
header.ancount = 0;
|
||||
header.nscount = 0;
|
||||
header.arcount = 0;
|
||||
|
||||
packet.append(reinterpret_cast<const char *>(&header), sizeof(DnsHeader));
|
||||
|
||||
const QByteArray qname = encodeDnsName(hostname);
|
||||
if (qname.isEmpty()) {
|
||||
return QByteArray();
|
||||
}
|
||||
packet.append(qname);
|
||||
|
||||
quint16 qtype = qToBigEndian<quint16>(DNS_TYPE_A);
|
||||
packet.append(reinterpret_cast<const char *>(&qtype), sizeof(quint16));
|
||||
|
||||
quint16 qclass = qToBigEndian<quint16>(DNS_CLASS_IN);
|
||||
packet.append(reinterpret_cast<const char *>(&qclass), sizeof(quint16));
|
||||
|
||||
return packet;
|
||||
}
|
||||
|
||||
QString parseDnsResponse(const QByteArray &response, bool isTcp)
|
||||
{
|
||||
if (response.size() < static_cast<int>(sizeof(DnsHeader))) {
|
||||
return QString();
|
||||
}
|
||||
|
||||
int offset = isTcp ? 2 : 0;
|
||||
if (response.size() < offset + static_cast<int>(sizeof(DnsHeader))) {
|
||||
return QString();
|
||||
}
|
||||
|
||||
DnsHeader header;
|
||||
std::memcpy(&header, response.constData() + offset, sizeof(DnsHeader));
|
||||
offset += sizeof(DnsHeader);
|
||||
|
||||
const quint16 flags = qFromBigEndian(header.flags);
|
||||
const quint16 ancount = qFromBigEndian(header.ancount);
|
||||
|
||||
if ((flags & 0x8000) == 0 || (flags & 0x000F) != 0) {
|
||||
return QString();
|
||||
}
|
||||
|
||||
if (ancount == 0) {
|
||||
return QString();
|
||||
}
|
||||
|
||||
while (offset < response.size() && response.at(offset) != 0) {
|
||||
const quint8 length = static_cast<quint8>(response.at(offset));
|
||||
if (length > 63) {
|
||||
return QString();
|
||||
}
|
||||
offset += length + 1;
|
||||
}
|
||||
if (offset >= response.size()) {
|
||||
return QString();
|
||||
}
|
||||
offset++;
|
||||
|
||||
offset += 4;
|
||||
|
||||
for (int i = 0; i < ancount && offset < response.size(); ++i) {
|
||||
if (offset >= response.size()) {
|
||||
break;
|
||||
}
|
||||
|
||||
const quint8 nameByte = static_cast<quint8>(response.at(offset));
|
||||
if ((nameByte & 0xC0) == 0xC0) {
|
||||
offset += 2;
|
||||
} else {
|
||||
while (offset < response.size() && response.at(offset) != 0) {
|
||||
const quint8 length = static_cast<quint8>(response.at(offset));
|
||||
if (length > 63) {
|
||||
return QString();
|
||||
}
|
||||
offset += length + 1;
|
||||
}
|
||||
offset++;
|
||||
}
|
||||
|
||||
if (offset + 10 > response.size()) {
|
||||
break;
|
||||
}
|
||||
|
||||
const quint16 type =
|
||||
qFromBigEndian<quint16>(*reinterpret_cast<const quint16 *>(response.constData() + offset));
|
||||
offset += 2;
|
||||
offset += 2;
|
||||
offset += 4;
|
||||
|
||||
const quint16 rdlength =
|
||||
qFromBigEndian<quint16>(*reinterpret_cast<const quint16 *>(response.constData() + offset));
|
||||
offset += 2;
|
||||
|
||||
if (type == DNS_TYPE_A && rdlength == 4) {
|
||||
if (offset + 4 > response.size()) {
|
||||
break;
|
||||
}
|
||||
|
||||
QHostAddress ip;
|
||||
ip.setAddress(
|
||||
qFromBigEndian<quint32>(*reinterpret_cast<const quint32 *>(response.constData() + offset)));
|
||||
return ip.toString();
|
||||
}
|
||||
|
||||
offset += rdlength;
|
||||
}
|
||||
|
||||
return QString();
|
||||
}
|
||||
|
||||
} // namespace amnezia::transport::dns::detail
|
||||
@@ -0,0 +1,38 @@
|
||||
#ifndef DNSPACKET_P_H
|
||||
#define DNSPACKET_P_H
|
||||
|
||||
#include <QByteArray>
|
||||
#include <QHostAddress>
|
||||
#include <QString>
|
||||
#include <QtEndian>
|
||||
|
||||
namespace amnezia::transport::dns::detail
|
||||
{
|
||||
|
||||
constexpr quint16 DNS_PORT = 53;
|
||||
constexpr quint16 DNS_TYPE_A = 1;
|
||||
constexpr quint16 DNS_CLASS_IN = 1;
|
||||
|
||||
#pragma pack(push, 1)
|
||||
struct DnsHeader
|
||||
{
|
||||
quint16 id;
|
||||
quint16 flags;
|
||||
quint16 qdcount;
|
||||
quint16 ancount;
|
||||
quint16 nscount;
|
||||
quint16 arcount;
|
||||
};
|
||||
#pragma pack(pop)
|
||||
|
||||
QHostAddress resolveHostAddress(const QString &host);
|
||||
|
||||
QByteArray encodeDnsName(const QString &hostname);
|
||||
|
||||
QByteArray buildDnsQuery(const QString &hostname, quint16 transactionId);
|
||||
|
||||
QString parseDnsResponse(const QByteArray &response, bool isTcp);
|
||||
|
||||
} // namespace amnezia::transport::dns::detail
|
||||
|
||||
#endif // DNSPACKET_P_H
|
||||
@@ -0,0 +1,354 @@
|
||||
#include "dnsResolver.h"
|
||||
|
||||
#include "dnsPacket_p.h"
|
||||
|
||||
#include <QDateTime>
|
||||
#include <QEventLoop>
|
||||
#include <QHostAddress>
|
||||
#include <QNetworkAccessManager>
|
||||
#include <QNetworkDatagram>
|
||||
#include <QNetworkReply>
|
||||
#include <QNetworkRequest>
|
||||
#include <QSslSocket>
|
||||
#include <QTcpSocket>
|
||||
#include <QTimer>
|
||||
#include <QUdpSocket>
|
||||
#include <QUrl>
|
||||
|
||||
namespace amnezia::transport::dns::DnsResolver
|
||||
{
|
||||
|
||||
using detail::buildDnsQuery;
|
||||
using detail::parseDnsResponse;
|
||||
using detail::resolveHostAddress;
|
||||
|
||||
QString resolve(const QString &hostname,
|
||||
const QString &dnsServer,
|
||||
DnsProtocol protocol,
|
||||
quint16 port,
|
||||
int timeoutMsecs,
|
||||
const QString &dohEndpoint)
|
||||
{
|
||||
switch (protocol) {
|
||||
case DnsProtocol::Udp:
|
||||
return resolveOverUdp(hostname, dnsServer, port, timeoutMsecs);
|
||||
case DnsProtocol::Tcp:
|
||||
return resolveOverTcp(hostname, dnsServer, port, timeoutMsecs);
|
||||
case DnsProtocol::Tls:
|
||||
return resolveOverTls(hostname, dnsServer, port, timeoutMsecs);
|
||||
case DnsProtocol::Https:
|
||||
return resolveOverHttps(hostname, dnsServer, dohEndpoint, timeoutMsecs);
|
||||
case DnsProtocol::Quic:
|
||||
return resolveOverQuic(hostname, dnsServer, port, timeoutMsecs);
|
||||
}
|
||||
return QString();
|
||||
}
|
||||
|
||||
QString resolveOverUdp(const QString &hostname, const QString &dnsServer, quint16 port, int timeoutMsecs)
|
||||
{
|
||||
QUdpSocket socket;
|
||||
|
||||
const quint16 transactionId = static_cast<quint16>(QDateTime::currentMSecsSinceEpoch() & 0xFFFF);
|
||||
const QByteArray query = buildDnsQuery(hostname, transactionId);
|
||||
if (query.isEmpty()) {
|
||||
return QString();
|
||||
}
|
||||
|
||||
const QHostAddress dnsAddress = resolveHostAddress(dnsServer);
|
||||
if (dnsAddress.isNull()) {
|
||||
return QString();
|
||||
}
|
||||
|
||||
const qint64 bytesWritten = socket.writeDatagram(query, dnsAddress, port);
|
||||
if (bytesWritten != query.size()) {
|
||||
return QString();
|
||||
}
|
||||
|
||||
QEventLoop loop;
|
||||
QTimer timer;
|
||||
timer.setSingleShot(true);
|
||||
timer.setInterval(timeoutMsecs);
|
||||
|
||||
QByteArray response;
|
||||
bool responseReceived = false;
|
||||
|
||||
QObject::connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit);
|
||||
QObject::connect(&socket, &QUdpSocket::readyRead, [&]() {
|
||||
while (socket.hasPendingDatagrams()) {
|
||||
QNetworkDatagram datagram = socket.receiveDatagram();
|
||||
if (datagram.isValid()) {
|
||||
response = datagram.data();
|
||||
responseReceived = true;
|
||||
loop.quit();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
timer.start();
|
||||
loop.exec();
|
||||
timer.stop();
|
||||
|
||||
if (!responseReceived || response.isEmpty()) {
|
||||
return QString();
|
||||
}
|
||||
|
||||
return parseDnsResponse(response, false);
|
||||
}
|
||||
|
||||
QString resolveOverTcp(const QString &hostname, const QString &dnsServer, quint16 port, int timeoutMsecs)
|
||||
{
|
||||
QTcpSocket socket;
|
||||
|
||||
const QHostAddress dnsAddress = resolveHostAddress(dnsServer);
|
||||
if (dnsAddress.isNull()) {
|
||||
return QString();
|
||||
}
|
||||
|
||||
socket.connectToHost(dnsAddress, port);
|
||||
if (!socket.waitForConnected(timeoutMsecs)) {
|
||||
return QString();
|
||||
}
|
||||
|
||||
const quint16 transactionId = static_cast<quint16>(QDateTime::currentMSecsSinceEpoch() & 0xFFFF);
|
||||
const QByteArray query = buildDnsQuery(hostname, transactionId);
|
||||
if (query.isEmpty()) {
|
||||
socket.close();
|
||||
return QString();
|
||||
}
|
||||
|
||||
quint16 length = qToBigEndian<quint16>(static_cast<quint16>(query.size()));
|
||||
QByteArray tcpQuery;
|
||||
tcpQuery.append(reinterpret_cast<const char *>(&length), sizeof(quint16));
|
||||
tcpQuery.append(query);
|
||||
|
||||
const qint64 bytesWritten = socket.write(tcpQuery);
|
||||
if (bytesWritten != tcpQuery.size() || !socket.waitForBytesWritten(timeoutMsecs)) {
|
||||
socket.close();
|
||||
return QString();
|
||||
}
|
||||
|
||||
QEventLoop loop;
|
||||
QTimer timer;
|
||||
timer.setSingleShot(true);
|
||||
timer.setInterval(timeoutMsecs);
|
||||
|
||||
QByteArray response;
|
||||
bool responseReceived = false;
|
||||
|
||||
QObject::connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit);
|
||||
QObject::connect(&socket, &QTcpSocket::readyRead, [&]() {
|
||||
if (socket.bytesAvailable() >= 2 && response.isEmpty()) {
|
||||
QByteArray lengthBytes = socket.read(2);
|
||||
if (lengthBytes.size() == 2) {
|
||||
const quint16 responseLength =
|
||||
qFromBigEndian<quint16>(*reinterpret_cast<const quint16 *>(lengthBytes.constData()));
|
||||
while (socket.bytesAvailable() < responseLength) {
|
||||
if (!socket.waitForReadyRead(timeoutMsecs / 2)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (socket.bytesAvailable() >= responseLength) {
|
||||
response = socket.read(responseLength);
|
||||
responseReceived = true;
|
||||
loop.quit();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
timer.start();
|
||||
loop.exec();
|
||||
timer.stop();
|
||||
|
||||
socket.close();
|
||||
|
||||
if (!responseReceived || response.isEmpty()) {
|
||||
return QString();
|
||||
}
|
||||
|
||||
return parseDnsResponse(response, true);
|
||||
}
|
||||
|
||||
QString resolveOverTls(const QString &hostname, const QString &dnsServer, quint16 port, int timeoutMsecs)
|
||||
{
|
||||
QSslSocket socket;
|
||||
|
||||
const QHostAddress dnsAddress = resolveHostAddress(dnsServer);
|
||||
if (dnsAddress.isNull()) {
|
||||
return QString();
|
||||
}
|
||||
|
||||
socket.setPeerVerifyMode(QSslSocket::QueryPeer);
|
||||
socket.connectToHostEncrypted(dnsAddress.toString(), port);
|
||||
|
||||
if (!socket.waitForConnected(timeoutMsecs)) {
|
||||
return QString();
|
||||
}
|
||||
|
||||
if (!socket.waitForEncrypted(timeoutMsecs)) {
|
||||
socket.close();
|
||||
return QString();
|
||||
}
|
||||
|
||||
const quint16 transactionId = static_cast<quint16>(QDateTime::currentMSecsSinceEpoch() & 0xFFFF);
|
||||
const QByteArray query = buildDnsQuery(hostname, transactionId);
|
||||
if (query.isEmpty()) {
|
||||
socket.close();
|
||||
return QString();
|
||||
}
|
||||
|
||||
quint16 length = qToBigEndian<quint16>(static_cast<quint16>(query.size()));
|
||||
QByteArray tlsQuery;
|
||||
tlsQuery.append(reinterpret_cast<const char *>(&length), sizeof(quint16));
|
||||
tlsQuery.append(query);
|
||||
|
||||
const qint64 bytesWritten = socket.write(tlsQuery);
|
||||
if (bytesWritten != tlsQuery.size() || !socket.waitForBytesWritten(timeoutMsecs)) {
|
||||
socket.close();
|
||||
return QString();
|
||||
}
|
||||
|
||||
QEventLoop loop;
|
||||
QTimer timer;
|
||||
timer.setSingleShot(true);
|
||||
timer.setInterval(timeoutMsecs);
|
||||
|
||||
QByteArray response;
|
||||
bool responseReceived = false;
|
||||
|
||||
QObject::connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit);
|
||||
QObject::connect(&socket, &QSslSocket::readyRead, [&]() {
|
||||
if (socket.bytesAvailable() >= 2 && response.isEmpty()) {
|
||||
QByteArray lengthBytes = socket.read(2);
|
||||
if (lengthBytes.size() == 2) {
|
||||
const quint16 responseLength =
|
||||
qFromBigEndian<quint16>(*reinterpret_cast<const quint16 *>(lengthBytes.constData()));
|
||||
while (socket.bytesAvailable() < responseLength) {
|
||||
if (!socket.waitForReadyRead(timeoutMsecs / 2)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (socket.bytesAvailable() >= responseLength) {
|
||||
response = socket.read(responseLength);
|
||||
responseReceived = true;
|
||||
loop.quit();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
timer.start();
|
||||
loop.exec();
|
||||
timer.stop();
|
||||
|
||||
socket.close();
|
||||
|
||||
if (!responseReceived || response.isEmpty()) {
|
||||
return QString();
|
||||
}
|
||||
|
||||
return parseDnsResponse(response, true);
|
||||
}
|
||||
|
||||
QString resolveOverHttps(const QString &hostname, const QString &dnsServer, const QString &endpoint, int timeoutMsecs)
|
||||
{
|
||||
const QString dohUrl = QStringLiteral("https://%1%2").arg(dnsServer, endpoint);
|
||||
|
||||
const quint16 transactionId = static_cast<quint16>(QDateTime::currentMSecsSinceEpoch() & 0xFFFF);
|
||||
const QByteArray query = buildDnsQuery(hostname, transactionId);
|
||||
if (query.isEmpty()) {
|
||||
return QString();
|
||||
}
|
||||
|
||||
QNetworkRequest request;
|
||||
request.setUrl(QUrl(dohUrl));
|
||||
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/dns-message");
|
||||
request.setRawHeader("Accept", "application/dns-message");
|
||||
request.setTransferTimeout(timeoutMsecs);
|
||||
|
||||
QNetworkAccessManager nam;
|
||||
QNetworkReply *reply = nam.post(request, query);
|
||||
|
||||
QEventLoop loop;
|
||||
QTimer timer;
|
||||
timer.setSingleShot(true);
|
||||
timer.setInterval(timeoutMsecs);
|
||||
|
||||
QByteArray response;
|
||||
bool responseReceived = false;
|
||||
|
||||
QObject::connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit);
|
||||
QObject::connect(reply, &QNetworkReply::finished, [&]() {
|
||||
if (reply->error() == QNetworkReply::NoError) {
|
||||
response = reply->readAll();
|
||||
responseReceived = true;
|
||||
}
|
||||
loop.quit();
|
||||
});
|
||||
|
||||
timer.start();
|
||||
loop.exec();
|
||||
timer.stop();
|
||||
|
||||
reply->deleteLater();
|
||||
|
||||
if (!responseReceived || response.isEmpty()) {
|
||||
return QString();
|
||||
}
|
||||
|
||||
return parseDnsResponse(response, false);
|
||||
}
|
||||
|
||||
QString resolveOverQuic(const QString &hostname, const QString &dnsServer, quint16 port, int timeoutMsecs)
|
||||
{
|
||||
// QUIC требует специальной библиотеки — пока используем UDP fallback
|
||||
QUdpSocket socket;
|
||||
|
||||
const QHostAddress dnsAddress = resolveHostAddress(dnsServer);
|
||||
if (dnsAddress.isNull()) {
|
||||
return QString();
|
||||
}
|
||||
|
||||
const quint16 transactionId = static_cast<quint16>(QDateTime::currentMSecsSinceEpoch() & 0xFFFF);
|
||||
const QByteArray query = buildDnsQuery(hostname, transactionId);
|
||||
if (query.isEmpty()) {
|
||||
return QString();
|
||||
}
|
||||
|
||||
const qint64 bytesWritten = socket.writeDatagram(query, dnsAddress, port);
|
||||
if (bytesWritten != query.size()) {
|
||||
return QString();
|
||||
}
|
||||
|
||||
QEventLoop loop;
|
||||
QTimer timer;
|
||||
timer.setSingleShot(true);
|
||||
timer.setInterval(timeoutMsecs);
|
||||
|
||||
QByteArray response;
|
||||
bool responseReceived = false;
|
||||
|
||||
QObject::connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit);
|
||||
QObject::connect(&socket, &QUdpSocket::readyRead, [&]() {
|
||||
while (socket.hasPendingDatagrams()) {
|
||||
QNetworkDatagram datagram = socket.receiveDatagram();
|
||||
if (datagram.isValid()) {
|
||||
response = datagram.data();
|
||||
responseReceived = true;
|
||||
loop.quit();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
timer.start();
|
||||
loop.exec();
|
||||
timer.stop();
|
||||
|
||||
if (!responseReceived || response.isEmpty()) {
|
||||
return QString();
|
||||
}
|
||||
|
||||
return parseDnsResponse(response, false);
|
||||
}
|
||||
|
||||
} // namespace amnezia::transport::dns::DnsResolver
|
||||
@@ -0,0 +1,29 @@
|
||||
#ifndef DNSRESOLVER_H
|
||||
#define DNSRESOLVER_H
|
||||
|
||||
#include <QString>
|
||||
|
||||
namespace amnezia::transport::dns
|
||||
{
|
||||
|
||||
enum class DnsProtocol { Udp, Tcp, Tls, Https, Quic };
|
||||
|
||||
namespace DnsResolver
|
||||
{
|
||||
QString resolve(const QString &hostname,
|
||||
const QString &dnsServer,
|
||||
DnsProtocol protocol,
|
||||
quint16 port,
|
||||
int timeoutMsecs = 3000,
|
||||
const QString &dohEndpoint = QStringLiteral("/dns-query"));
|
||||
|
||||
QString resolveOverUdp(const QString &hostname, const QString &dnsServer, quint16 port, int timeoutMsecs = 3000);
|
||||
QString resolveOverTcp(const QString &hostname, const QString &dnsServer, quint16 port, int timeoutMsecs = 3000);
|
||||
QString resolveOverTls(const QString &hostname, const QString &dnsServer, quint16 port, int timeoutMsecs = 3000);
|
||||
QString resolveOverHttps(const QString &hostname, const QString &dnsServer, const QString &endpoint, int timeoutMsecs = 3000);
|
||||
QString resolveOverQuic(const QString &hostname, const QString &dnsServer, quint16 port, int timeoutMsecs = 3000);
|
||||
} // namespace DnsResolver
|
||||
|
||||
} // namespace amnezia::transport::dns
|
||||
|
||||
#endif // DNSRESOLVER_H
|
||||
@@ -0,0 +1,817 @@
|
||||
#include "dnsTunnel.h"
|
||||
|
||||
#include "dnsPacket_p.h"
|
||||
|
||||
#include <QDateTime>
|
||||
#include <QDebug>
|
||||
#include <QElapsedTimer>
|
||||
#include <QEventLoop>
|
||||
#include <QHostAddress>
|
||||
#include <QList>
|
||||
#include <QMap>
|
||||
#include <QNetworkAccessManager>
|
||||
#include <QNetworkDatagram>
|
||||
#include <QNetworkReply>
|
||||
#include <QNetworkRequest>
|
||||
#include <QSharedPointer>
|
||||
#include <QSslError>
|
||||
#include <QSslSocket>
|
||||
#include <QStringList>
|
||||
#include <QTcpSocket>
|
||||
#include <QThread>
|
||||
#include <QTimer>
|
||||
#include <QUdpSocket>
|
||||
#include <QUrl>
|
||||
|
||||
namespace amnezia::transport::dns::DnsTunnel
|
||||
{
|
||||
|
||||
using detail::resolveHostAddress;
|
||||
|
||||
namespace
|
||||
{
|
||||
constexpr quint16 EDNS0_PAYLOAD_OPTION_CODE = 65001;
|
||||
constexpr quint16 EDNS0_CHUNK_REQUEST_CODE = 65002;
|
||||
constexpr quint16 EDNS0_CHUNK_RESPONSE_CODE = 65003;
|
||||
|
||||
struct ChunkMeta
|
||||
{
|
||||
QByteArray chunkId;
|
||||
quint16 totalChunks = 0;
|
||||
quint16 chunkIndex = 0;
|
||||
quint32 totalSize = 0;
|
||||
};
|
||||
|
||||
void appendUint16BE(QByteArray &data, quint16 value)
|
||||
{
|
||||
data.append(static_cast<char>((value >> 8) & 0xFF));
|
||||
data.append(static_cast<char>(value & 0xFF));
|
||||
}
|
||||
|
||||
QByteArray buildDnsChunkRequest(const QString &queryName, quint16 transactionId,
|
||||
const QByteArray &chunkId, quint16 chunkIndex)
|
||||
{
|
||||
QByteArray query;
|
||||
|
||||
appendUint16BE(query, transactionId);
|
||||
appendUint16BE(query, 0x0100);
|
||||
appendUint16BE(query, 1);
|
||||
appendUint16BE(query, 0);
|
||||
appendUint16BE(query, 0);
|
||||
appendUint16BE(query, 1);
|
||||
|
||||
const QStringList labels = queryName.split('.');
|
||||
for (const QString &label : labels) {
|
||||
QByteArray labelBytes = label.toUtf8();
|
||||
query.append(static_cast<char>(labelBytes.size()));
|
||||
query.append(labelBytes);
|
||||
}
|
||||
query.append(static_cast<char>(0));
|
||||
appendUint16BE(query, 16);
|
||||
appendUint16BE(query, 1);
|
||||
|
||||
const quint16 optionDataLen = 4 + 18;
|
||||
|
||||
query.append(static_cast<char>(0));
|
||||
appendUint16BE(query, 41);
|
||||
appendUint16BE(query, 4096);
|
||||
query.append(static_cast<char>(0));
|
||||
query.append(static_cast<char>(0));
|
||||
appendUint16BE(query, 0);
|
||||
appendUint16BE(query, optionDataLen);
|
||||
|
||||
appendUint16BE(query, EDNS0_CHUNK_REQUEST_CODE);
|
||||
appendUint16BE(query, 18);
|
||||
query.append(chunkId.left(16).leftJustified(16, '\0'));
|
||||
appendUint16BE(query, chunkIndex);
|
||||
|
||||
return query;
|
||||
}
|
||||
|
||||
ChunkMeta parseChunkMeta(const QByteArray &response)
|
||||
{
|
||||
ChunkMeta meta;
|
||||
|
||||
if (response.size() < 12) return meta;
|
||||
|
||||
const quint8 *data = reinterpret_cast<const quint8 *>(response.constData());
|
||||
|
||||
const quint16 qdCount = (data[4] << 8) | data[5];
|
||||
const quint16 anCount = (data[6] << 8) | data[7];
|
||||
const quint16 nsCount = (data[8] << 8) | data[9];
|
||||
const quint16 arCount = (data[10] << 8) | data[11];
|
||||
|
||||
int pos = 12;
|
||||
|
||||
auto skipDnsName = [&]() -> bool {
|
||||
int maxLabels = 128;
|
||||
while (pos < response.size() && data[pos] != 0 && maxLabels-- > 0) {
|
||||
if ((data[pos] & 0xC0) == 0xC0) {
|
||||
pos += 2;
|
||||
return pos <= response.size();
|
||||
}
|
||||
const int labelLen = data[pos];
|
||||
if (pos + 1 + labelLen > response.size()) return false;
|
||||
pos += labelLen + 1;
|
||||
}
|
||||
if (pos < response.size() && data[pos] == 0) pos++;
|
||||
return pos <= response.size();
|
||||
};
|
||||
|
||||
for (int i = 0; i < qdCount && pos < response.size(); ++i) {
|
||||
if (!skipDnsName()) return meta;
|
||||
if (pos + 4 > response.size()) return meta;
|
||||
pos += 4;
|
||||
}
|
||||
|
||||
for (int i = 0; i < anCount && pos < response.size(); ++i) {
|
||||
if (!skipDnsName()) return meta;
|
||||
if (pos + 10 > response.size()) return meta;
|
||||
const quint16 rdlen = (data[pos + 8] << 8) | data[pos + 9];
|
||||
if (pos + 10 + rdlen > response.size()) return meta;
|
||||
pos += 10 + rdlen;
|
||||
}
|
||||
|
||||
for (int i = 0; i < nsCount && pos < response.size(); ++i) {
|
||||
if (!skipDnsName()) return meta;
|
||||
if (pos + 10 > response.size()) return meta;
|
||||
const quint16 rdlen = (data[pos + 8] << 8) | data[pos + 9];
|
||||
if (pos + 10 + rdlen > response.size()) return meta;
|
||||
pos += 10 + rdlen;
|
||||
}
|
||||
|
||||
for (int i = 0; i < arCount && pos < response.size(); ++i) {
|
||||
if (pos < response.size() && data[pos] == 0) {
|
||||
pos++;
|
||||
} else {
|
||||
if (!skipDnsName()) return meta;
|
||||
}
|
||||
|
||||
if (pos + 10 > response.size()) return meta;
|
||||
|
||||
const quint16 rtype = (data[pos] << 8) | data[pos + 1];
|
||||
const quint16 rdlen = (data[pos + 8] << 8) | data[pos + 9];
|
||||
if (pos + 10 + rdlen > response.size()) return meta;
|
||||
pos += 10;
|
||||
|
||||
if (rtype == 41 && rdlen > 0) {
|
||||
const int optEnd = pos + rdlen;
|
||||
while (pos + 4 <= optEnd) {
|
||||
const quint16 optCode = (data[pos] << 8) | data[pos + 1];
|
||||
const quint16 optLen = (data[pos + 2] << 8) | data[pos + 3];
|
||||
pos += 4;
|
||||
|
||||
if (optCode == EDNS0_CHUNK_RESPONSE_CODE && optLen >= 24) {
|
||||
meta.chunkId = QByteArray(reinterpret_cast<const char *>(data + pos), 16);
|
||||
meta.totalChunks = (data[pos + 16] << 8) | data[pos + 17];
|
||||
meta.chunkIndex = (data[pos + 18] << 8) | data[pos + 19];
|
||||
meta.totalSize = (static_cast<quint32>(data[pos + 20]) << 24)
|
||||
| (static_cast<quint32>(data[pos + 21]) << 16)
|
||||
| (static_cast<quint32>(data[pos + 22]) << 8) | data[pos + 23];
|
||||
return meta;
|
||||
}
|
||||
pos += optLen;
|
||||
}
|
||||
} else {
|
||||
pos += rdlen;
|
||||
}
|
||||
}
|
||||
|
||||
return meta;
|
||||
}
|
||||
|
||||
QByteArray buildDnsTxtQueryWithPayload(const QString &queryName, quint16 transactionId, const QByteArray &payload)
|
||||
{
|
||||
QByteArray query;
|
||||
|
||||
appendUint16BE(query, transactionId);
|
||||
appendUint16BE(query, 0x0100);
|
||||
appendUint16BE(query, 1);
|
||||
appendUint16BE(query, 0);
|
||||
appendUint16BE(query, 0);
|
||||
appendUint16BE(query, 1);
|
||||
|
||||
const QStringList labels = queryName.split('.');
|
||||
for (const QString &label : labels) {
|
||||
QByteArray labelBytes = label.toUtf8();
|
||||
query.append(static_cast<char>(labelBytes.size()));
|
||||
query.append(labelBytes);
|
||||
}
|
||||
query.append(static_cast<char>(0));
|
||||
appendUint16BE(query, 16);
|
||||
appendUint16BE(query, 1);
|
||||
|
||||
const QByteArray payloadBase64 = payload.toBase64();
|
||||
const quint16 optionDataLen = 4 + payloadBase64.size();
|
||||
|
||||
query.append(static_cast<char>(0));
|
||||
appendUint16BE(query, 41);
|
||||
appendUint16BE(query, 4096);
|
||||
query.append(static_cast<char>(0));
|
||||
query.append(static_cast<char>(0));
|
||||
appendUint16BE(query, 0);
|
||||
appendUint16BE(query, optionDataLen);
|
||||
|
||||
appendUint16BE(query, EDNS0_PAYLOAD_OPTION_CODE);
|
||||
appendUint16BE(query, payloadBase64.size());
|
||||
query.append(payloadBase64);
|
||||
|
||||
return query;
|
||||
}
|
||||
|
||||
QByteArray parseDnsTxtResponse(const QByteArray &response)
|
||||
{
|
||||
if (response.size() < 12) {
|
||||
return QByteArray();
|
||||
}
|
||||
|
||||
const uchar *data = reinterpret_cast<const uchar *>(response.constData());
|
||||
int pos = 0;
|
||||
|
||||
pos += 2;
|
||||
const quint16 flags = (data[pos] << 8) | data[pos + 1]; pos += 2;
|
||||
const quint16 qdCount = (data[pos] << 8) | data[pos + 1]; pos += 2;
|
||||
const quint16 anCount = (data[pos] << 8) | data[pos + 1]; pos += 2;
|
||||
pos += 2;
|
||||
pos += 2;
|
||||
|
||||
if ((flags & 0x8000) == 0) {
|
||||
return QByteArray();
|
||||
}
|
||||
|
||||
if (anCount > 100 || qdCount > 10) {
|
||||
return QByteArray();
|
||||
}
|
||||
|
||||
auto skipDnsName = [&]() -> bool {
|
||||
int maxLabels = 128;
|
||||
while (pos < response.size() && data[pos] != 0 && maxLabels-- > 0) {
|
||||
if ((data[pos] & 0xC0) == 0xC0) {
|
||||
pos += 2;
|
||||
return pos <= response.size();
|
||||
}
|
||||
const int labelLen = data[pos];
|
||||
if (pos + 1 + labelLen > response.size()) return false;
|
||||
pos += labelLen + 1;
|
||||
}
|
||||
if (pos < response.size() && data[pos] == 0) pos++;
|
||||
return pos <= response.size();
|
||||
};
|
||||
|
||||
for (int i = 0; i < qdCount && pos < response.size(); ++i) {
|
||||
if (!skipDnsName()) {
|
||||
return QByteArray();
|
||||
}
|
||||
if (pos + 4 > response.size()) return QByteArray();
|
||||
pos += 4;
|
||||
}
|
||||
|
||||
QByteArray combinedTxt;
|
||||
for (int i = 0; i < anCount && pos < response.size(); ++i) {
|
||||
if (!skipDnsName()) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (pos + 10 > response.size()) {
|
||||
break;
|
||||
}
|
||||
|
||||
const quint16 rtype = (data[pos] << 8) | data[pos + 1]; pos += 2;
|
||||
pos += 2; // class
|
||||
pos += 4; // ttl
|
||||
const quint16 rdlength = (data[pos] << 8) | data[pos + 1]; pos += 2;
|
||||
|
||||
if (pos + rdlength > response.size()) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (rtype == 16) {
|
||||
const int rdEnd = pos + rdlength;
|
||||
while (pos < rdEnd && pos < response.size()) {
|
||||
const quint8 txtLen = data[pos++];
|
||||
if (txtLen > 0 && pos + txtLen <= rdEnd && pos + txtLen <= response.size()) {
|
||||
combinedTxt.append(reinterpret_cast<const char *>(data + pos), txtLen);
|
||||
pos += txtLen;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
pos += rdlength;
|
||||
}
|
||||
}
|
||||
|
||||
if (combinedTxt.isEmpty()) {
|
||||
return QByteArray();
|
||||
}
|
||||
|
||||
return QByteArray::fromBase64(combinedTxt);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
QByteArray send(const QByteArray &payload,
|
||||
const QString &endpointName,
|
||||
const QString &baseDomain,
|
||||
const QString &dnsServer,
|
||||
DnsProtocol protocol,
|
||||
quint16 port,
|
||||
int timeoutMsecs,
|
||||
const QString &dohEndpoint)
|
||||
{
|
||||
const QString queryName = QStringLiteral("%1.%2").arg(endpointName, baseDomain);
|
||||
|
||||
switch (protocol) {
|
||||
case DnsProtocol::Udp:
|
||||
return sendOverUdpChunked(payload, queryName, dnsServer, port, timeoutMsecs);
|
||||
case DnsProtocol::Tcp:
|
||||
return sendOverTcp(payload, queryName, dnsServer, port, timeoutMsecs);
|
||||
case DnsProtocol::Tls:
|
||||
return sendOverTls(payload, queryName, dnsServer, port, timeoutMsecs);
|
||||
case DnsProtocol::Https:
|
||||
return sendOverHttps(payload, queryName, dnsServer, port, dohEndpoint, timeoutMsecs);
|
||||
case DnsProtocol::Quic:
|
||||
return QByteArray();
|
||||
}
|
||||
return QByteArray();
|
||||
}
|
||||
|
||||
QByteArray sendOverUdp(const QByteArray &payload, const QString &queryName,
|
||||
const QString &dnsServer, quint16 port, int timeoutMsecs)
|
||||
{
|
||||
QUdpSocket socket;
|
||||
|
||||
const quint16 transactionId = static_cast<quint16>(QDateTime::currentMSecsSinceEpoch() & 0xFFFF);
|
||||
const QByteArray query = buildDnsTxtQueryWithPayload(queryName, transactionId, payload);
|
||||
|
||||
if (query.isEmpty()) {
|
||||
return QByteArray();
|
||||
}
|
||||
|
||||
const QHostAddress dnsAddress = resolveHostAddress(dnsServer);
|
||||
if (dnsAddress.isNull()) {
|
||||
return QByteArray();
|
||||
}
|
||||
|
||||
const qint64 bytesWritten = socket.writeDatagram(query, dnsAddress, port);
|
||||
if (bytesWritten != query.size()) {
|
||||
return QByteArray();
|
||||
}
|
||||
|
||||
QElapsedTimer timer;
|
||||
timer.start();
|
||||
|
||||
while (timer.elapsed() < timeoutMsecs) {
|
||||
if (socket.waitForReadyRead(qMax(1, timeoutMsecs - static_cast<int>(timer.elapsed())))) {
|
||||
while (socket.hasPendingDatagrams()) {
|
||||
QNetworkDatagram datagram = socket.receiveDatagram();
|
||||
if (datagram.isValid()) {
|
||||
return parseDnsTxtResponse(datagram.data());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return QByteArray();
|
||||
}
|
||||
|
||||
QByteArray sendOverTcp(const QByteArray &payload, const QString &queryName,
|
||||
const QString &dnsServer, quint16 port, int timeoutMsecs)
|
||||
{
|
||||
qDebug() << "[DNS-TCP] start: queryName=" << queryName << "server=" << dnsServer
|
||||
<< "port=" << port << "payloadBytes=" << payload.size();
|
||||
QTcpSocket socket;
|
||||
|
||||
const QHostAddress dnsAddress = resolveHostAddress(dnsServer);
|
||||
if (dnsAddress.isNull()) {
|
||||
qWarning() << "[DNS-TCP] failed to resolve" << dnsServer;
|
||||
return QByteArray();
|
||||
}
|
||||
|
||||
socket.connectToHost(dnsAddress, port);
|
||||
if (!socket.waitForConnected(timeoutMsecs)) {
|
||||
qWarning() << "[DNS-TCP] connect failed:" << socket.errorString();
|
||||
return QByteArray();
|
||||
}
|
||||
qDebug() << "[DNS-TCP] connected";
|
||||
|
||||
const quint16 transactionId = static_cast<quint16>(QDateTime::currentMSecsSinceEpoch() & 0xFFFF);
|
||||
const QByteArray query = buildDnsTxtQueryWithPayload(queryName, transactionId, payload);
|
||||
|
||||
if (query.isEmpty()) {
|
||||
qWarning() << "[DNS-TCP] failed to build DNS query";
|
||||
socket.close();
|
||||
return QByteArray();
|
||||
}
|
||||
qDebug() << "[DNS-TCP] built DNS query bytes=" << query.size() << "txid=" << transactionId;
|
||||
quint16 length = qToBigEndian<quint16>(static_cast<quint16>(query.size()));
|
||||
QByteArray tcpQuery;
|
||||
tcpQuery.append(reinterpret_cast<const char *>(&length), sizeof(quint16));
|
||||
tcpQuery.append(query);
|
||||
|
||||
const qint64 bytesWritten = socket.write(tcpQuery);
|
||||
qDebug() << "[DNS-TCP] wrote bytes=" << bytesWritten << "/ expected=" << tcpQuery.size();
|
||||
if (bytesWritten != tcpQuery.size() || !socket.waitForBytesWritten(timeoutMsecs)) {
|
||||
qWarning() << "[DNS-TCP] write failed:" << socket.errorString();
|
||||
socket.close();
|
||||
return QByteArray();
|
||||
}
|
||||
|
||||
QElapsedTimer timer;
|
||||
timer.start();
|
||||
|
||||
while (socket.bytesAvailable() < 2) {
|
||||
const int remaining = timeoutMsecs - timer.elapsed();
|
||||
if (remaining <= 0 || !socket.waitForReadyRead(remaining)) {
|
||||
qWarning() << "[DNS-TCP] timeout waiting for response length, socketState="
|
||||
<< socket.state() << "err=" << socket.errorString()
|
||||
<< "bytesAvailable=" << socket.bytesAvailable();
|
||||
socket.close();
|
||||
return QByteArray();
|
||||
}
|
||||
}
|
||||
|
||||
QByteArray lengthBytes = socket.read(2);
|
||||
if (lengthBytes.size() != 2) {
|
||||
qWarning() << "[DNS-TCP] could not read length prefix";
|
||||
socket.close();
|
||||
return QByteArray();
|
||||
}
|
||||
|
||||
const quint16 responseLength =
|
||||
qFromBigEndian<quint16>(*reinterpret_cast<const quint16 *>(lengthBytes.constData()));
|
||||
qDebug() << "[DNS-TCP] response length prefix=" << responseLength;
|
||||
|
||||
QByteArray response;
|
||||
while (response.size() < responseLength) {
|
||||
const int remaining = timeoutMsecs - timer.elapsed();
|
||||
if (remaining <= 0) {
|
||||
qWarning() << "[DNS-TCP] timeout reading body, got" << response.size() << "/" << responseLength;
|
||||
socket.close();
|
||||
return QByteArray();
|
||||
}
|
||||
|
||||
if (socket.bytesAvailable() > 0) {
|
||||
response.append(socket.read(responseLength - response.size()));
|
||||
} else if (!socket.waitForReadyRead(remaining)) {
|
||||
qWarning() << "[DNS-TCP] timeout in waitForReadyRead, got" << response.size() << "/" << responseLength;
|
||||
socket.close();
|
||||
return QByteArray();
|
||||
}
|
||||
}
|
||||
|
||||
qDebug() << "[DNS-TCP] full response read, bytes=" << response.size();
|
||||
socket.close();
|
||||
QByteArray parsed = parseDnsTxtResponse(response);
|
||||
qDebug() << "[DNS-TCP] parsed TXT payload bytes=" << parsed.size();
|
||||
return parsed;
|
||||
}
|
||||
|
||||
QByteArray sendOverTls(const QByteArray &payload, const QString &queryName,
|
||||
const QString &dnsServer, quint16 port, int timeoutMsecs)
|
||||
{
|
||||
QSslSocket socket;
|
||||
#ifdef AGW_INSECURE_SSL
|
||||
socket.setPeerVerifyMode(QSslSocket::VerifyNone);
|
||||
QObject::connect(&socket, QOverload<const QList<QSslError> &>::of(&QSslSocket::sslErrors),
|
||||
&socket, [&socket](const QList<QSslError> &errs) {
|
||||
qWarning() << "[DoT] sslErrors (ignored, AGW_INSECURE_SSL=1):" << errs;
|
||||
socket.ignoreSslErrors();
|
||||
});
|
||||
#else
|
||||
socket.setPeerVerifyMode(QSslSocket::VerifyPeer);
|
||||
#endif
|
||||
|
||||
const QHostAddress dnsAddress = resolveHostAddress(dnsServer);
|
||||
if (dnsAddress.isNull()) {
|
||||
qWarning() << "[DoT] failed to resolve" << dnsServer;
|
||||
return QByteArray();
|
||||
}
|
||||
|
||||
socket.connectToHostEncrypted(dnsServer, port);
|
||||
if (!socket.waitForEncrypted(timeoutMsecs)) {
|
||||
qWarning() << "[DoT] handshake failed:" << socket.errorString();
|
||||
return QByteArray();
|
||||
}
|
||||
|
||||
const quint16 transactionId = static_cast<quint16>(QDateTime::currentMSecsSinceEpoch() & 0xFFFF);
|
||||
const QByteArray query = buildDnsTxtQueryWithPayload(queryName, transactionId, payload);
|
||||
|
||||
if (query.isEmpty()) {
|
||||
socket.close();
|
||||
return QByteArray();
|
||||
}
|
||||
|
||||
quint16 length = qToBigEndian<quint16>(static_cast<quint16>(query.size()));
|
||||
QByteArray tcpQuery;
|
||||
tcpQuery.append(reinterpret_cast<const char *>(&length), sizeof(quint16));
|
||||
tcpQuery.append(query);
|
||||
|
||||
const qint64 bytesWritten = socket.write(tcpQuery);
|
||||
if (bytesWritten != tcpQuery.size() || !socket.waitForBytesWritten(timeoutMsecs)) {
|
||||
socket.close();
|
||||
return QByteArray();
|
||||
}
|
||||
|
||||
QElapsedTimer timer;
|
||||
timer.start();
|
||||
|
||||
while (socket.bytesAvailable() < 2) {
|
||||
const int remaining = timeoutMsecs - timer.elapsed();
|
||||
if (remaining <= 0 || !socket.waitForReadyRead(remaining)) {
|
||||
socket.close();
|
||||
return QByteArray();
|
||||
}
|
||||
}
|
||||
|
||||
QByteArray lengthBytes = socket.read(2);
|
||||
if (lengthBytes.size() != 2) {
|
||||
socket.close();
|
||||
return QByteArray();
|
||||
}
|
||||
|
||||
const quint16 responseLength =
|
||||
qFromBigEndian<quint16>(*reinterpret_cast<const quint16 *>(lengthBytes.constData()));
|
||||
|
||||
QByteArray response;
|
||||
while (response.size() < responseLength) {
|
||||
const int remaining = timeoutMsecs - timer.elapsed();
|
||||
if (remaining <= 0) {
|
||||
socket.close();
|
||||
return QByteArray();
|
||||
}
|
||||
|
||||
if (socket.bytesAvailable() > 0) {
|
||||
response.append(socket.read(responseLength - response.size()));
|
||||
} else if (!socket.waitForReadyRead(remaining)) {
|
||||
socket.close();
|
||||
return QByteArray();
|
||||
}
|
||||
}
|
||||
|
||||
socket.close();
|
||||
return parseDnsTxtResponse(response);
|
||||
}
|
||||
|
||||
QByteArray sendOverHttps(const QByteArray &payload, const QString &queryName,
|
||||
const QString &dnsServer, quint16 port, const QString &endpoint, int timeoutMsecs)
|
||||
{
|
||||
const quint16 transactionId = static_cast<quint16>(QDateTime::currentMSecsSinceEpoch() & 0xFFFF);
|
||||
const QByteArray dnsQuery = buildDnsTxtQueryWithPayload(queryName, transactionId, payload);
|
||||
|
||||
qDebug() << "[DoH] queryName=" << queryName << "payloadBytes=" << payload.size()
|
||||
<< "dnsQueryBytes=" << dnsQuery.size() << "txid=" << transactionId;
|
||||
|
||||
if (dnsQuery.isEmpty()) {
|
||||
qWarning() << "[DoH] failed to build DNS query (payload too big or queryName invalid)";
|
||||
return QByteArray();
|
||||
}
|
||||
|
||||
const QString scheme = (port == 443) ? QStringLiteral("https") : QStringLiteral("http");
|
||||
const QString url = QStringLiteral("%1://%2:%3%4").arg(scheme).arg(dnsServer).arg(port).arg(endpoint);
|
||||
|
||||
qDebug() << "[DoH] POST" << url << "timeoutMs=" << timeoutMsecs;
|
||||
|
||||
QNetworkRequest request((QUrl(url)));
|
||||
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/dns-message");
|
||||
request.setRawHeader("Accept", "application/dns-message");
|
||||
request.setTransferTimeout(timeoutMsecs);
|
||||
|
||||
QNetworkAccessManager manager;
|
||||
QNetworkReply *reply = manager.post(request, dnsQuery);
|
||||
|
||||
QObject::connect(reply, &QNetworkReply::sslErrors, reply,
|
||||
[reply](const QList<QSslError> &errs) {
|
||||
qWarning() << "[DoH] sslErrors:" << errs;
|
||||
#ifdef AGW_INSECURE_SSL
|
||||
qWarning() << "[DoH] AGW_INSECURE_SSL=1, ignoring SSL errors";
|
||||
reply->ignoreSslErrors();
|
||||
#endif
|
||||
});
|
||||
|
||||
QEventLoop loop;
|
||||
QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
|
||||
|
||||
QTimer::singleShot(timeoutMsecs, &loop, &QEventLoop::quit);
|
||||
loop.exec();
|
||||
|
||||
if (!reply->isFinished()) {
|
||||
qWarning() << "[DoH] timeout after" << timeoutMsecs << "ms, aborting";
|
||||
reply->abort();
|
||||
reply->deleteLater();
|
||||
return QByteArray();
|
||||
}
|
||||
|
||||
if (reply->error() != QNetworkReply::NoError) {
|
||||
qWarning() << "[DoH] reply error:" << reply->error() << reply->errorString()
|
||||
<< "httpStatus=" << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
|
||||
reply->deleteLater();
|
||||
return QByteArray();
|
||||
}
|
||||
|
||||
QByteArray response = reply->readAll();
|
||||
qDebug() << "[DoH] raw HTTP response bytes=" << response.size()
|
||||
<< "httpStatus=" << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
|
||||
reply->deleteLater();
|
||||
|
||||
if (response.isEmpty()) {
|
||||
qWarning() << "[DoH] empty HTTP response body";
|
||||
return QByteArray();
|
||||
}
|
||||
|
||||
QByteArray parsed = parseDnsTxtResponse(response);
|
||||
qDebug() << "[DoH] parsed TXT payload bytes=" << parsed.size();
|
||||
return parsed;
|
||||
}
|
||||
|
||||
QByteArray sendOverUdpChunked(const QByteArray &payload, const QString &queryName,
|
||||
const QString &dnsServer, quint16 port, int timeoutMsecs)
|
||||
{
|
||||
qDebug() << "[DNS-UDP] start: queryName=" << queryName << "server=" << dnsServer
|
||||
<< "port=" << port << "payloadBytes=" << payload.size() << "timeoutMs=" << timeoutMsecs;
|
||||
const QHostAddress dnsAddress = resolveHostAddress(dnsServer);
|
||||
if (dnsAddress.isNull()) {
|
||||
qWarning() << "[DNS-UDP] failed to resolve" << dnsServer;
|
||||
return QByteArray();
|
||||
}
|
||||
qDebug() << "[DNS-UDP] resolved to" << dnsAddress.toString();
|
||||
|
||||
constexpr int MAX_INITIAL_RETRIES = 3;
|
||||
constexpr int MAX_CHUNK_RETRIES = 2;
|
||||
constexpr int MAX_CONCURRENT_REQUESTS = 5;
|
||||
constexpr int BASE_TIMEOUT_MS = 2000;
|
||||
|
||||
auto sendUdpRequestWithTimeout = [&](const QByteArray &query, int requestTimeoutMs) -> QByteArray {
|
||||
QUdpSocket socket;
|
||||
const qint64 written = socket.writeDatagram(query, dnsAddress, port);
|
||||
if (written != query.size()) {
|
||||
return QByteArray();
|
||||
}
|
||||
|
||||
QElapsedTimer timer;
|
||||
timer.start();
|
||||
|
||||
while (timer.elapsed() < requestTimeoutMs) {
|
||||
if (socket.waitForReadyRead(qMax(1, requestTimeoutMs - static_cast<int>(timer.elapsed())))) {
|
||||
while (socket.hasPendingDatagrams()) {
|
||||
QNetworkDatagram datagram = socket.receiveDatagram();
|
||||
if (datagram.isValid()) {
|
||||
return datagram.data();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return QByteArray();
|
||||
};
|
||||
|
||||
auto sendWithRetry = [&](const QByteArray &query, int maxRetries) -> QByteArray {
|
||||
for (int attempt = 0; attempt < maxRetries; ++attempt) {
|
||||
const int timeout = BASE_TIMEOUT_MS * (attempt + 1);
|
||||
QByteArray response = sendUdpRequestWithTimeout(query, timeout);
|
||||
if (!response.isEmpty()) {
|
||||
return response;
|
||||
}
|
||||
|
||||
if (attempt < maxRetries - 1) {
|
||||
QThread::msleep(timeout / 2);
|
||||
}
|
||||
}
|
||||
return QByteArray();
|
||||
};
|
||||
|
||||
const quint16 transactionId = static_cast<quint16>(QDateTime::currentMSecsSinceEpoch() & 0xFFFF);
|
||||
const QByteArray initialQuery = buildDnsTxtQueryWithPayload(queryName, transactionId, payload);
|
||||
|
||||
qDebug() << "[DNS-UDP] initialQuery size=" << initialQuery.size() << "txid=" << transactionId;
|
||||
|
||||
if (initialQuery.isEmpty()) {
|
||||
qWarning() << "[DNS-UDP] failed to build initial query (payload too big or queryName invalid)";
|
||||
return QByteArray();
|
||||
}
|
||||
|
||||
const QByteArray firstResponse = sendWithRetry(initialQuery, MAX_INITIAL_RETRIES);
|
||||
qDebug() << "[DNS-UDP] first response size=" << firstResponse.size();
|
||||
|
||||
if (firstResponse.isEmpty()) {
|
||||
qWarning() << "[DNS-UDP] no response from server after" << MAX_INITIAL_RETRIES << "retries";
|
||||
return QByteArray();
|
||||
}
|
||||
|
||||
const ChunkMeta meta = parseChunkMeta(firstResponse);
|
||||
const QByteArray firstTxtData = parseDnsTxtResponse(firstResponse);
|
||||
|
||||
qDebug() << "[DNS-UDP] meta totalChunks=" << meta.totalChunks
|
||||
<< "chunkId=" << meta.chunkId << "firstTxtData size=" << firstTxtData.size();
|
||||
|
||||
if (firstTxtData.isEmpty()) {
|
||||
qWarning() << "[DNS-UDP] failed to parse TXT data from first response";
|
||||
return QByteArray();
|
||||
}
|
||||
|
||||
if (meta.totalChunks <= 1) {
|
||||
qDebug() << "[DNS-UDP] single chunk, returning" << firstTxtData.size() << "bytes";
|
||||
return firstTxtData;
|
||||
}
|
||||
|
||||
QMap<int, QByteArray> chunks;
|
||||
chunks[0] = firstTxtData;
|
||||
|
||||
auto requestChunksBatch = [&](const QList<int> &chunkIndices, int batchTimeout) {
|
||||
if (chunkIndices.isEmpty()) return;
|
||||
|
||||
QList<QSharedPointer<QUdpSocket>> sockets;
|
||||
QMap<QUdpSocket *, int> socketToIndex;
|
||||
|
||||
for (int idx : chunkIndices) {
|
||||
if (chunks.contains(idx)) continue;
|
||||
|
||||
const quint16 chunkTxId =
|
||||
static_cast<quint16>((QDateTime::currentMSecsSinceEpoch() + idx) & 0xFFFF);
|
||||
const QByteArray chunkQuery =
|
||||
buildDnsChunkRequest(queryName, chunkTxId, meta.chunkId, idx);
|
||||
|
||||
if (chunkQuery.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
auto socket = QSharedPointer<QUdpSocket>::create();
|
||||
socket->writeDatagram(chunkQuery, dnsAddress, port);
|
||||
socketToIndex[socket.data()] = idx;
|
||||
sockets.append(socket);
|
||||
}
|
||||
|
||||
if (sockets.isEmpty()) return;
|
||||
|
||||
QElapsedTimer deadline;
|
||||
deadline.start();
|
||||
int receivedCount = 0;
|
||||
const int expectedCount = sockets.size();
|
||||
|
||||
while (deadline.elapsed() < batchTimeout && receivedCount < expectedCount
|
||||
&& chunks.size() < meta.totalChunks) {
|
||||
for (auto &socket : sockets) {
|
||||
if (socket->waitForReadyRead(50)) {
|
||||
while (socket->hasPendingDatagrams()) {
|
||||
QNetworkDatagram datagram = socket->receiveDatagram();
|
||||
if (datagram.isValid()) {
|
||||
const QByteArray chunkTxtData = parseDnsTxtResponse(datagram.data());
|
||||
if (!chunkTxtData.isEmpty()) {
|
||||
const ChunkMeta chunkMeta = parseChunkMeta(datagram.data());
|
||||
const int idx = (chunkMeta.totalChunks > 0)
|
||||
? chunkMeta.chunkIndex
|
||||
: socketToIndex.value(socket.data(), -1);
|
||||
if (idx >= 0 && !chunks.contains(idx)) {
|
||||
chunks[idx] = chunkTxtData;
|
||||
receivedCount++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const int totalTimeout = qMax(timeoutMsecs / 2, 5000);
|
||||
const int batchTimeout = totalTimeout / (MAX_CHUNK_RETRIES + 1);
|
||||
|
||||
for (int retryRound = 0; retryRound <= MAX_CHUNK_RETRIES; ++retryRound) {
|
||||
QList<int> missing;
|
||||
for (int i = 1; i < meta.totalChunks; ++i) {
|
||||
if (!chunks.contains(i)) {
|
||||
missing.append(i);
|
||||
}
|
||||
}
|
||||
|
||||
if (missing.isEmpty()) {
|
||||
break;
|
||||
}
|
||||
|
||||
for (int batchStart = 0; batchStart < missing.size(); batchStart += MAX_CONCURRENT_REQUESTS) {
|
||||
const QList<int> batch = missing.mid(batchStart, MAX_CONCURRENT_REQUESTS);
|
||||
requestChunksBatch(batch, batchTimeout);
|
||||
}
|
||||
}
|
||||
|
||||
QList<int> finalMissing;
|
||||
for (int i = 0; i < meta.totalChunks; ++i) {
|
||||
if (!chunks.contains(i)) {
|
||||
finalMissing.append(i);
|
||||
}
|
||||
}
|
||||
|
||||
if (!finalMissing.isEmpty()) {
|
||||
return QByteArray();
|
||||
}
|
||||
|
||||
QByteArray combined;
|
||||
combined.reserve(meta.totalSize > 0 ? meta.totalSize : meta.totalChunks * 500);
|
||||
|
||||
for (int i = 0; i < meta.totalChunks; ++i) {
|
||||
combined.append(chunks[i]);
|
||||
}
|
||||
|
||||
return combined;
|
||||
}
|
||||
|
||||
} // namespace amnezia::transport::dns::DnsTunnel
|
||||
@@ -0,0 +1,35 @@
|
||||
#ifndef DNSTUNNEL_H
|
||||
#define DNSTUNNEL_H
|
||||
|
||||
#include <QByteArray>
|
||||
#include <QString>
|
||||
|
||||
#include "dnsResolver.h"
|
||||
|
||||
namespace amnezia::transport::dns::DnsTunnel
|
||||
{
|
||||
|
||||
QByteArray send(const QByteArray &payload,
|
||||
const QString &endpointName,
|
||||
const QString &baseDomain,
|
||||
const QString &dnsServer,
|
||||
DnsProtocol protocol,
|
||||
quint16 port,
|
||||
int timeoutMsecs = 30000,
|
||||
const QString &dohEndpoint = QStringLiteral("/dns-query"));
|
||||
|
||||
QByteArray sendOverUdp(const QByteArray &payload, const QString &queryName,
|
||||
const QString &dnsServer, quint16 port, int timeoutMsecs);
|
||||
QByteArray sendOverTcp(const QByteArray &payload, const QString &queryName,
|
||||
const QString &dnsServer, quint16 port, int timeoutMsecs);
|
||||
QByteArray sendOverTls(const QByteArray &payload, const QString &queryName,
|
||||
const QString &dnsServer, quint16 port, int timeoutMsecs);
|
||||
QByteArray sendOverHttps(const QByteArray &payload, const QString &queryName,
|
||||
const QString &dnsServer, quint16 port, const QString &endpoint, int timeoutMsecs);
|
||||
|
||||
QByteArray sendOverUdpChunked(const QByteArray &payload, const QString &queryName,
|
||||
const QString &dnsServer, quint16 port, int timeoutMsecs);
|
||||
|
||||
} // namespace amnezia::transport::dns::DnsTunnel
|
||||
|
||||
#endif // DNSTUNNEL_H
|
||||
@@ -0,0 +1,157 @@
|
||||
#include "dnsGatewayTransport.h"
|
||||
|
||||
#include <QDebug>
|
||||
#include <QHostAddress>
|
||||
#include <QHostInfo>
|
||||
#include <QSharedPointer>
|
||||
#include <QStringList>
|
||||
|
||||
#include "dns/dnsTunnel.h"
|
||||
#include "core/networkUtilities.h"
|
||||
|
||||
#ifdef AMNEZIA_DESKTOP
|
||||
#include "core/ipcclient.h"
|
||||
#endif
|
||||
|
||||
namespace amnezia::transport
|
||||
{
|
||||
|
||||
DnsGatewayTransport::DnsGatewayTransport(dns::DnsProtocol protocol,
|
||||
const QString &dnsServer,
|
||||
const QString &baseDomain,
|
||||
quint16 port,
|
||||
int timeoutMsecs,
|
||||
bool isStrictKillSwitchEnabled,
|
||||
const QString &dohEndpoint)
|
||||
: m_protocol(protocol),
|
||||
m_dnsServer(dnsServer),
|
||||
m_baseDomain(baseDomain),
|
||||
m_port(port),
|
||||
m_timeoutMsecs(timeoutMsecs),
|
||||
m_isStrictKillSwitchEnabled(isStrictKillSwitchEnabled),
|
||||
m_dohEndpoint(dohEndpoint)
|
||||
{
|
||||
}
|
||||
|
||||
QString DnsGatewayTransport::name() const
|
||||
{
|
||||
switch (m_protocol) {
|
||||
case dns::DnsProtocol::Udp: return QStringLiteral("DNS-UDP");
|
||||
case dns::DnsProtocol::Tcp: return QStringLiteral("DNS-TCP");
|
||||
case dns::DnsProtocol::Tls: return QStringLiteral("DNS-DoT");
|
||||
case dns::DnsProtocol::Https: return QStringLiteral("DNS-DoH");
|
||||
case dns::DnsProtocol::Quic: return QStringLiteral("DNS-DoQ");
|
||||
}
|
||||
return QStringLiteral("DNS");
|
||||
}
|
||||
|
||||
QString DnsGatewayTransport::resolveServerOnce()
|
||||
{
|
||||
if (m_resolved.load()) {
|
||||
return m_resolvedServerIp;
|
||||
}
|
||||
|
||||
QHostAddress addr(m_dnsServer);
|
||||
if (!addr.isNull()) {
|
||||
m_resolvedServerIp = m_dnsServer;
|
||||
} else {
|
||||
QHostInfo info = QHostInfo::fromName(m_dnsServer);
|
||||
if (!info.addresses().isEmpty()) {
|
||||
m_resolvedServerIp = info.addresses().first().toString();
|
||||
} else {
|
||||
m_resolvedServerIp = m_dnsServer;
|
||||
}
|
||||
}
|
||||
m_resolved.store(true);
|
||||
return m_resolvedServerIp;
|
||||
}
|
||||
|
||||
void DnsGatewayTransport::applyKillSwitchAllowlist(const QString &ip)
|
||||
{
|
||||
#ifdef AMNEZIA_DESKTOP
|
||||
if (!m_isStrictKillSwitchEnabled || ip.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
IpcClient::withInterface([&](QSharedPointer<IpcInterfaceReplica> iface) {
|
||||
QRemoteObjectPendingReply<bool> reply = iface->addKillSwitchAllowedRange(QStringList { ip });
|
||||
if (!reply.waitForFinished(1000) || !reply.returnValue()) {
|
||||
qWarning() << "DnsGatewayTransport: addKillSwitchAllowedRange failed for" << ip;
|
||||
}
|
||||
});
|
||||
#else
|
||||
Q_UNUSED(ip)
|
||||
#endif
|
||||
}
|
||||
|
||||
amnezia::ErrorCode DnsGatewayTransport::send(const QString &endpointTemplate,
|
||||
const QByteArray &requestBody,
|
||||
QByteArray &decryptedResponse,
|
||||
const DecryptionHook &decryptionHook)
|
||||
{
|
||||
QString endpointName = endpointTemplate;
|
||||
endpointName.remove("%1");
|
||||
if (endpointName.startsWith(QLatin1String("v1/"))) {
|
||||
endpointName = endpointName.mid(3);
|
||||
}
|
||||
while (endpointName.endsWith(QLatin1Char('/'))) {
|
||||
endpointName.chop(1);
|
||||
}
|
||||
while (endpointName.startsWith(QLatin1Char('/'))) {
|
||||
endpointName = endpointName.mid(1);
|
||||
}
|
||||
|
||||
qDebug() << "[DNS-Transport]" << name() << "send() endpointTemplate=" << endpointTemplate
|
||||
<< "endpointName=" << endpointName << "baseDomain=" << m_baseDomain
|
||||
<< "server=" << m_dnsServer << "port=" << m_port
|
||||
<< "dohPath=" << m_dohEndpoint << "timeoutMs=" << m_timeoutMsecs
|
||||
<< "requestBodyBytes=" << requestBody.size();
|
||||
|
||||
if (endpointName.isEmpty() || m_baseDomain.isEmpty() || m_dnsServer.isEmpty()) {
|
||||
qWarning() << "[DNS-Transport] ABORT: empty endpoint/baseDomain/server";
|
||||
return amnezia::ErrorCode::AmneziaServiceConnectionFailed;
|
||||
}
|
||||
|
||||
const bool needsHostname = (m_protocol == dns::DnsProtocol::Tls
|
||||
|| m_protocol == dns::DnsProtocol::Https);
|
||||
|
||||
QString serverIp = resolveServerOnce();
|
||||
QString serverForRequest = needsHostname ? m_dnsServer : serverIp;
|
||||
|
||||
qDebug() << "[DNS-Transport] resolved server IP=" << serverIp
|
||||
<< "serverForRequest=" << serverForRequest
|
||||
<< "needsHostname=" << needsHostname;
|
||||
|
||||
applyKillSwitchAllowlist(serverIp);
|
||||
|
||||
const QByteArray encrypted = dns::DnsTunnel::send(requestBody,
|
||||
endpointName,
|
||||
m_baseDomain,
|
||||
serverForRequest,
|
||||
m_protocol,
|
||||
m_port,
|
||||
m_timeoutMsecs,
|
||||
m_dohEndpoint);
|
||||
qDebug() << "[DNS-Transport] DnsTunnel::send returned" << encrypted.size() << "bytes";
|
||||
if (encrypted.isEmpty()) {
|
||||
qWarning() << "[DNS-Transport] DnsTunnel returned empty payload, treat as connection failure";
|
||||
return amnezia::ErrorCode::AmneziaServiceConnectionFailed;
|
||||
}
|
||||
|
||||
if (!decryptionHook) {
|
||||
qCritical() << "[DNS-Transport] decryption hook is null";
|
||||
return amnezia::ErrorCode::ApiConfigDecryptionError;
|
||||
}
|
||||
|
||||
DecryptionResult decrypted = decryptionHook(encrypted);
|
||||
if (!decrypted.isOk) {
|
||||
qCritical() << "[DNS-Transport] response decryption failed (encrypted bytes="
|
||||
<< encrypted.size() << ")";
|
||||
return amnezia::ErrorCode::ApiConfigDecryptionError;
|
||||
}
|
||||
|
||||
qDebug() << "[DNS-Transport] success, decrypted response bytes=" << decrypted.decrypted.size();
|
||||
decryptedResponse = decrypted.decrypted;
|
||||
return amnezia::ErrorCode::NoError;
|
||||
}
|
||||
|
||||
} // namespace amnezia::transport
|
||||
@@ -0,0 +1,49 @@
|
||||
#ifndef DNSGATEWAYTRANSPORT_H
|
||||
#define DNSGATEWAYTRANSPORT_H
|
||||
|
||||
#include <QString>
|
||||
#include <atomic>
|
||||
|
||||
#include "dns/dnsResolver.h"
|
||||
#include "igatewaytransport.h"
|
||||
|
||||
namespace amnezia::transport
|
||||
{
|
||||
|
||||
class DnsGatewayTransport : public IGatewayTransport
|
||||
{
|
||||
public:
|
||||
DnsGatewayTransport(dns::DnsProtocol protocol,
|
||||
const QString &dnsServer,
|
||||
const QString &baseDomain,
|
||||
quint16 port,
|
||||
int timeoutMsecs,
|
||||
bool isStrictKillSwitchEnabled,
|
||||
const QString &dohEndpoint = QStringLiteral("/dns-query"));
|
||||
|
||||
QString name() const override;
|
||||
|
||||
amnezia::ErrorCode send(const QString &endpointTemplate,
|
||||
const QByteArray &requestBody,
|
||||
QByteArray &decryptedResponse,
|
||||
const DecryptionHook &decryptionHook) override;
|
||||
|
||||
private:
|
||||
QString resolveServerOnce();
|
||||
void applyKillSwitchAllowlist(const QString &ip);
|
||||
|
||||
dns::DnsProtocol m_protocol;
|
||||
QString m_dnsServer;
|
||||
QString m_baseDomain;
|
||||
quint16 m_port;
|
||||
int m_timeoutMsecs;
|
||||
bool m_isStrictKillSwitchEnabled;
|
||||
QString m_dohEndpoint;
|
||||
|
||||
std::atomic_bool m_resolved{ false };
|
||||
QString m_resolvedServerIp;
|
||||
};
|
||||
|
||||
} // namespace amnezia::transport
|
||||
|
||||
#endif // DNSGATEWAYTRANSPORT_H
|
||||
@@ -0,0 +1,345 @@
|
||||
#include "httpGatewayTransport.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <random>
|
||||
|
||||
#include <QCryptographicHash>
|
||||
#include <QDebug>
|
||||
#include <QEventLoop>
|
||||
#include <QHostAddress>
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QMutexLocker>
|
||||
#include <QNetworkAccessManager>
|
||||
#include <QNetworkReply>
|
||||
#include <QNetworkRequest>
|
||||
#include <QSharedPointer>
|
||||
#include <QThread>
|
||||
#include <QUrl>
|
||||
#include <QUuid>
|
||||
|
||||
#include "QBlockCipher.h"
|
||||
|
||||
#include "amnezia_application.h"
|
||||
#include "core/api/apiUtils.h"
|
||||
#include "core/networkUtilities.h"
|
||||
#include "utilities.h"
|
||||
|
||||
#ifdef AMNEZIA_DESKTOP
|
||||
#include "core/ipcclient.h"
|
||||
#endif
|
||||
|
||||
#ifdef Q_OS_IOS
|
||||
#include "platforms/ios/ios_controller.h"
|
||||
#endif
|
||||
|
||||
namespace amnezia::transport
|
||||
{
|
||||
|
||||
QMutex HttpGatewayTransport::s_proxyMutex;
|
||||
QString HttpGatewayTransport::s_proxyUrl;
|
||||
|
||||
namespace
|
||||
{
|
||||
constexpr int kProxyHealthTimeoutMsecs = 1000;
|
||||
constexpr int httpStatusCodeNotFound = 404;
|
||||
constexpr int httpStatusCodeConflict = 409;
|
||||
constexpr int httpStatusCodeNotImplemented = 501;
|
||||
|
||||
constexpr QLatin1String errorResponsePattern1("No active configuration found for");
|
||||
constexpr QLatin1String errorResponsePattern2("No non-revoked public key found for");
|
||||
constexpr QLatin1String errorResponsePattern3("Account not found.");
|
||||
constexpr QLatin1String updateRequestResponsePattern("client version update is required");
|
||||
} // namespace
|
||||
|
||||
HttpGatewayTransport::HttpGatewayTransport(const QString &endpoint,
|
||||
bool isDevEnvironment,
|
||||
int requestTimeoutMsecs,
|
||||
bool isStrictKillSwitchEnabled)
|
||||
: m_endpoint(endpoint),
|
||||
m_isDevEnvironment(isDevEnvironment),
|
||||
m_requestTimeoutMsecs(requestTimeoutMsecs),
|
||||
m_isStrictKillSwitchEnabled(isStrictKillSwitchEnabled)
|
||||
{
|
||||
}
|
||||
|
||||
void HttpGatewayTransport::applyKillSwitchAllowlist(const QString &host)
|
||||
{
|
||||
#ifdef AMNEZIA_DESKTOP
|
||||
if (!m_isStrictKillSwitchEnabled || host.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
const QString ip = NetworkUtilities::getIPAddress(host);
|
||||
if (ip.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
IpcClient::withInterface([&](QSharedPointer<IpcInterfaceReplica> iface) {
|
||||
QRemoteObjectPendingReply<bool> reply = iface->addKillSwitchAllowedRange(QStringList { ip });
|
||||
if (!reply.waitForFinished(1000) || !reply.returnValue()) {
|
||||
qWarning() << "HttpGatewayTransport: addKillSwitchAllowedRange failed for" << ip;
|
||||
}
|
||||
});
|
||||
#else
|
||||
Q_UNUSED(host)
|
||||
#endif
|
||||
}
|
||||
|
||||
HttpGatewayTransport::ReplyOutcome HttpGatewayTransport::doPost(const QString &fullUrl, const QByteArray &requestBody)
|
||||
{
|
||||
ReplyOutcome outcome;
|
||||
|
||||
#ifdef Q_OS_IOS
|
||||
IosController::Instance()->requestInetAccess();
|
||||
QThread::msleep(10);
|
||||
#endif
|
||||
|
||||
QNetworkRequest request;
|
||||
request.setTransferTimeout(m_requestTimeoutMsecs);
|
||||
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
|
||||
request.setRawHeader("X-Client-Request-ID",
|
||||
QUuid::createUuid().toString(QUuid::WithoutBraces).toUtf8());
|
||||
request.setUrl(fullUrl);
|
||||
|
||||
applyKillSwitchAllowlist(QUrl(fullUrl).host());
|
||||
|
||||
QNetworkReply *reply = amnApp->networkManager()->post(request, requestBody);
|
||||
|
||||
QEventLoop wait;
|
||||
QObject::connect(reply, &QNetworkReply::finished, &wait, &QEventLoop::quit);
|
||||
QObject::connect(reply, &QNetworkReply::sslErrors, [&, reply](const QList<QSslError> &errors) {
|
||||
outcome.sslErrors = errors;
|
||||
#ifdef AGW_INSECURE_SSL
|
||||
qWarning() << "[HTTP] sslErrors (ignored, AGW_INSECURE_SSL=1):" << errors;
|
||||
reply->ignoreSslErrors();
|
||||
outcome.sslErrors.clear();
|
||||
#endif
|
||||
});
|
||||
wait.exec(QEventLoop::ExcludeUserInputEvents);
|
||||
|
||||
outcome.encryptedBody = reply->readAll();
|
||||
outcome.errorString = reply->errorString();
|
||||
outcome.networkError = reply->error();
|
||||
outcome.httpStatusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
|
||||
|
||||
reply->deleteLater();
|
||||
return outcome;
|
||||
}
|
||||
|
||||
bool HttpGatewayTransport::shouldBypass(const ReplyOutcome &outcome, const DecryptionResult &decrypted) const
|
||||
{
|
||||
if (!outcome.sslErrors.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!decrypted.isOk) {
|
||||
return true;
|
||||
}
|
||||
|
||||
int apiHttpStatus = -1;
|
||||
QJsonDocument jsonDoc = QJsonDocument::fromJson(decrypted.decrypted);
|
||||
if (jsonDoc.isObject()) {
|
||||
apiHttpStatus = jsonDoc.object().value("http_status").toInt(-1);
|
||||
}
|
||||
|
||||
if (outcome.networkError == QNetworkReply::NetworkError::OperationCanceledError
|
||||
|| outcome.networkError == QNetworkReply::NetworkError::TimeoutError) {
|
||||
return true;
|
||||
}
|
||||
if (decrypted.decrypted.contains("html")) {
|
||||
return true;
|
||||
}
|
||||
if (apiHttpStatus == httpStatusCodeNotFound) {
|
||||
if (decrypted.decrypted.contains(errorResponsePattern1)
|
||||
|| decrypted.decrypted.contains(errorResponsePattern2)
|
||||
|| decrypted.decrypted.contains(errorResponsePattern3)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (apiHttpStatus == httpStatusCodeNotImplemented) {
|
||||
if (decrypted.decrypted.contains(updateRequestResponsePattern)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (apiHttpStatus == httpStatusCodeConflict) {
|
||||
return false;
|
||||
}
|
||||
if (outcome.networkError != QNetworkReply::NetworkError::NoError) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
QStringList HttpGatewayTransport::fetchProxyUrls(const QByteArray &/*serviceHint*/)
|
||||
{
|
||||
QStringList baseUrls = m_isDevEnvironment
|
||||
? QString(DEV_S3_ENDPOINT).split(", ")
|
||||
: QString(PROD_S3_ENDPOINT).split(", ");
|
||||
|
||||
QByteArray rsaKey = m_isDevEnvironment ? DEV_AGW_PUBLIC_KEY : PROD_AGW_PUBLIC_KEY;
|
||||
|
||||
QStringList proxyStorageUrls;
|
||||
for (const auto &baseUrl : baseUrls) {
|
||||
proxyStorageUrls.push_back(baseUrl + "endpoints.json");
|
||||
}
|
||||
|
||||
QNetworkRequest request;
|
||||
request.setTransferTimeout(m_requestTimeoutMsecs);
|
||||
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
|
||||
|
||||
for (const auto &proxyStorageUrl : proxyStorageUrls) {
|
||||
request.setUrl(proxyStorageUrl);
|
||||
QNetworkReply *reply = amnApp->networkManager()->get(request);
|
||||
QEventLoop wait;
|
||||
QObject::connect(reply, &QNetworkReply::finished, &wait, &QEventLoop::quit);
|
||||
wait.exec(QEventLoop::ExcludeUserInputEvents);
|
||||
|
||||
if (reply->error() != QNetworkReply::NoError) {
|
||||
reply->deleteLater();
|
||||
continue;
|
||||
}
|
||||
|
||||
QByteArray encryptedResponseBody = reply->readAll();
|
||||
reply->deleteLater();
|
||||
|
||||
QByteArray responseBody;
|
||||
try {
|
||||
if (!m_isDevEnvironment) {
|
||||
QCryptographicHash hash(QCryptographicHash::Sha512);
|
||||
hash.addData(rsaKey);
|
||||
QByteArray hashResult = hash.result().toHex();
|
||||
|
||||
QByteArray key = QByteArray::fromHex(hashResult.left(64));
|
||||
QByteArray iv = QByteArray::fromHex(hashResult.mid(64, 32));
|
||||
|
||||
QSimpleCrypto::QBlockCipher blockCipher;
|
||||
responseBody = blockCipher.decryptAesBlockCipher(QByteArray::fromBase64(encryptedResponseBody), key, iv);
|
||||
} else {
|
||||
responseBody = encryptedResponseBody;
|
||||
}
|
||||
} catch (...) {
|
||||
Utils::logException();
|
||||
qCritical() << "HttpGatewayTransport: error decrypting proxy storage payload";
|
||||
continue;
|
||||
}
|
||||
|
||||
QJsonArray endpointsArray = QJsonDocument::fromJson(responseBody).array();
|
||||
QStringList endpoints;
|
||||
endpoints.reserve(endpointsArray.size());
|
||||
for (const QJsonValue &endpoint : endpointsArray) {
|
||||
endpoints.push_back(endpoint.toString());
|
||||
}
|
||||
return endpoints;
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
amnezia::ErrorCode HttpGatewayTransport::send(const QString &endpointTemplate,
|
||||
const QByteArray &requestBody,
|
||||
QByteArray &decryptedResponse,
|
||||
const DecryptionHook &decryptionHook)
|
||||
{
|
||||
auto buildOutcome = [&](const QString &gatewayBase) {
|
||||
return doPost(endpointTemplate.arg(gatewayBase), requestBody);
|
||||
};
|
||||
|
||||
auto tryDecrypt = [&](const QByteArray &encrypted) -> DecryptionResult {
|
||||
if (!decryptionHook) {
|
||||
DecryptionResult r;
|
||||
r.decrypted = encrypted;
|
||||
r.isOk = false;
|
||||
return r;
|
||||
}
|
||||
return decryptionHook(encrypted);
|
||||
};
|
||||
|
||||
QString cachedProxy;
|
||||
{
|
||||
QMutexLocker lock(&s_proxyMutex);
|
||||
cachedProxy = s_proxyUrl;
|
||||
}
|
||||
const QString primaryBase = cachedProxy.isEmpty() ? m_endpoint : cachedProxy;
|
||||
|
||||
ReplyOutcome outcome = buildOutcome(primaryBase);
|
||||
DecryptionResult decrypted = tryDecrypt(outcome.encryptedBody);
|
||||
|
||||
if (outcome.sslErrors.isEmpty() && shouldBypass(outcome, decrypted)) {
|
||||
QStringList proxyUrls = fetchProxyUrls(QByteArray());
|
||||
std::random_device randomDevice;
|
||||
std::mt19937 generator(randomDevice());
|
||||
std::shuffle(proxyUrls.begin(), proxyUrls.end(), generator);
|
||||
|
||||
bool bypassResolved = false;
|
||||
|
||||
if (cachedProxy.isEmpty()) {
|
||||
QNetworkRequest healthRequest;
|
||||
healthRequest.setTransferTimeout(kProxyHealthTimeoutMsecs);
|
||||
healthRequest.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
|
||||
|
||||
for (const QString &proxyUrl : std::as_const(proxyUrls)) {
|
||||
healthRequest.setUrl(proxyUrl + "lmbd-health");
|
||||
QNetworkReply *reply = amnApp->networkManager()->get(healthRequest);
|
||||
QEventLoop wait;
|
||||
QObject::connect(reply, &QNetworkReply::finished, &wait, &QEventLoop::quit);
|
||||
wait.exec(QEventLoop::ExcludeUserInputEvents);
|
||||
|
||||
const auto err = reply->error();
|
||||
reply->deleteLater();
|
||||
if (err == QNetworkReply::NoError) {
|
||||
QMutexLocker lock(&s_proxyMutex);
|
||||
s_proxyUrl = proxyUrl;
|
||||
cachedProxy = proxyUrl;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!cachedProxy.isEmpty()) {
|
||||
ReplyOutcome retry = buildOutcome(cachedProxy);
|
||||
DecryptionResult retryDecrypted = tryDecrypt(retry.encryptedBody);
|
||||
if (retry.sslErrors.isEmpty() && !shouldBypass(retry, retryDecrypted)) {
|
||||
outcome = retry;
|
||||
decrypted = retryDecrypted;
|
||||
bypassResolved = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!bypassResolved) {
|
||||
for (const QString &proxyUrl : std::as_const(proxyUrls)) {
|
||||
ReplyOutcome retry = buildOutcome(proxyUrl);
|
||||
DecryptionResult retryDecrypted = tryDecrypt(retry.encryptedBody);
|
||||
if (retry.sslErrors.isEmpty() && !shouldBypass(retry, retryDecrypted)) {
|
||||
{
|
||||
QMutexLocker lock(&s_proxyMutex);
|
||||
s_proxyUrl = proxyUrl;
|
||||
}
|
||||
outcome = retry;
|
||||
decrypted = retryDecrypted;
|
||||
bypassResolved = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
auto errorCode = apiUtils::checkNetworkReplyErrors(outcome.sslErrors,
|
||||
outcome.errorString,
|
||||
outcome.networkError,
|
||||
outcome.httpStatusCode,
|
||||
decrypted.decrypted);
|
||||
if (errorCode != amnezia::ErrorCode::NoError) {
|
||||
return errorCode;
|
||||
}
|
||||
|
||||
if (!decrypted.isOk) {
|
||||
qCritical() << "HttpGatewayTransport: response decryption failed";
|
||||
return amnezia::ErrorCode::ApiConfigDecryptionError;
|
||||
}
|
||||
|
||||
decryptedResponse = decrypted.decrypted;
|
||||
return amnezia::ErrorCode::NoError;
|
||||
}
|
||||
|
||||
} // namespace amnezia::transport
|
||||
@@ -0,0 +1,58 @@
|
||||
#ifndef HTTPGATEWAYTRANSPORT_H
|
||||
#define HTTPGATEWAYTRANSPORT_H
|
||||
|
||||
#include <QByteArray>
|
||||
#include <QList>
|
||||
#include <QMutex>
|
||||
#include <QNetworkReply>
|
||||
#include <QSslError>
|
||||
#include <QString>
|
||||
#include <QStringList>
|
||||
|
||||
#include "igatewaytransport.h"
|
||||
|
||||
namespace amnezia::transport
|
||||
{
|
||||
|
||||
class HttpGatewayTransport : public IGatewayTransport
|
||||
{
|
||||
public:
|
||||
HttpGatewayTransport(const QString &endpoint,
|
||||
bool isDevEnvironment,
|
||||
int requestTimeoutMsecs,
|
||||
bool isStrictKillSwitchEnabled);
|
||||
|
||||
QString name() const override { return QStringLiteral("HTTP"); }
|
||||
|
||||
amnezia::ErrorCode send(const QString &endpointTemplate,
|
||||
const QByteArray &requestBody,
|
||||
QByteArray &decryptedResponse,
|
||||
const DecryptionHook &decryptionHook) override;
|
||||
|
||||
private:
|
||||
struct ReplyOutcome
|
||||
{
|
||||
QByteArray encryptedBody;
|
||||
QList<QSslError> sslErrors;
|
||||
QNetworkReply::NetworkError networkError = QNetworkReply::NoError;
|
||||
QString errorString;
|
||||
int httpStatusCode = 0;
|
||||
};
|
||||
|
||||
ReplyOutcome doPost(const QString &fullUrl, const QByteArray &requestBody);
|
||||
void applyKillSwitchAllowlist(const QString &host);
|
||||
QStringList fetchProxyUrls(const QByteArray &serviceHint);
|
||||
bool shouldBypass(const ReplyOutcome &outcome, const DecryptionResult &decrypted) const;
|
||||
|
||||
QString m_endpoint;
|
||||
bool m_isDevEnvironment;
|
||||
int m_requestTimeoutMsecs;
|
||||
bool m_isStrictKillSwitchEnabled;
|
||||
|
||||
static QMutex s_proxyMutex;
|
||||
static QString s_proxyUrl;
|
||||
};
|
||||
|
||||
} // namespace amnezia::transport
|
||||
|
||||
#endif // HTTPGATEWAYTRANSPORT_H
|
||||
@@ -0,0 +1,36 @@
|
||||
#ifndef IGATEWAYTRANSPORT_H
|
||||
#define IGATEWAYTRANSPORT_H
|
||||
|
||||
#include <QByteArray>
|
||||
#include <QString>
|
||||
#include <functional>
|
||||
|
||||
#include "core/defs.h"
|
||||
|
||||
namespace amnezia::transport
|
||||
{
|
||||
|
||||
struct DecryptionResult
|
||||
{
|
||||
QByteArray decrypted;
|
||||
bool isOk = false;
|
||||
};
|
||||
|
||||
using DecryptionHook = std::function<DecryptionResult(const QByteArray &encrypted)>;
|
||||
|
||||
class IGatewayTransport
|
||||
{
|
||||
public:
|
||||
virtual ~IGatewayTransport() = default;
|
||||
|
||||
virtual QString name() const = 0;
|
||||
|
||||
virtual amnezia::ErrorCode send(const QString &endpointTemplate,
|
||||
const QByteArray &requestBody,
|
||||
QByteArray &decryptedResponse,
|
||||
const DecryptionHook &decryptionHook) = 0;
|
||||
};
|
||||
|
||||
} // namespace amnezia::transport
|
||||
|
||||
#endif // IGATEWAYTRANSPORT_H
|
||||
@@ -1,124 +0,0 @@
|
||||
get_filename_component(DIR_NAME ${CMAKE_CURRENT_SOURCE_DIR} NAME)
|
||||
message("Configuring " ${DIR_NAME})
|
||||
|
||||
set(webview_URI AmneziaWebView)
|
||||
|
||||
find_package(QT NAMES Qt6 REQUIRED COMPONENTS Quick)
|
||||
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Quick)
|
||||
|
||||
# Widgets and WebEngineWidgets are only available on desktop platforms
|
||||
if(WIN32 OR (APPLE AND NOT IOS) OR (LINUX AND NOT ANDROID))
|
||||
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Widgets)
|
||||
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS WebEngineWidgets)
|
||||
endif()
|
||||
|
||||
set(CMAKE_AUTOMOC ON)
|
||||
set(CMAKE_INCLUDE_CURRENT_DIR ON)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 20)
|
||||
|
||||
set(PLUGIN_CLASS_NAME WebViewPlugin)
|
||||
add_definitions(-DURI=${webview_URI})
|
||||
|
||||
include_directories(${CMAKE_CURRENT_SOURCE_DIR})
|
||||
|
||||
set(webview_HEADERS
|
||||
amneziawebview.h
|
||||
amneziawebview_p.h
|
||||
websettings.h
|
||||
mimecache.h
|
||||
filehandler.h
|
||||
qrchandler.h
|
||||
jshandler.h
|
||||
plugin.h
|
||||
amneziawebhistory.h
|
||||
amneziawebhistory_p.h
|
||||
)
|
||||
|
||||
set(webview_SOURCES
|
||||
amneziawebview.cpp
|
||||
amneziawebview_p.cpp
|
||||
websettings.cpp
|
||||
mimecache.cpp
|
||||
qrchandler.cpp
|
||||
jshandler.cpp
|
||||
filehandler.cpp
|
||||
plugin.cpp
|
||||
amneziawebhistory.cpp
|
||||
)
|
||||
|
||||
if (CMAKE_CROSSCOMPILING AND ANDROID)
|
||||
|
||||
list(APPEND webview_SOURCES
|
||||
"${CMAKE_CURRENT_LIST_DIR}/jshandler_android.cpp"
|
||||
"${CMAKE_CURRENT_LIST_DIR}/qrchandler_android.cpp"
|
||||
"${CMAKE_CURRENT_LIST_DIR}/filehandler_android.cpp"
|
||||
"${CMAKE_CURRENT_LIST_DIR}/amneziawebview_android.cpp"
|
||||
)
|
||||
|
||||
endif ()
|
||||
|
||||
if (CMAKE_CROSSCOMPILING AND APPLE)
|
||||
|
||||
add_definitions(-DENABLE_WKWEBVIEW)
|
||||
list(APPEND webview_SOURCES
|
||||
"${CMAKE_CURRENT_LIST_DIR}/amneziawebview_ios.mm"
|
||||
"${CMAKE_CURRENT_LIST_DIR}/qrchandler_ios.mm"
|
||||
"${CMAKE_CURRENT_LIST_DIR}/jshandler_ios.mm"
|
||||
"${CMAKE_CURRENT_LIST_DIR}/filehandler_ios.mm"
|
||||
)
|
||||
|
||||
endif ()
|
||||
|
||||
if (NOT CMAKE_CROSSCOMPILING)
|
||||
# Require WebEngineWidgets for desktop platforms (QtWebKit is not available in Qt 6)
|
||||
if (Qt6WebEngineWidgets_FOUND)
|
||||
message(STATUS "Using Qt WebEngineWidgets for desktop webview")
|
||||
list(APPEND webview_HEADERS
|
||||
amneziawebview_webengine_p.h
|
||||
)
|
||||
list(APPEND webview_SOURCES
|
||||
amneziawebview_webengine.cpp
|
||||
)
|
||||
else ()
|
||||
message(FATAL_ERROR "Qt WebEngineWidgets is required for desktop builds. QtWebKit is not available in Qt 6. Please install Qt WebEngineWidgets module.")
|
||||
endif ()
|
||||
endif ()
|
||||
|
||||
add_library(webview STATIC ${webview_SOURCES} ${webview_HEADERS})
|
||||
|
||||
target_compile_definitions(webview PRIVATE
|
||||
QT_PLUGIN
|
||||
QT_STATICPLUGIN
|
||||
)
|
||||
|
||||
target_link_libraries(webview PUBLIC
|
||||
Qt${QT_VERSION_MAJOR}::Core
|
||||
Qt${QT_VERSION_MAJOR}::Quick
|
||||
)
|
||||
|
||||
# Widgets and WebEngineWidgets are only available on desktop platforms
|
||||
if(WIN32 OR (APPLE AND NOT IOS) OR (LINUX AND NOT ANDROID))
|
||||
if(TARGET Qt${QT_VERSION_MAJOR}::Widgets)
|
||||
target_link_libraries(webview PUBLIC Qt${QT_VERSION_MAJOR}::Widgets)
|
||||
endif()
|
||||
|
||||
if (Qt6WebEngineWidgets_FOUND)
|
||||
target_link_libraries(webview PRIVATE
|
||||
Qt${QT_VERSION_MAJOR}::WebEngineWidgets
|
||||
)
|
||||
endif ()
|
||||
endif()
|
||||
|
||||
# Link WebKit framework for iOS
|
||||
if (CMAKE_CROSSCOMPILING AND APPLE)
|
||||
find_library(FW_WEBKIT WebKit)
|
||||
if(FW_WEBKIT)
|
||||
target_link_libraries(webview PRIVATE ${FW_WEBKIT})
|
||||
endif()
|
||||
endif()
|
||||
|
||||
set_target_properties(webview PROPERTIES AUTOMOC_MOC_OPTIONS "-Muri=${webview_URI}")
|
||||
|
||||
#include(precompiled.headers)
|
||||
#add_precompiled_header(webview pch.h FORCEINCLUDE)
|
||||
@@ -1,434 +0,0 @@
|
||||
#include "amneziawebhistory.h"
|
||||
#include "amneziawebhistory_p.h"
|
||||
#include "amneziawebview.h"
|
||||
#include "amneziawebview_p.h"
|
||||
|
||||
#include <QSharedData>
|
||||
#include <QDebug>
|
||||
|
||||
|
||||
/*!
|
||||
Constructs a history item from \a other. The new item and \a other
|
||||
will share their data, and modifying either this item or \a other will
|
||||
modify both instances.
|
||||
*/
|
||||
AmneziaWebHistoryItem::AmneziaWebHistoryItem(const AmneziaWebHistoryItem &other)
|
||||
: d_ptr(other.d_ptr)
|
||||
{
|
||||
}
|
||||
|
||||
/*!
|
||||
Assigns the \a other history item to this. This item and \a other
|
||||
will share their data, and modifying either this item or \a other will
|
||||
modify both instances.
|
||||
*/
|
||||
AmneziaWebHistoryItem &AmneziaWebHistoryItem::operator=(const AmneziaWebHistoryItem &other)
|
||||
{
|
||||
d_ptr = other.d_ptr;
|
||||
return *this;
|
||||
}
|
||||
|
||||
/*!
|
||||
Destroys the history item.
|
||||
*/
|
||||
AmneziaWebHistoryItem::~AmneziaWebHistoryItem()
|
||||
{
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns the URL associated with the history item.
|
||||
|
||||
\sa originalUrl(), title(), lastVisited(), data(), mimeType()
|
||||
*/
|
||||
QUrl AmneziaWebHistoryItem::url() const
|
||||
{
|
||||
Q_D(const AmneziaWebHistoryItem);
|
||||
if (d)
|
||||
return d->url();
|
||||
return QUrl();
|
||||
}
|
||||
|
||||
|
||||
/*!
|
||||
Returns the title of the page associated with the history item.
|
||||
|
||||
\sa icon(), url(), lastVisited(), data(), mimeType()
|
||||
*/
|
||||
QString AmneziaWebHistoryItem::title() const
|
||||
{
|
||||
Q_D(const AmneziaWebHistoryItem);
|
||||
if (d)
|
||||
return d->title();
|
||||
return QString();
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns the icon associated with the history item.
|
||||
|
||||
\sa title(), url(), lastVisited(), data(), mimeType()
|
||||
*/
|
||||
QIcon AmneziaWebHistoryItem::icon() const
|
||||
{
|
||||
Q_D(const AmneziaWebHistoryItem);
|
||||
if (d)
|
||||
return d->icon();
|
||||
|
||||
return QIcon();
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns the data associated with the history item.
|
||||
|
||||
\sa icon(), title(), url(), lastVisited(), mimeType()
|
||||
*/
|
||||
QByteArray AmneziaWebHistoryItem::data() const
|
||||
{
|
||||
Q_D(const AmneziaWebHistoryItem);
|
||||
if(d) return d->data();
|
||||
return QByteArray();
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns the mimeType associated with the history item.
|
||||
|
||||
\sa icon(), title(), url(), lastVisited(), data()
|
||||
*/
|
||||
QString AmneziaWebHistoryItem::mimeType() const
|
||||
{
|
||||
Q_D(const AmneziaWebHistoryItem);
|
||||
if(d) return d->mimeType();
|
||||
return QString("text/html");
|
||||
}
|
||||
|
||||
/*!*
|
||||
\internal
|
||||
*/
|
||||
AmneziaWebHistoryItem::AmneziaWebHistoryItem(AmneziaWebHistoryItemPrivate *priv) : d_ptr(priv)
|
||||
{
|
||||
}
|
||||
|
||||
/*!
|
||||
\since 4.5
|
||||
Returns whether this is a valid history item.
|
||||
*/
|
||||
bool AmneziaWebHistoryItem::isValid() const
|
||||
{
|
||||
Q_D(const AmneziaWebHistoryItem);
|
||||
bool valid = (d);
|
||||
return valid;
|
||||
}
|
||||
|
||||
AmneziaWebHistory::AmneziaWebHistory(AmneziaWebView *parent) : QObject(parent)
|
||||
, d_ptr(new AmneziaWebHistoryPrivate())
|
||||
{
|
||||
Q_D(AmneziaWebHistory);
|
||||
d->q_ptr = this;
|
||||
}
|
||||
|
||||
AmneziaWebHistory::~AmneziaWebHistory()
|
||||
{
|
||||
clear();
|
||||
}
|
||||
|
||||
/*!
|
||||
Clears the history.
|
||||
|
||||
\sa count(), items()
|
||||
*/
|
||||
void AmneziaWebHistory::clear()
|
||||
{
|
||||
Q_D(AmneziaWebHistory);
|
||||
while (d->items.count()) {
|
||||
d->items.removeFirst();
|
||||
}
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns a list of all items currently in the history.
|
||||
|
||||
\sa count(), clear()
|
||||
*/
|
||||
QList<AmneziaWebHistoryItem> AmneziaWebHistory::items() const
|
||||
{
|
||||
Q_D(const AmneziaWebHistory);
|
||||
QList<AmneziaWebHistoryItem> ret;
|
||||
|
||||
for (int i = 0; i < d->items.size(); ++i) {
|
||||
AmneziaWebHistoryItem item(d->items[i]);
|
||||
ret.append(item);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns the list of items in the backwards history list.
|
||||
At most \a maxItems entries are returned.
|
||||
|
||||
\sa forwardItems()
|
||||
*/
|
||||
QList<AmneziaWebHistoryItem> AmneziaWebHistory::backItems(int maxItems) const
|
||||
{
|
||||
Q_D(const AmneziaWebHistory);
|
||||
|
||||
int count = d->currentIndex;
|
||||
if (maxItems >= 0) {
|
||||
count = qMin(count, maxItems);
|
||||
}
|
||||
|
||||
QList<AmneziaWebHistoryItem> ret;
|
||||
for (int i = (d->currentIndex - count); i < d->currentIndex; i++) {
|
||||
ret.append(d->items[i]);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns the list of items in the forward history list.
|
||||
At most \a maxItems entries are returned.
|
||||
|
||||
\sa backItems()
|
||||
*/
|
||||
QList<AmneziaWebHistoryItem> AmneziaWebHistory::forwardItems(int maxItems) const
|
||||
{
|
||||
Q_D(const AmneziaWebHistory);
|
||||
|
||||
int count = d->items.count() - d->currentIndex - 1;
|
||||
if (maxItems >= 0) {
|
||||
count = qMin(count, maxItems);
|
||||
}
|
||||
|
||||
QList<AmneziaWebHistoryItem> ret;
|
||||
for (int i = (d->currentIndex + 1); i <= d->currentIndex + count; i++) {
|
||||
ret.append(d->items[i]);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
|
||||
/*!
|
||||
Returns true if there is an item preceding the current item in the history;
|
||||
otherwise returns false.
|
||||
|
||||
\sa canGoForward()
|
||||
*/
|
||||
bool AmneziaWebHistory::canGoBack() const
|
||||
{
|
||||
const AmneziaWebHistoryItem current = currentItem();
|
||||
bool can = (current.isValid() && current.d_ptr->backItem() != nullptr);
|
||||
return can;
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns true if we have an item to go forward to; otherwise returns false.
|
||||
|
||||
\sa canGoBack()
|
||||
*/
|
||||
bool AmneziaWebHistory::canGoForward() const
|
||||
{
|
||||
const AmneziaWebHistoryItem current = currentItem();
|
||||
bool can = (current.isValid() && current.d_ptr->forwardItem() != nullptr);
|
||||
return can;
|
||||
}
|
||||
|
||||
/*!
|
||||
Set the current item to be the previous item in the history and goes to the
|
||||
corresponding page; i.e., goes back one history item.
|
||||
|
||||
\sa forward(), goToItem()
|
||||
*/
|
||||
void AmneziaWebHistory::back()
|
||||
{
|
||||
Q_D(AmneziaWebHistory);
|
||||
if(!canGoBack()) return;
|
||||
AmneziaWebView *view = qobject_cast<AmneziaWebView*>(parent());
|
||||
AmneziaWebHistoryItem item = backItem();
|
||||
|
||||
d->currentIndex--;
|
||||
if (view) {
|
||||
if (item.data().length() > 0) {
|
||||
view->setContent(item.data(), item.mimeType(), item.url());
|
||||
}
|
||||
else {
|
||||
|
||||
view->setUrl(item.url());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*!
|
||||
Sets the current item to be the next item in the history and goes to the
|
||||
corresponding page; i.e., goes forward one history item.
|
||||
|
||||
\sa back(), goToItem()
|
||||
*/
|
||||
void AmneziaWebHistory::forward()
|
||||
{
|
||||
Q_D(AmneziaWebHistory);
|
||||
if(!canGoForward()) return;
|
||||
AmneziaWebView *view = qobject_cast<AmneziaWebView*>(parent());
|
||||
AmneziaWebHistoryItem item = backItem();
|
||||
|
||||
d->currentIndex++;
|
||||
if (view) {
|
||||
if (item.data().length() > 0) {
|
||||
view->setContent(item.data(), item.mimeType(), item.url());
|
||||
}
|
||||
else {
|
||||
view->setUrl(item.url());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*!
|
||||
Sets the current item to be the specified \a item in the history and goes to the page.
|
||||
|
||||
\sa back(), forward()
|
||||
*/
|
||||
void AmneziaWebHistory::goToItem(const AmneziaWebHistoryItem &item)
|
||||
{
|
||||
Q_D(AmneziaWebHistory);
|
||||
if(!item.isValid()) return;
|
||||
AmneziaWebView *view = qobject_cast<AmneziaWebView*>(parent());
|
||||
if (!view) return; //There is no view to go.
|
||||
if (item.url().isEmpty()) return; //
|
||||
|
||||
int index = -1;
|
||||
for(int i= 0; i < d->items.count(); ++i) {
|
||||
if(d->items[i].d_ptr.data() == item.d_ptr.data()) {
|
||||
index = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (index >= 0) {
|
||||
|
||||
d->currentIndex = index;
|
||||
if (item.data().length() > 0) {
|
||||
view->setContent(item.data(), item.mimeType(), item.url());
|
||||
}
|
||||
else {
|
||||
view->setUrl(item.url());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns the current item in the history.
|
||||
*/
|
||||
AmneziaWebHistoryItem AmneziaWebHistory::currentItem() const
|
||||
{
|
||||
Q_D(const AmneziaWebHistory);
|
||||
|
||||
if ((d->currentIndex >= 0) && (d->currentIndex < d->items.count())) {
|
||||
return AmneziaWebHistoryItem(d->items.at(d->currentIndex));
|
||||
}
|
||||
return AmneziaWebHistoryItem(nullptr);
|
||||
}
|
||||
|
||||
void AmneziaWebHistory::append(const QUrl& url, const QByteArray& data, const QString& mimeType)
|
||||
{
|
||||
Q_D(AmneziaWebHistory);
|
||||
|
||||
const AmneziaWebHistoryItem current = currentItem();
|
||||
// Check if url is same as current, and do not add it second time.
|
||||
if (current.url() == url) return;
|
||||
|
||||
AmneziaWebHistoryItemPrivate *priv = new AmneziaWebHistoryItemPrivate();
|
||||
if(current.isValid()) {
|
||||
current.d_ptr->_forwardItem = priv;
|
||||
priv->_backItem = current.d_ptr.data();
|
||||
}
|
||||
priv->_data = data;
|
||||
priv->_url = url;
|
||||
priv->_mimeType = mimeType;
|
||||
|
||||
//Remove last items till current
|
||||
while (d->items.count() > (d->currentIndex + 1)) {
|
||||
d->items.removeLast();
|
||||
}
|
||||
|
||||
//No more then maximum
|
||||
while (d->items.count() >= d->maximumCount) {
|
||||
d->items.removeFirst();
|
||||
}
|
||||
|
||||
d->items.append(AmneziaWebHistoryItem(priv));
|
||||
d->currentIndex = (d->items.count() - 1);
|
||||
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns the item before the current item in the history.
|
||||
*/
|
||||
AmneziaWebHistoryItem AmneziaWebHistory::backItem() const
|
||||
{
|
||||
AmneziaWebHistoryItem current = currentItem();
|
||||
return AmneziaWebHistoryItem(current.d_ptr->backItem());
|
||||
}
|
||||
|
||||
|
||||
/*!
|
||||
Returns the item after the current item in the history.
|
||||
*/
|
||||
AmneziaWebHistoryItem AmneziaWebHistory::forwardItem() const
|
||||
{
|
||||
AmneziaWebHistoryItem current = currentItem();
|
||||
return AmneziaWebHistoryItem(current.d_ptr->forwardItem());
|
||||
}
|
||||
|
||||
/*!
|
||||
\since 4.5
|
||||
Returns the index of the current item in history.
|
||||
*/
|
||||
int AmneziaWebHistory::currentItemIndex() const
|
||||
{
|
||||
Q_D(const AmneziaWebHistory);
|
||||
return d->currentIndex;
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns the item at index \a i in the history.
|
||||
*/
|
||||
AmneziaWebHistoryItem AmneziaWebHistory::itemAt(int i) const
|
||||
{
|
||||
Q_D(const AmneziaWebHistory);
|
||||
int index = (i < 0) ? 0 : i;
|
||||
index = (index >= count()) ? (count() -1) : index;
|
||||
if (index >= 0) {
|
||||
return AmneziaWebHistoryItem(d->items.at(index));
|
||||
}
|
||||
return AmneziaWebHistoryItem(nullptr);
|
||||
}
|
||||
|
||||
/*!
|
||||
Returns the total number of items in the history.
|
||||
*/
|
||||
int AmneziaWebHistory::count() const
|
||||
{
|
||||
Q_D(const AmneziaWebHistory);
|
||||
return d->items.count();
|
||||
}
|
||||
|
||||
/*!
|
||||
\since 4.5
|
||||
Returns the maximum number of items in the history.
|
||||
|
||||
\sa setMaximumItemCount()
|
||||
*/
|
||||
int AmneziaWebHistory::maximumItemCount() const
|
||||
{
|
||||
Q_D(const AmneziaWebHistory);
|
||||
return d->maximumCount;
|
||||
}
|
||||
|
||||
/*!
|
||||
\since 4.5
|
||||
Sets the maximum number of items in the history to \a count.
|
||||
|
||||
\sa maximumItemCount()
|
||||
*/
|
||||
void AmneziaWebHistory::setMaximumItemCount(int count)
|
||||
{
|
||||
Q_D(AmneziaWebHistory);
|
||||
d->maximumCount = count;
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
#ifndef WEBHISTORY_H
|
||||
#define WEBHISTORY_H
|
||||
|
||||
#include <QObject>
|
||||
#include <QIcon>
|
||||
|
||||
class AmneziaWebViewPrivate;
|
||||
class AmneziaWebView;
|
||||
|
||||
class AmneziaWebHistory;
|
||||
class AmneziaWebHistoryItemPrivate;
|
||||
class AmneziaWebHistoryItem
|
||||
{
|
||||
Q_DECLARE_PRIVATE(AmneziaWebHistoryItem)
|
||||
public:
|
||||
|
||||
AmneziaWebHistoryItem(const AmneziaWebHistoryItem &other);
|
||||
AmneziaWebHistoryItem &operator=(const AmneziaWebHistoryItem &other);
|
||||
~AmneziaWebHistoryItem();
|
||||
|
||||
QUrl url() const;
|
||||
QString title() const;
|
||||
QIcon icon() const;
|
||||
|
||||
QByteArray data() const;
|
||||
QString mimeType() const;
|
||||
|
||||
bool isValid() const;
|
||||
|
||||
private:
|
||||
explicit AmneziaWebHistoryItem(AmneziaWebHistoryItemPrivate *priv);
|
||||
friend class AmneziaWebHistory;
|
||||
friend class AmneziaWebViewPrivate;
|
||||
QExplicitlySharedDataPointer<AmneziaWebHistoryItemPrivate> d_ptr;
|
||||
};
|
||||
|
||||
class AmneziaWebHistoryPrivate;
|
||||
class AmneziaWebHistory : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
Q_DECLARE_PRIVATE(AmneziaWebHistory)
|
||||
|
||||
public:
|
||||
virtual ~AmneziaWebHistory();
|
||||
|
||||
void append(const QUrl& url, const QByteArray& data = QByteArray(), const QString& mimeType = QString("text/html"));
|
||||
void clear();
|
||||
|
||||
QList<AmneziaWebHistoryItem> items() const;
|
||||
QList<AmneziaWebHistoryItem> backItems(int maxItems) const;
|
||||
QList<AmneziaWebHistoryItem> forwardItems(int maxItems) const;
|
||||
|
||||
bool canGoBack() const;
|
||||
bool canGoForward() const;
|
||||
|
||||
void back();
|
||||
void forward();
|
||||
void goToItem(const AmneziaWebHistoryItem &item);
|
||||
|
||||
AmneziaWebHistoryItem backItem() const;
|
||||
AmneziaWebHistoryItem currentItem() const;
|
||||
AmneziaWebHistoryItem forwardItem() const;
|
||||
AmneziaWebHistoryItem itemAt(int i) const;
|
||||
int currentItemIndex() const;
|
||||
|
||||
int count() const;
|
||||
int maximumItemCount() const;
|
||||
void setMaximumItemCount(int count);
|
||||
|
||||
private:
|
||||
|
||||
friend class AmneziaWebViewPrivate;
|
||||
explicit AmneziaWebHistory(AmneziaWebView *parent);
|
||||
Q_DISABLE_COPY(AmneziaWebHistory)
|
||||
QScopedPointer<AmneziaWebHistoryPrivate> d_ptr;
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -1,72 +0,0 @@
|
||||
#ifndef WEBHISTORY_P_H
|
||||
#define WEBHISTORY_P_H
|
||||
|
||||
#include <QUrl>
|
||||
|
||||
#include "amneziawebhistory.h"
|
||||
|
||||
class AmneziaWebHistoryItemPrivate;
|
||||
class AmneziaWebHistoryItem;
|
||||
|
||||
class AmneziaWebHistoryPrivate
|
||||
{
|
||||
Q_DECLARE_PUBLIC(AmneziaWebHistory)
|
||||
public:
|
||||
|
||||
static AmneziaWebHistoryPrivate *get(AmneziaWebHistory *q)
|
||||
{
|
||||
if (!q) { return nullptr; }
|
||||
return q->d_func();
|
||||
}
|
||||
|
||||
AmneziaWebHistoryPrivate(): currentIndex(-1), maximumCount(10), q_ptr(nullptr) { }
|
||||
~AmneziaWebHistoryPrivate() = default;
|
||||
|
||||
|
||||
private:
|
||||
friend class AmneziaWebHistoryItemPrivate;
|
||||
int currentIndex;
|
||||
int maximumCount;
|
||||
QList<AmneziaWebHistoryItem> items;
|
||||
AmneziaWebHistory *q_ptr;
|
||||
};
|
||||
|
||||
class AmneziaWebHistoryItemPrivate : public QSharedData
|
||||
{
|
||||
public:
|
||||
|
||||
static QExplicitlySharedDataPointer<AmneziaWebHistoryItemPrivate> get(AmneziaWebHistoryItem *q)
|
||||
{
|
||||
return q->d_ptr;
|
||||
}
|
||||
|
||||
~AmneziaWebHistoryItemPrivate()
|
||||
{
|
||||
}
|
||||
|
||||
QUrl url() const { return _url; }
|
||||
QString title() const { return _title; }
|
||||
QIcon icon() const {return _icon;}
|
||||
QByteArray data() const {return _data;}
|
||||
QString mimeType() const {return _mimeType;}
|
||||
|
||||
// Every item knows its back and forward items
|
||||
AmneziaWebHistoryItemPrivate *backItem() {return _backItem; }
|
||||
AmneziaWebHistoryItemPrivate *forwardItem() {return _forwardItem; }
|
||||
|
||||
private:
|
||||
friend class AmneziaWebHistory;
|
||||
AmneziaWebHistoryItemPrivate() = default;
|
||||
|
||||
AmneziaWebHistoryItemPrivate *_backItem = nullptr;
|
||||
AmneziaWebHistoryItemPrivate *_forwardItem = nullptr;
|
||||
QIcon _icon;
|
||||
QString _title;
|
||||
QUrl _url;
|
||||
QString _html;
|
||||
QByteArray _data;
|
||||
QString _mimeType;
|
||||
};
|
||||
|
||||
|
||||
#endif
|
||||
@@ -1,751 +0,0 @@
|
||||
#include <QDebug>
|
||||
#include <QEvent>
|
||||
#include <QFile>
|
||||
#include <QThread>
|
||||
#include <QMetaObject>
|
||||
#include <QQmlContext>
|
||||
#include <QQmlEngine>
|
||||
#include <QKeyEvent>
|
||||
#include <QMouseEvent>
|
||||
#include <QPen>
|
||||
#include <QList>
|
||||
#include <QQuickWindow>
|
||||
#include <QTimer>
|
||||
|
||||
#include <QPainter>
|
||||
|
||||
#if defined(Q_OS_ANDROID) || defined(Q_OS_IOS)
|
||||
#include <QGuiApplication>
|
||||
#define qApp qGuiApp
|
||||
#else
|
||||
#include <QApplication>
|
||||
#endif
|
||||
|
||||
#include "amneziawebview.h"
|
||||
#include "amneziawebview_p.h"
|
||||
|
||||
QUrl defaultBaseUrl()
|
||||
{
|
||||
#if defined(Q_OS_MACOS) || defined(Q_OS_WINDOWS)
|
||||
return QUrl(QLatin1String("local:///"));
|
||||
#else
|
||||
return QUrl(QLatin1String("file:///"));
|
||||
#endif
|
||||
}
|
||||
|
||||
QT_BEGIN_NAMESPACE
|
||||
|
||||
AmneziaWebView::AmneziaWebView(QQuickItem *parent) : QQuickPaintedItem(parent),
|
||||
d_ptr(AmneziaWebViewPrivate::create(this))
|
||||
{
|
||||
Q_D(AmneziaWebView);
|
||||
d->q_ptr = this;
|
||||
d->init();
|
||||
init();
|
||||
}
|
||||
|
||||
AmneziaWebView::~AmneziaWebView()
|
||||
{
|
||||
disconnect(this);
|
||||
}
|
||||
|
||||
void AmneziaWebView::init()
|
||||
{
|
||||
Q_D(AmneziaWebView);
|
||||
setAcceptedMouseButtons(Qt::LeftButton);
|
||||
setFlag(QQuickItem::ItemHasContents, true);
|
||||
setOpaquePainting(true);
|
||||
|
||||
setClip(true);
|
||||
|
||||
connect(this, SIGNAL(windowChanged(QQuickWindow*)), this, SLOT(windowWasChanged(QQuickWindow*)));
|
||||
connect(this, SIGNAL(parentChanged(QQuickItem*)), this, SLOT(parentWasChanged()));
|
||||
connect(this, SIGNAL(fillColorChanged()), this,SLOT(fillColorWasChanged()));
|
||||
|
||||
connect(d, SIGNAL(titleChanged(QString)), this, SIGNAL(titleChanged(QString)));
|
||||
connect(d, SIGNAL(loadStarted()), this, SLOT(doLoadStarted()));
|
||||
connect(d, SIGNAL(loadFinished(bool)), this, SLOT(doLoadFinished(bool)));
|
||||
}
|
||||
|
||||
void AmneziaWebView::componentComplete()
|
||||
{
|
||||
Q_D(AmneziaWebView);
|
||||
QQuickItem::componentComplete();
|
||||
|
||||
// Update geometry after component is complete
|
||||
if (window()) {
|
||||
QMetaObject::invokeMethod(this, "updateGeometry", Qt::QueuedConnection);
|
||||
}
|
||||
|
||||
switch (d->pending) {
|
||||
case AmneziaWebViewPrivate::PendingUrl:
|
||||
// Make WebView visible before loading
|
||||
if (isVisible() && !d->visible) {
|
||||
d->show();
|
||||
}
|
||||
setUrl(d->pendingUrl);
|
||||
break;
|
||||
case AmneziaWebViewPrivate::PendingHtml:
|
||||
if (isVisible() && !d->visible) {
|
||||
d->show();
|
||||
}
|
||||
setHtml(d->pendingString, d->pendingUrl);
|
||||
break;
|
||||
case AmneziaWebViewPrivate::PendingContent:
|
||||
if (isVisible() && !d->visible) {
|
||||
d->show();
|
||||
}
|
||||
setContent(d->pendingData, d->pendingString, d->pendingUrl);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
AmneziaWebView::Status AmneziaWebView::status() const
|
||||
{
|
||||
Q_D(const AmneziaWebView);
|
||||
return d->status;
|
||||
}
|
||||
|
||||
/*!
|
||||
\qmlproperty real WebView::progress
|
||||
This property holds the progress of loading the current URL, from 0 to 1.
|
||||
|
||||
If you just want to know when progress gets to 1, use
|
||||
WebView::onLoadFinished() or WebView::onLoadFailed() instead.
|
||||
*/
|
||||
qreal AmneziaWebView::progress() const
|
||||
{
|
||||
Q_D(const AmneziaWebView);
|
||||
return d->progress;
|
||||
}
|
||||
|
||||
void AmneziaWebView::doLoadStarted()
|
||||
{
|
||||
Q_D(AmneziaWebView);
|
||||
|
||||
if (!d->url.isEmpty()) {
|
||||
d->status = Loading;
|
||||
emit statusChanged(d->status);
|
||||
}
|
||||
emit loadStarted();
|
||||
}
|
||||
|
||||
void AmneziaWebView::doLoadProgress(int p)
|
||||
{
|
||||
Q_D(AmneziaWebView);
|
||||
|
||||
if (d->progress == p / 100.0)
|
||||
return;
|
||||
d->progress = p / 100.0;
|
||||
emit progressChanged();
|
||||
}
|
||||
|
||||
|
||||
void AmneziaWebView::doLoadFinished(bool ok)
|
||||
{
|
||||
Q_D(AmneziaWebView);
|
||||
|
||||
if (ok) {
|
||||
d->status = d->url.isEmpty() ? Null : Ready;
|
||||
emit loadFinished();
|
||||
} else {
|
||||
d->status = Error;
|
||||
emit loadFailed();
|
||||
}
|
||||
emit statusChanged(d->status);
|
||||
}
|
||||
|
||||
/*!
|
||||
\qmlproperty url AmneziaWebView::url
|
||||
This property holds the URL to the page displayed in this item. It can be set,
|
||||
but also can change spontaneously (eg. because of network redirection).
|
||||
|
||||
If the url is empty, the page is blank.
|
||||
|
||||
The url is always absolute (QML will resolve relative URL strings in the context
|
||||
of the containing QML document).
|
||||
*/
|
||||
QUrl AmneziaWebView::url() const
|
||||
{
|
||||
Q_D(const AmneziaWebView);
|
||||
return d->url;
|
||||
}
|
||||
|
||||
void AmneziaWebView::setUrl(const QUrl& url)
|
||||
{
|
||||
Q_D(AmneziaWebView);
|
||||
|
||||
QString urlString = url.toString();
|
||||
while ( urlString.endsWith('#')) urlString.chop(1);
|
||||
QUrl newUrl(urlString);
|
||||
|
||||
if (newUrl == QUrl(QLatin1String("about:blank")) ) {
|
||||
newUrl = QUrl("");
|
||||
}
|
||||
|
||||
if ((url == d->url) || (newUrl == d->url))
|
||||
return;
|
||||
|
||||
if (isComponentComplete()) {
|
||||
// Make WebView visible before loading
|
||||
if (isVisible() && !d->visible) {
|
||||
d->show();
|
||||
}
|
||||
d->load(url);
|
||||
|
||||
} else {
|
||||
|
||||
d->pending = d->PendingUrl;
|
||||
d->pendingUrl = url;
|
||||
}
|
||||
}
|
||||
|
||||
qreal AmneziaWebView::preferredWidth() const
|
||||
{
|
||||
Q_D(const AmneziaWebView);
|
||||
return d->preferredwidth;
|
||||
}
|
||||
|
||||
void AmneziaWebView::setPreferredWidth(qreal width)
|
||||
{
|
||||
Q_D(AmneziaWebView);
|
||||
|
||||
if (d->preferredwidth == width)
|
||||
return;
|
||||
|
||||
d->preferredwidth = width;
|
||||
updateContentsSize();
|
||||
setImplicitWidth(width);
|
||||
emit preferredWidthChanged();
|
||||
}
|
||||
|
||||
qreal AmneziaWebView::preferredHeight() const
|
||||
{
|
||||
Q_D(const AmneziaWebView);
|
||||
return d->preferredheight;
|
||||
}
|
||||
|
||||
void AmneziaWebView::setPreferredHeight(qreal height)
|
||||
{
|
||||
Q_D(AmneziaWebView);
|
||||
|
||||
if (d->preferredheight == height)
|
||||
return;
|
||||
|
||||
d->preferredheight = height;
|
||||
updateContentsSize();
|
||||
setImplicitHeight(height);
|
||||
emit preferredHeightChanged();
|
||||
}
|
||||
|
||||
|
||||
/*!
|
||||
\qmlmethod bool AmneziaWebView::evaluateJavaScript(string scriptSource)
|
||||
|
||||
Evaluates the \a scriptSource JavaScript inside the context of the
|
||||
main web frame, and returns the result of the last executed statement.
|
||||
|
||||
Note that this JavaScript does \e not have any access to QML objects
|
||||
except as made available as windowObjects.
|
||||
*/
|
||||
void AmneziaWebView::evaluateJavaScript(const QString& scriptSource)
|
||||
{
|
||||
Q_D(AmneziaWebView);
|
||||
if (qApp->thread() == QThread::currentThread()) {
|
||||
d->evaluateJavaScript(scriptSource);
|
||||
}
|
||||
else {
|
||||
QMetaObject::invokeMethod(d, "evaluateJavaScript", Qt::BlockingQueuedConnection,
|
||||
Q_ARG(const QString, scriptSource));
|
||||
}
|
||||
}
|
||||
|
||||
void AmneziaWebView::windowWasChanged(QQuickWindow* window)
|
||||
{
|
||||
Q_D(AmneziaWebView);
|
||||
d->setWindowParent(window);
|
||||
}
|
||||
|
||||
void AmneziaWebView::updateGeometry()
|
||||
{
|
||||
Q_D(AmneziaWebView);
|
||||
QRectF geometry = QRectF(QPointF(x(), y()), QSizeF(width(), height()));
|
||||
if (!geometry.isEmpty() && window()) {
|
||||
QRectF sceneGeometry = mapRectToScene(geometry);
|
||||
QRect rect = sceneGeometry.toRect();
|
||||
qDebug() << "AmneziaWebView::updateGeometry() - local:" << geometry
|
||||
<< "scene:" << sceneGeometry << "rect:" << rect
|
||||
<< "width:" << width() << "height:" << height();
|
||||
d->setGeometry(rect);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void AmneziaWebView::parentWasChanged()
|
||||
{
|
||||
if (parentItem()) {
|
||||
updateGeometry();
|
||||
}
|
||||
}
|
||||
|
||||
QList<QQuickItem *> recurseChildren(QQuickItem * parentItem)
|
||||
{
|
||||
QList<QQuickItem *>childs = parentItem->childItems();
|
||||
QList<QQuickItem *> items;
|
||||
int count = childs.count();
|
||||
for(int i = count - 1; i >= 0; --i) {
|
||||
QQuickItem *next = childs.at(i);
|
||||
items.append(recurseChildren(next));
|
||||
}
|
||||
items.append(childs);
|
||||
return items;
|
||||
}
|
||||
|
||||
|
||||
void AmneziaWebView::paint(QPainter *painter)
|
||||
{
|
||||
Q_D(AmneziaWebView);
|
||||
if (!painter || !window() ) {
|
||||
return;
|
||||
}
|
||||
|
||||
QRectF contentRect = contentsBoundingRect();
|
||||
if ((contentRect.height() <= 0) || (contentRect.width() <= 0)) return;
|
||||
|
||||
painter->setOpacity(1.0);
|
||||
QMutexLocker lock(&d->renderMutex);
|
||||
|
||||
QColor color = d->backgroundColor;
|
||||
painter->fillRect(contentRect, color);
|
||||
|
||||
}
|
||||
|
||||
void AmneziaWebView::afterRendering()
|
||||
{
|
||||
Q_D(AmneziaWebView);
|
||||
|
||||
Qt::ApplicationState state = qApp->applicationState();
|
||||
if ( state != Qt::ApplicationActive) {
|
||||
if (d->visible && isVisible()) {
|
||||
QMetaObject::invokeMethod(d, "requestHide", Qt::QueuedConnection);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!window()) return;
|
||||
|
||||
if (isVisible()) {
|
||||
QMetaObject::invokeMethod(this, "updateGeometry", Qt::QueuedConnection);
|
||||
}
|
||||
|
||||
QMetaObject::invokeMethod(d, "requestShow", Qt::QueuedConnection);
|
||||
|
||||
}
|
||||
|
||||
void AmneziaWebView::geometryChange(const QRectF &newGeometry, const QRectF &oldGeometry)
|
||||
{
|
||||
Q_D(AmneziaWebView);
|
||||
|
||||
QQuickPaintedItem::geometryChange(newGeometry, oldGeometry);
|
||||
|
||||
// Update WebView geometry when QML item size changes
|
||||
if (window() && !newGeometry.isEmpty() && newGeometry != oldGeometry) {
|
||||
QMetaObject::invokeMethod(this, "updateGeometry", Qt::QueuedConnection);
|
||||
}
|
||||
}
|
||||
|
||||
void AmneziaWebView::itemChange(ItemChange change, const ItemChangeData & value)
|
||||
{
|
||||
Q_D(AmneziaWebView);
|
||||
switch (change) {
|
||||
case ItemSceneChange: {
|
||||
QQuickWindow *sc = value.window;
|
||||
if (sc) {
|
||||
connect(sc, SIGNAL(afterRendering()), this, SLOT(afterRendering()), Qt::QueuedConnection);
|
||||
}
|
||||
else {
|
||||
disconnect(this, SLOT(afterRendering()));
|
||||
}
|
||||
}
|
||||
break;
|
||||
case ItemVisibleHasChanged: {
|
||||
|
||||
if (!window()) break;
|
||||
|
||||
if (value.boolValue) {
|
||||
// Component became visible - show WebView
|
||||
if (!d->visible) {
|
||||
d->show();
|
||||
}
|
||||
} else {
|
||||
QMetaObject::invokeMethod(d, "requestHide", Qt::QueuedConnection);
|
||||
}
|
||||
if (value.boolValue && !d->overlapped) {
|
||||
QMetaObject::invokeMethod(d, "requestShow", Qt::QueuedConnection);
|
||||
}
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
QQuickPaintedItem::itemChange(change, value);
|
||||
}
|
||||
|
||||
/*!
|
||||
\qmlproperty list<object> WebView::javaScriptWindowObjects
|
||||
|
||||
A list of QML objects to expose to the web page.
|
||||
|
||||
Each object will be added as a property of the web frame's window object. The
|
||||
property name is controlled by the value of \c WebView.windowObjectName
|
||||
attached property.
|
||||
|
||||
Exposing QML objects to a web page allows JavaScript executing in the web
|
||||
page itself to communicate with QML, by reading and writing properties and
|
||||
by calling methods of the exposed QML objects.
|
||||
|
||||
This example shows how to call into a QML method using a window object.
|
||||
|
||||
\qml
|
||||
WebView {
|
||||
javaScriptWindowObjects: QtObject {
|
||||
WebView.windowObjectName: "qml"
|
||||
|
||||
function qmlCall() {
|
||||
console.log("This call is in QML!");
|
||||
}
|
||||
}
|
||||
|
||||
html: "<script>window.qml.qmlCall();</script>"
|
||||
}
|
||||
\endqml
|
||||
|
||||
The output of the example will be:
|
||||
\code
|
||||
This call is in QML!
|
||||
\endcode
|
||||
|
||||
If Javascript is not enabled for the page, then this property does nothing.
|
||||
*/
|
||||
QQmlListProperty<QObject> AmneziaWebView::javaScriptWindowObjects()
|
||||
{
|
||||
Q_D(AmneziaWebView);
|
||||
return QQmlListProperty<QObject>(this, d, &AmneziaWebViewPrivate::windowObjectsAppend,
|
||||
&AmneziaWebViewPrivate::windowObjectsCount,
|
||||
&AmneziaWebViewPrivate::windowObjectsAt,
|
||||
&AmneziaWebViewPrivate::windowObjectsClear );
|
||||
}
|
||||
|
||||
AmneziaWebViewSettings* AmneziaWebView::settingsObject() const
|
||||
{
|
||||
Q_D(const AmneziaWebView);
|
||||
return d->m_settings.data();
|
||||
}
|
||||
|
||||
|
||||
AmneziaWebViewAttached* AmneziaWebView::qmlAttachedProperties(QObject* o)
|
||||
{
|
||||
return new AmneziaWebViewAttached(o);
|
||||
}
|
||||
|
||||
void AmneziaWebViewPrivate::updateWindowObjects()
|
||||
{
|
||||
|
||||
if (!q_ptr->isComponentCompletePublic())
|
||||
return;
|
||||
|
||||
for (int i = 0; i < windowObjects.count(); ++i) {
|
||||
QObject* object = windowObjects.at(i);
|
||||
AmneziaWebViewAttached* attached = static_cast<AmneziaWebViewAttached *>(qmlAttachedPropertiesObject<AmneziaWebView>(object));
|
||||
if (attached && !attached->windowObjectName().isEmpty())
|
||||
addToJavaScriptWindowObject(attached->windowObjectName(), object);
|
||||
}
|
||||
}
|
||||
|
||||
int AmneziaWebView::pressGrabTime() const
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
void AmneziaWebView::setPressGrabTime(int millis)
|
||||
{
|
||||
Q_UNUSED(millis)
|
||||
|
||||
emit pressGrabTimeChanged();
|
||||
}
|
||||
|
||||
#ifndef QT_NO_ACTION
|
||||
/*!
|
||||
\qmlproperty action WebView::back
|
||||
This property holds the action for causing the previous URL in the history to be displayed.
|
||||
*/
|
||||
QAction* AmneziaWebView::backAction() const
|
||||
{
|
||||
return action(AmneziaWebView::Back);
|
||||
}
|
||||
|
||||
/*!
|
||||
\qmlproperty action WebView::forward
|
||||
This property holds the action for causing the next URL in the history to be displayed.
|
||||
*/
|
||||
QAction* AmneziaWebView::forwardAction() const
|
||||
{
|
||||
return action(AmneziaWebView::Forward);
|
||||
}
|
||||
|
||||
/*!
|
||||
\qmlproperty action WebView::reload
|
||||
This property holds the action for reloading with the current URL
|
||||
*/
|
||||
QAction* AmneziaWebView::reloadAction() const
|
||||
{
|
||||
return action(AmneziaWebView::Reload);
|
||||
}
|
||||
|
||||
/*!
|
||||
\qmlproperty action WebView::stop
|
||||
This property holds the action for stopping loading with the current URL
|
||||
*/
|
||||
QAction* AmneziaWebView::stopAction() const
|
||||
{
|
||||
return action(AmneziaWebView::Stop);
|
||||
}
|
||||
#endif // QT_NO_ACTION
|
||||
|
||||
/*!
|
||||
\qmlproperty string WebView::title
|
||||
This property holds the title of the web page currently viewed
|
||||
|
||||
By default, this property contains an empty string.
|
||||
*/
|
||||
QString AmneziaWebView::title() const
|
||||
{
|
||||
Q_D(const AmneziaWebView);
|
||||
return d->title;
|
||||
}
|
||||
|
||||
/*!
|
||||
\qmlproperty pixmap WebView::icon
|
||||
This property holds the icon associated with the web page currently viewed
|
||||
*/
|
||||
QPixmap AmneziaWebView::icon() const
|
||||
{
|
||||
Q_D(const AmneziaWebView);
|
||||
return d->icon().pixmap(QSize(256, 256));
|
||||
}
|
||||
|
||||
/*!
|
||||
\qmlproperty string WebView::statusText
|
||||
|
||||
This property is the current status suggested by the current web page. In a web browser,
|
||||
such status is often shown in some kind of status bar.
|
||||
*/
|
||||
void AmneziaWebView::setStatusText(const QString& text)
|
||||
{
|
||||
Q_D(AmneziaWebView);
|
||||
d->statusText = text;
|
||||
emit statusTextChanged();
|
||||
}
|
||||
|
||||
void AmneziaWebView::windowObjectCleared()
|
||||
{
|
||||
Q_D(AmneziaWebView);
|
||||
d->updateWindowObjects();
|
||||
}
|
||||
|
||||
QString AmneziaWebView::statusText() const
|
||||
{
|
||||
Q_D(const AmneziaWebView);
|
||||
return d->statusText;
|
||||
}
|
||||
|
||||
|
||||
void AmneziaWebView::load(const QNetworkRequest& request, QNetworkAccessManager::Operation operation, const QByteArray& body)
|
||||
{
|
||||
Q_D(AmneziaWebView);
|
||||
d->load(request, operation, body);
|
||||
}
|
||||
|
||||
QString AmneziaWebView::html() const
|
||||
{
|
||||
Q_D(const AmneziaWebView);
|
||||
return d->toHtml();
|
||||
}
|
||||
|
||||
void AmneziaWebView::setHtml(const QString& html, const QUrl& baseUrl)
|
||||
{
|
||||
Q_D(AmneziaWebView);
|
||||
auto originUrl = baseUrl.isValid() ? baseUrl : defaultBaseUrl();
|
||||
|
||||
updateContentsSize();
|
||||
if (isComponentComplete()) {
|
||||
d->setHtml(html, originUrl);
|
||||
}
|
||||
else {
|
||||
d->pending = d->PendingHtml;
|
||||
d->pendingUrl = originUrl;
|
||||
d->pendingString = html;
|
||||
}
|
||||
emit htmlChanged();
|
||||
}
|
||||
|
||||
void AmneziaWebView::setContent(const QByteArray& data, const QString& mimeType, const QUrl& baseUrl)
|
||||
{
|
||||
Q_D(AmneziaWebView);
|
||||
|
||||
updateContentsSize();
|
||||
auto originUrl = baseUrl.isValid() ? baseUrl : defaultBaseUrl();
|
||||
|
||||
if (isComponentComplete())
|
||||
d->setContent(data, mimeType, qmlContext(this)->resolvedUrl(baseUrl));
|
||||
else {
|
||||
d->pending = d->PendingContent;
|
||||
d->pendingUrl = originUrl;
|
||||
d->pendingString = mimeType;
|
||||
d->pendingData = data;
|
||||
}
|
||||
}
|
||||
|
||||
AmneziaWebHistory* AmneziaWebView::history() const
|
||||
{
|
||||
Q_D(const AmneziaWebView);
|
||||
return d->history();
|
||||
}
|
||||
|
||||
#ifndef QT_NO_ACTION
|
||||
QAction* AmneziaWebView::action(AmneziaWebView::WebAction action) const
|
||||
{
|
||||
Q_D(const AmneziaWebView);
|
||||
return d->action(action);
|
||||
}
|
||||
#endif
|
||||
|
||||
/*!
|
||||
\qmlproperty component WebView::newWindowComponent
|
||||
|
||||
This property holds the component to use for new windows.
|
||||
The component must have a WebView somewhere in its structure.
|
||||
|
||||
When the web engine requests a new window, it will be an instance of
|
||||
this component.
|
||||
|
||||
The parent of the new window is set by newWindowParent. It must be set.
|
||||
*/
|
||||
QQmlComponent* AmneziaWebView::newWindowComponent() const
|
||||
{
|
||||
Q_D(const AmneziaWebView);
|
||||
return d->newWindowComponent;
|
||||
}
|
||||
|
||||
void AmneziaWebView::setNewWindowComponent(QQmlComponent* newWindow)
|
||||
{
|
||||
Q_D(AmneziaWebView);
|
||||
if (newWindow == d->newWindowComponent)
|
||||
return;
|
||||
d->newWindowComponent = newWindow;
|
||||
emit newWindowComponentChanged();
|
||||
}
|
||||
|
||||
|
||||
/*!
|
||||
\qmlproperty item WebView::newWindowParent
|
||||
|
||||
The parent item for new windows.
|
||||
|
||||
\sa newWindowComponent
|
||||
*/
|
||||
QQuickItem* AmneziaWebView::newWindowParent() const
|
||||
{
|
||||
Q_D(const AmneziaWebView);
|
||||
return d->newWindowParent;
|
||||
}
|
||||
|
||||
void AmneziaWebView::setNewWindowParent(QQuickItem *parent)
|
||||
{
|
||||
Q_D(AmneziaWebView);
|
||||
if (parent == d->newWindowParent)
|
||||
return;
|
||||
if (d->newWindowParent && parent) {
|
||||
QList<QQuickItem *> children = d->newWindowParent->childItems();
|
||||
for (int i = 0; i < children.count(); ++i)
|
||||
children.at(i)->setParentItem(parent);
|
||||
}
|
||||
d->newWindowParent = parent;
|
||||
emit newWindowParentChanged();
|
||||
}
|
||||
|
||||
QSize AmneziaWebView::contentsSize() const
|
||||
{
|
||||
Q_D(const AmneziaWebView);
|
||||
return d->contentsSize() * contentsScale();
|
||||
}
|
||||
|
||||
qreal AmneziaWebView::contentsScale() const
|
||||
{
|
||||
Q_D(const AmneziaWebView);
|
||||
return d->scale();
|
||||
}
|
||||
|
||||
void AmneziaWebView::setContentsScale(qreal scale)
|
||||
{
|
||||
Q_D(AmneziaWebView);
|
||||
if (scale == d->scale())
|
||||
return;
|
||||
d->setScale(scale);
|
||||
|
||||
//updateGeometry();
|
||||
emit contentsScaleChanged();
|
||||
}
|
||||
|
||||
void AmneziaWebView::setDefaultFontSize(int size)
|
||||
{
|
||||
Q_D(AmneziaWebView);
|
||||
d->setDefaultFontSize(size);
|
||||
}
|
||||
|
||||
void AmneziaWebView::setStandardFontFamily(const QString &family)
|
||||
{
|
||||
Q_D(AmneziaWebView);
|
||||
d->setStandardFontFamily(family);
|
||||
}
|
||||
|
||||
void AmneziaWebView::setTextZoom(int percent)
|
||||
{
|
||||
Q_D(AmneziaWebView);
|
||||
d->setTextZoom(percent);
|
||||
}
|
||||
|
||||
|
||||
#ifdef Q_REVISION
|
||||
/*!
|
||||
\qmlproperty color WebView::backgroundColor
|
||||
\since QtWebKit 1.1
|
||||
This property holds the background color of the view.
|
||||
*/
|
||||
|
||||
QColor AmneziaWebView::backgroundColor() const
|
||||
{
|
||||
Q_D(const AmneziaWebView);
|
||||
return d->backgroundColor;
|
||||
}
|
||||
|
||||
void AmneziaWebView::setBackgroundColor(const QColor& color)
|
||||
{
|
||||
setFillColor(color);
|
||||
}
|
||||
|
||||
void AmneziaWebView::fillColorWasChanged()
|
||||
{
|
||||
Q_D(AmneziaWebView);
|
||||
QColor color = fillColor();
|
||||
d->setBackgroundColor(color);
|
||||
emit backgroundColorChanged();
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
QT_END_NAMESPACE
|
||||
|
||||
@@ -1,309 +0,0 @@
|
||||
#ifndef DECLARATIVEWEBVIEW_H
|
||||
#define DECLARATIVEWEBVIEW_H
|
||||
|
||||
#include <QObject>
|
||||
#include <QAction>
|
||||
#include <QBasicTimer>
|
||||
#include <QUrl>
|
||||
#include <QtNetwork/QNetworkAccessManager>
|
||||
|
||||
#include <QtQml>
|
||||
#include <QQuickPaintedItem>
|
||||
|
||||
#include "websettings.h"
|
||||
|
||||
QT_BEGIN_NAMESPACE
|
||||
|
||||
class AmneziaWebViewSettings;
|
||||
class AmneziaWebViewPrivate;
|
||||
class AmneziaWebViewAttached;
|
||||
class AmneziaWebHistory;
|
||||
|
||||
class AmneziaWebView : public QQuickPaintedItem
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
Q_ENUMS(Status SelectionMode)
|
||||
|
||||
Q_PROPERTY(QString title READ title NOTIFY titleChanged)
|
||||
Q_PROPERTY(QPixmap icon READ icon NOTIFY iconChanged)
|
||||
Q_PROPERTY(QString statusText READ statusText NOTIFY statusTextChanged)
|
||||
Q_PROPERTY(QString html READ html WRITE setHtml NOTIFY htmlChanged)
|
||||
Q_PROPERTY(int pressGrabTime READ pressGrabTime WRITE setPressGrabTime NOTIFY pressGrabTimeChanged)
|
||||
Q_PROPERTY(qreal preferredWidth READ preferredWidth WRITE setPreferredWidth NOTIFY preferredWidthChanged)
|
||||
Q_PROPERTY(qreal preferredHeight READ preferredHeight WRITE setPreferredHeight NOTIFY preferredHeightChanged)
|
||||
Q_PROPERTY(QUrl url READ url WRITE setUrl NOTIFY urlChanged)
|
||||
Q_PROPERTY(qreal progress READ progress NOTIFY progressChanged)
|
||||
Q_PROPERTY(Status status READ status NOTIFY statusChanged)
|
||||
|
||||
|
||||
#ifndef QT_NO_ACTION
|
||||
Q_PROPERTY(QAction* reload READ reloadAction CONSTANT)
|
||||
Q_PROPERTY(QAction* back READ backAction CONSTANT)
|
||||
Q_PROPERTY(QAction* forward READ forwardAction CONSTANT)
|
||||
Q_PROPERTY(QAction* stop READ stopAction CONSTANT)
|
||||
#endif
|
||||
|
||||
Q_PROPERTY(AmneziaWebViewSettings* settings READ settingsObject CONSTANT)
|
||||
Q_PROPERTY(QQmlListProperty<QObject> javaScriptWindowObjects READ javaScriptWindowObjects CONSTANT)
|
||||
Q_PROPERTY(QQmlComponent* newWindowComponent READ newWindowComponent WRITE setNewWindowComponent NOTIFY newWindowComponentChanged)
|
||||
Q_PROPERTY(QQuickItem* newWindowParent READ newWindowParent WRITE setNewWindowParent NOTIFY newWindowParentChanged)
|
||||
Q_PROPERTY(QSize contentsSize READ contentsSize NOTIFY contentsSizeChanged)
|
||||
Q_PROPERTY(qreal contentsScale READ contentsScale WRITE setContentsScale NOTIFY contentsScaleChanged)
|
||||
Q_PROPERTY(QColor backgroundColor READ backgroundColor WRITE setBackgroundColor NOTIFY backgroundColorChanged)
|
||||
|
||||
public:
|
||||
|
||||
enum WebAction {
|
||||
NoWebAction = - 1,
|
||||
|
||||
OpenLink,
|
||||
|
||||
OpenLinkInNewWindow,
|
||||
OpenFrameInNewWindow,
|
||||
|
||||
DownloadLinkToDisk,
|
||||
CopyLinkToClipboard,
|
||||
|
||||
OpenImageInNewWindow,
|
||||
DownloadImageToDisk,
|
||||
CopyImageToClipboard,
|
||||
|
||||
Back,
|
||||
Forward,
|
||||
Stop,
|
||||
Reload,
|
||||
|
||||
Cut,
|
||||
Copy,
|
||||
Paste,
|
||||
|
||||
Undo,
|
||||
Redo,
|
||||
MoveToNextChar,
|
||||
MoveToPreviousChar,
|
||||
MoveToNextWord,
|
||||
MoveToPreviousWord,
|
||||
MoveToNextLine,
|
||||
MoveToPreviousLine,
|
||||
MoveToStartOfLine,
|
||||
MoveToEndOfLine,
|
||||
MoveToStartOfBlock,
|
||||
MoveToEndOfBlock,
|
||||
MoveToStartOfDocument,
|
||||
MoveToEndOfDocument,
|
||||
SelectNextChar,
|
||||
SelectPreviousChar,
|
||||
SelectNextWord,
|
||||
SelectPreviousWord,
|
||||
SelectNextLine,
|
||||
SelectPreviousLine,
|
||||
SelectStartOfLine,
|
||||
SelectEndOfLine,
|
||||
SelectStartOfBlock,
|
||||
SelectEndOfBlock,
|
||||
SelectStartOfDocument,
|
||||
SelectEndOfDocument,
|
||||
DeleteStartOfWord,
|
||||
DeleteEndOfWord,
|
||||
|
||||
SetTextDirectionDefault,
|
||||
SetTextDirectionLeftToRight,
|
||||
SetTextDirectionRightToLeft,
|
||||
|
||||
ToggleBold,
|
||||
ToggleItalic,
|
||||
ToggleUnderline,
|
||||
|
||||
InspectElement,
|
||||
|
||||
InsertParagraphSeparator,
|
||||
InsertLineSeparator,
|
||||
|
||||
SelectAll,
|
||||
ReloadAndBypassCache,
|
||||
|
||||
PasteAndMatchStyle,
|
||||
RemoveFormat,
|
||||
|
||||
ToggleStrikethrough,
|
||||
ToggleSubscript,
|
||||
ToggleSuperscript,
|
||||
InsertUnorderedList,
|
||||
InsertOrderedList,
|
||||
Indent,
|
||||
Outdent,
|
||||
|
||||
AlignCenter,
|
||||
AlignJustified,
|
||||
AlignLeft,
|
||||
AlignRight,
|
||||
|
||||
StopScheduledPageRefresh,
|
||||
|
||||
CopyImageUrlToClipboard,
|
||||
|
||||
WebActionCount
|
||||
};
|
||||
|
||||
|
||||
explicit AmneziaWebView(QQuickItem *parent = nullptr);
|
||||
virtual ~AmneziaWebView();
|
||||
|
||||
QUrl url() const;
|
||||
void setUrl(const QUrl &);
|
||||
|
||||
QString title() const;
|
||||
|
||||
QPixmap icon() const;
|
||||
|
||||
int pressGrabTime() const;
|
||||
void setPressGrabTime(int);
|
||||
|
||||
qreal preferredWidth() const;
|
||||
void setPreferredWidth(qreal);
|
||||
qreal preferredHeight() const;
|
||||
void setPreferredHeight(qreal);
|
||||
|
||||
enum Status { Null, Ready, Loading, Error };
|
||||
Status status() const;
|
||||
qreal progress() const;
|
||||
QString statusText() const;
|
||||
|
||||
#ifndef QT_NO_ACTION
|
||||
QAction *reloadAction() const;
|
||||
QAction *backAction() const;
|
||||
QAction *forwardAction() const;
|
||||
QAction *stopAction() const;
|
||||
QAction* action(AmneziaWebView::WebAction) const;
|
||||
#endif
|
||||
|
||||
void load(const QNetworkRequest &request, QNetworkAccessManager::Operation operation = QNetworkAccessManager::GetOperation,
|
||||
const QByteArray &body = QByteArray());
|
||||
|
||||
QString html() const;
|
||||
|
||||
void setHtml(const QString &html, const QUrl &baseUrl = QUrl());
|
||||
void setContent(const QByteArray &data, const QString &mimeType = QString(), const QUrl &baseUrl = QUrl());
|
||||
|
||||
AmneziaWebHistory* history() const;
|
||||
|
||||
QQmlListProperty<QObject> javaScriptWindowObjects();
|
||||
AmneziaWebViewSettings* settingsObject() const;
|
||||
static AmneziaWebViewAttached* qmlAttachedProperties(QObject*);
|
||||
|
||||
QQmlComponent *newWindowComponent() const;
|
||||
void setNewWindowComponent(QQmlComponent *newWindow);
|
||||
QQuickItem* newWindowParent() const;
|
||||
void setNewWindowParent(QQuickItem* newWindow);
|
||||
|
||||
bool isComponentCompletePublic() const { return isComponentComplete(); }
|
||||
|
||||
QSize contentsSize() const;
|
||||
|
||||
void setContentsScale(qreal scale);
|
||||
qreal contentsScale() const;
|
||||
|
||||
QColor backgroundColor() const;
|
||||
void setBackgroundColor(const QColor&);
|
||||
|
||||
void paint(QPainter *painter) override;
|
||||
|
||||
void setDefaultFontSize(int size);
|
||||
void setStandardFontFamily(const QString &family);
|
||||
Q_INVOKABLE void setTextZoom(int percent);
|
||||
|
||||
Q_SIGNALS:
|
||||
|
||||
void preferredWidthChanged();
|
||||
void preferredHeightChanged();
|
||||
|
||||
void urlChanged();
|
||||
void progressChanged();
|
||||
void statusChanged(Status);
|
||||
void titleChanged(const QString&);
|
||||
void iconChanged();
|
||||
void statusTextChanged();
|
||||
void htmlChanged();
|
||||
void pressGrabTimeChanged();
|
||||
void newWindowComponentChanged();
|
||||
void newWindowParentChanged();
|
||||
void renderingEnabledChanged();
|
||||
void contentsSizeChanged(const QSize&);
|
||||
void contentsScaleChanged();
|
||||
void backgroundColorChanged();
|
||||
|
||||
void loadStarted();
|
||||
void loadFinished();
|
||||
void loadFinished(bool ok);
|
||||
void loadFailed();
|
||||
|
||||
void doubleClick(int clickX, int clickY);
|
||||
void zoomTo(qreal zoom, int centerX, int centerY);
|
||||
void alert(const QString& message);
|
||||
|
||||
public Q_SLOTS:
|
||||
void evaluateJavaScript(const QString&);
|
||||
|
||||
private Q_SLOTS:
|
||||
void afterRendering();
|
||||
void updateGeometry();
|
||||
void windowWasChanged(QQuickWindow* window);
|
||||
void parentWasChanged();
|
||||
void fillColorWasChanged();
|
||||
|
||||
void doLoadStarted();
|
||||
void doLoadProgress(int p);
|
||||
void doLoadFinished(bool ok);
|
||||
void setStatusText(const QString&);
|
||||
void windowObjectCleared();
|
||||
|
||||
protected:
|
||||
|
||||
void itemChange(ItemChange, const ItemChangeData &) override;
|
||||
void geometryChange(const QRectF &newGeometry, const QRectF &oldGeometry) override;
|
||||
QScopedPointer<AmneziaWebViewPrivate> d_ptr;
|
||||
|
||||
private:
|
||||
void updateContentsSize() {}
|
||||
void init();
|
||||
void componentComplete() override;
|
||||
QTimer upadeTimer;
|
||||
|
||||
|
||||
Q_DISABLE_COPY(AmneziaWebView)
|
||||
Q_DECLARE_PRIVATE(AmneziaWebView)
|
||||
|
||||
friend class QDeclarativeWebPage;
|
||||
};
|
||||
|
||||
class AmneziaWebViewAttached : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
Q_PROPERTY(QString windowObjectName READ windowObjectName WRITE setWindowObjectName)
|
||||
public:
|
||||
explicit AmneziaWebViewAttached(QObject* parent)
|
||||
: QObject(parent)
|
||||
{
|
||||
}
|
||||
|
||||
QString windowObjectName() const
|
||||
{
|
||||
return m_windowObjectName;
|
||||
}
|
||||
|
||||
void setWindowObjectName(const QString &n)
|
||||
{
|
||||
m_windowObjectName = n;
|
||||
}
|
||||
|
||||
private:
|
||||
QString m_windowObjectName;
|
||||
};
|
||||
|
||||
QT_END_NAMESPACE
|
||||
|
||||
QML_DECLARE_TYPE(AmneziaWebView)
|
||||
QML_DECLARE_TYPEINFO(AmneziaWebView, QML_HAS_ATTACHED_PROPERTIES)
|
||||
|
||||
#endif
|
||||
@@ -1,369 +0,0 @@
|
||||
#include <QtCore/qglobal.h>
|
||||
#include <QtCore>
|
||||
#include <QGuiApplication>
|
||||
#include <QCoreApplication>
|
||||
#include <QDebug>
|
||||
#include <QMap>
|
||||
#include <QMutex>
|
||||
#include <QMutexLocker>
|
||||
#include <QTimer>
|
||||
#include <jni.h>
|
||||
#include <android/bitmap.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "amneziawebview_p.h"
|
||||
#include "qrchandler.h"
|
||||
#include "filehandler.h"
|
||||
|
||||
#include <QJniObject>
|
||||
#include <QJniEnvironment>
|
||||
|
||||
namespace Jni
|
||||
{
|
||||
|
||||
using Object = QJniObject;
|
||||
}
|
||||
static const char qtAndroidWebViewControllerClass[] = "org/amnezia/vpn/WebViewController";
|
||||
|
||||
class AndroidWebViewPrivate;
|
||||
|
||||
typedef QMap<quintptr, AndroidWebViewPrivate *> WebViews;
|
||||
Q_GLOBAL_STATIC(WebViews, g_webViews)
|
||||
Q_GLOBAL_STATIC(QMutex, g_webMutex)
|
||||
|
||||
class AndroidWebViewPrivate : public AmneziaWebViewPrivate
|
||||
{
|
||||
Q_DECLARE_PUBLIC(AmneziaWebView)
|
||||
|
||||
public:
|
||||
|
||||
explicit AndroidWebViewPrivate(AmneziaWebView* q);
|
||||
virtual ~AndroidWebViewPrivate();
|
||||
|
||||
static AndroidWebViewPrivate *get(AmneziaWebView *q)
|
||||
{
|
||||
return static_cast<AndroidWebViewPrivate*>(AmneziaWebViewPrivate::get(q));
|
||||
}
|
||||
|
||||
virtual void setWindowParent(QWindow *parent);
|
||||
virtual void setBackgroundColor(const QColor backgroundColor);
|
||||
virtual void show();
|
||||
virtual void hide();
|
||||
virtual void setGeometry(const QRect &);
|
||||
virtual QString innerHTML() const;
|
||||
virtual void load(const QUrl& url);
|
||||
virtual void setHtml(const QString& html, const QUrl& baseUrl = QUrl());
|
||||
virtual void setContent(const QByteArray& data, const QString& mimeType, const QUrl& baseUrl);
|
||||
virtual void evaluateJavaScript(const QString& scriptSource);
|
||||
virtual bool isLoading() const;
|
||||
virtual bool canGoBack() const;
|
||||
virtual bool canGoForward() const;
|
||||
virtual void back();
|
||||
virtual void forward();
|
||||
virtual void reload();
|
||||
virtual void stop();
|
||||
virtual void setUrl(const QUrl &url);
|
||||
virtual QIcon icon() const;
|
||||
virtual void setScale(qreal scale);
|
||||
virtual qreal scale() const;
|
||||
virtual QSize contentsSize() const;
|
||||
virtual void setDefaultFontSize(int size);
|
||||
virtual void setStandardFontFamily(const QString &family);
|
||||
virtual void setTextZoom(int percent);
|
||||
private:
|
||||
|
||||
quintptr viewId;
|
||||
Jni::Object m_viewController;
|
||||
};
|
||||
|
||||
AndroidWebViewPrivate::AndroidWebViewPrivate(AmneziaWebView* q): AmneziaWebViewPrivate(q),
|
||||
viewId(reinterpret_cast<quintptr>(this))
|
||||
{
|
||||
m_viewController = Jni::Object(qtAndroidWebViewControllerClass,
|
||||
"(Landroid/app/Activity;J)V",
|
||||
QNativeInterface::QAndroidApplication::context().object(),
|
||||
viewId);
|
||||
QMutexLocker lock(g_webMutex());
|
||||
g_webViews->insert(viewId, this);
|
||||
setBackgroundColor(backgroundColor);
|
||||
}
|
||||
|
||||
AndroidWebViewPrivate::~AndroidWebViewPrivate()
|
||||
{
|
||||
QMutexLocker lock(g_webMutex());
|
||||
m_viewController.callMethod<void>("release", "()V");
|
||||
g_webViews->take(viewId);
|
||||
}
|
||||
|
||||
AmneziaWebViewPrivate *AmneziaWebViewPrivate::create(AmneziaWebView *q)
|
||||
{
|
||||
return new AndroidWebViewPrivate(q);
|
||||
}
|
||||
|
||||
void AndroidWebViewPrivate::setWindowParent(QWindow *parent)
|
||||
{
|
||||
Q_UNUSED(parent);
|
||||
}
|
||||
|
||||
|
||||
void AndroidWebViewPrivate::setBackgroundColor(const QColor backgroundColor)
|
||||
{
|
||||
m_viewController.callMethod<void>("setBackgroundColor", "(I)V",
|
||||
jint(backgroundColor.rgb()));
|
||||
emit backgroundColorChanged();
|
||||
}
|
||||
|
||||
|
||||
bool AndroidWebViewPrivate::isLoading() const
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
/// Deprecated
|
||||
void AndroidWebViewPrivate::setScale(qreal scale)
|
||||
{
|
||||
Q_UNUSED(scale);
|
||||
}
|
||||
|
||||
/// Deprecated
|
||||
qreal AndroidWebViewPrivate::scale() const
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
QIcon AndroidWebViewPrivate::icon() const
|
||||
{
|
||||
return QIcon();
|
||||
}
|
||||
|
||||
QSize AndroidWebViewPrivate::contentsSize() const
|
||||
{
|
||||
return QSize();
|
||||
}
|
||||
|
||||
void AndroidWebViewPrivate::setGeometry(const QRect &geometry)
|
||||
{
|
||||
if (this->geometry != geometry) {
|
||||
this->geometry = geometry;
|
||||
|
||||
m_viewController.callMethod<void>("setGeometry", "(IIII)V",
|
||||
jint(geometry.x()), jint(geometry.y()),
|
||||
jint(geometry.width()), jint(geometry.height()) );
|
||||
}
|
||||
}
|
||||
|
||||
void AndroidWebViewPrivate::setTextZoom(int percent)
|
||||
{
|
||||
m_viewController.callMethod<void>("setTextZoom", "(I)V", jint(percent));
|
||||
}
|
||||
|
||||
void AndroidWebViewPrivate::hide()
|
||||
{
|
||||
Q_Q(AmneziaWebView);
|
||||
if (visible) {
|
||||
m_viewController.callMethod<void>("hide", "()V");
|
||||
visible = false;
|
||||
q->update();
|
||||
}
|
||||
}
|
||||
|
||||
void AndroidWebViewPrivate::show()
|
||||
{
|
||||
if (!visible) {
|
||||
m_viewController.callMethod<void>("show", "()V");
|
||||
visible = true;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void AndroidWebViewPrivate::setContent(const QByteArray& data, const QString& mimeType, const QUrl& baseUrl)
|
||||
{
|
||||
Q_UNUSED(data);
|
||||
Q_UNUSED(mimeType);
|
||||
Q_UNUSED(baseUrl);
|
||||
}
|
||||
|
||||
void AndroidWebViewPrivate::setUrl(const QUrl &url)
|
||||
{
|
||||
AmneziaWebViewPrivate::setUrl(url);
|
||||
}
|
||||
|
||||
void AndroidWebViewPrivate::load(const QUrl &url)
|
||||
{
|
||||
// Make WebView visible before loading
|
||||
if (!visible) {
|
||||
show();
|
||||
}
|
||||
Jni::Object jurl = Jni::Object::fromString(url.isValid() ? url.toString() : QString("about:blank"));
|
||||
m_viewController.callMethod<void>("loadUrl", "(Ljava/lang/String;)V", jurl.object<jstring>());
|
||||
}
|
||||
|
||||
void AndroidWebViewPrivate::setHtml(const QString &html, const QUrl &baseUrl)
|
||||
{
|
||||
if (html.isNull()) {
|
||||
return;
|
||||
}
|
||||
|
||||
Jni::Object url = Jni::Object::fromString(baseUrl.isValid() ? baseUrl.toString() : QString("about:blank"));
|
||||
Jni::Object data = Jni::Object::fromString(html);
|
||||
Jni::Object mime = Jni::Object::fromString(QString("text/html"));
|
||||
Jni::Object encoding = Jni::Object::fromString(QString("utf-8"));
|
||||
|
||||
m_viewController.callMethod<void>("loadDataWithBaseURL", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V",
|
||||
url.object<jstring>(), data.object<jstring>(), mime.object<jstring>(), encoding.object<jstring>());
|
||||
}
|
||||
|
||||
void AndroidWebViewPrivate::evaluateJavaScript(const QString &scriptSource)
|
||||
{
|
||||
Jni::Object script = Jni::Object::fromString(scriptSource);
|
||||
m_viewController.callMethod<void>("evaluateJavaScript", "(Ljava/lang/String;)V", script.object<jstring>());
|
||||
}
|
||||
|
||||
bool AndroidWebViewPrivate::canGoBack() const
|
||||
{
|
||||
jboolean can = m_viewController.callMethod<jboolean>("canGoBack", "()Z");
|
||||
return can;
|
||||
}
|
||||
|
||||
bool AndroidWebViewPrivate::canGoForward() const
|
||||
{
|
||||
jboolean can = m_viewController.callMethod<jboolean>("canGoForward", "()Z");
|
||||
return can;
|
||||
}
|
||||
|
||||
void AndroidWebViewPrivate::back()
|
||||
{
|
||||
m_viewController.callMethod<void>("goBack", "()V");
|
||||
}
|
||||
|
||||
void AndroidWebViewPrivate::forward()
|
||||
{
|
||||
m_viewController.callMethod<void>("goForward", "()V");
|
||||
}
|
||||
|
||||
void AndroidWebViewPrivate::reload()
|
||||
{
|
||||
}
|
||||
|
||||
void AndroidWebViewPrivate::stop()
|
||||
{
|
||||
}
|
||||
|
||||
QString AndroidWebViewPrivate::innerHTML() const
|
||||
{
|
||||
return QString();
|
||||
}
|
||||
|
||||
void AndroidWebViewPrivate::setDefaultFontSize(int size)
|
||||
{
|
||||
m_viewController.callMethod<void>("setDefaultFontSize", "(I)V", jint(size));
|
||||
}
|
||||
|
||||
void AndroidWebViewPrivate::setStandardFontFamily(const QString &family)
|
||||
{
|
||||
Jni::Object fontFamily = Jni::Object::fromString(family);
|
||||
m_viewController.callMethod<void>("setStandardFontFamily", "(Ljava/lang/String;)V", fontFamily.object<jstring>());
|
||||
}
|
||||
|
||||
extern "C" {
|
||||
|
||||
JNIEXPORT void Java_org_amnezia_vpn_WebViewController_pageStarted(JNIEnv *env, jobject obj, jlong viewId, jstring url)
|
||||
{
|
||||
Q_UNUSED(env);
|
||||
Q_UNUSED(obj);
|
||||
|
||||
QMutexLocker lock(g_webMutex());
|
||||
AndroidWebViewPrivate *view = g_webViews()->value(viewId);
|
||||
if (view) {
|
||||
const char *urlChars = env->GetStringUTFChars(url, 0);
|
||||
const QUrl url = QUrl(QString(urlChars));
|
||||
QMetaObject::invokeMethod(view, "onPageStarted", Qt::QueuedConnection);
|
||||
}
|
||||
}
|
||||
|
||||
JNIEXPORT void Java_org_amnezia_vpn_WebViewController_pageFinished(JNIEnv *env, jobject obj, jlong viewId, jstring url)
|
||||
{
|
||||
Q_UNUSED(env);
|
||||
Q_UNUSED(obj);
|
||||
QMutexLocker lock(g_webMutex());
|
||||
AndroidWebViewPrivate *view = g_webViews()->value(viewId);
|
||||
if (view) {
|
||||
const char *urlChars = env->GetStringUTFChars(url, 0);
|
||||
const QUrl url = QUrl(QString(urlChars));
|
||||
QMetaObject::invokeMethod(view, "onPageFinished", Qt::QueuedConnection);
|
||||
}
|
||||
}
|
||||
|
||||
JNIEXPORT void Java_org_amnezia_vpn_WebViewController_urlChanged(JNIEnv *env, jobject obj, jlong viewId, jstring url)
|
||||
{
|
||||
Q_UNUSED(env);
|
||||
Q_UNUSED(obj);
|
||||
QMutexLocker lock(g_webMutex());
|
||||
AndroidWebViewPrivate *view = g_webViews()->value(viewId);
|
||||
if (view) {
|
||||
|
||||
const char *urlChars = env->GetStringUTFChars(url, 0);
|
||||
const QUrl url = QUrl(QString(urlChars));
|
||||
QMetaObject::invokeMethod(view, "onUrlChanged", Qt::QueuedConnection, Q_ARG( const QUrl, url));
|
||||
}
|
||||
}
|
||||
|
||||
JNIEXPORT jbyteArray Java_org_amnezia_vpn_WebViewController_dataForUrl(JNIEnv *env, jobject obj, jlong viewId, jstring url, jobject mimeType, jobject encoding)
|
||||
{
|
||||
Q_UNUSED(env)
|
||||
Q_UNUSED(obj)
|
||||
|
||||
QMutexLocker lock(g_webMutex());
|
||||
AndroidWebViewPrivate *view = g_webViews()->value(viewId);
|
||||
if (view) {
|
||||
|
||||
const char *urlChars = env->GetStringUTFChars(url, 0);
|
||||
const QUrl url = QUrl(QString(urlChars));
|
||||
|
||||
QByteArray buffer = view->dataForUrl(url);
|
||||
QString mime = view->mimeTypeForUrl(url);
|
||||
QString enc("utf-8");
|
||||
|
||||
jstring jMimeType = env->NewStringUTF(mime.toUtf8().constData());
|
||||
Jni::Object jMimeTypeObject(mimeType);
|
||||
if (jMimeTypeObject.isValid()) {
|
||||
jMimeTypeObject.callObjectMethod("insert", "(ILjava/lang/String;)Ljava/lang/StringBuilder;", 0, jMimeType);
|
||||
}
|
||||
|
||||
jstring jEncoding = env->NewStringUTF(enc.toUtf8().constData());
|
||||
Jni::Object jEncodingObject(encoding);
|
||||
if (jEncodingObject.isValid()) {
|
||||
|
||||
jEncodingObject.callObjectMethod("insert", "(ILjava/lang/String;)Ljava/lang/StringBuilder;", 0, jEncoding);
|
||||
}
|
||||
|
||||
env->DeleteLocalRef(jEncoding);
|
||||
env->DeleteLocalRef(jMimeType);
|
||||
|
||||
jbyteArray data = env->NewByteArray(buffer.size());
|
||||
env->SetByteArrayRegion(data, 0, buffer.size(), (const jbyte*) buffer.data());
|
||||
return data;
|
||||
}
|
||||
|
||||
return NULL;
|
||||
}
|
||||
|
||||
JNIEXPORT jboolean Java_org_amnezia_vpn_WebViewController_canHandleUrl(JNIEnv *env, jobject obj, jlong viewId, jstring url)
|
||||
|
||||
{
|
||||
Q_UNUSED(env);
|
||||
Q_UNUSED(obj);
|
||||
QMutexLocker lock(g_webMutex());
|
||||
AndroidWebViewPrivate *view = g_webViews()->value(viewId);
|
||||
if (view) {
|
||||
const char *urlChars = env->GetStringUTFChars(url, 0);
|
||||
const QUrl url = QUrl(QString(urlChars));
|
||||
return view->canHandleUrl(url);
|
||||
}
|
||||
|
||||
return jboolean(false);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,433 +0,0 @@
|
||||
#include <QtCore>
|
||||
#include <QDebug>
|
||||
#include <QBoxLayout>
|
||||
#include <QApplication>
|
||||
#include <QGuiApplication>
|
||||
#include <QStyle>
|
||||
#include <QQuickWindow>
|
||||
|
||||
#include "amneziawebview_desktop_p.h"
|
||||
#include "qrchandler.h"
|
||||
#include "filehandler.h"
|
||||
|
||||
typedef QMap<quintptr, AmneziaWebViewPrivate *> WebViews;
|
||||
Q_GLOBAL_STATIC(WebViews, g_webViews)
|
||||
|
||||
|
||||
QrcHandler::QrcHandler()
|
||||
{}
|
||||
|
||||
|
||||
FileHandler::FileHandler()
|
||||
{
|
||||
}
|
||||
|
||||
JsHandler::JsHandler(AmneziaWebView *host): _host(host), scriptObjectsInjected(false)
|
||||
{
|
||||
init();
|
||||
}
|
||||
|
||||
JsHandler::~JsHandler() {}
|
||||
|
||||
WebPage::WebPage(QObject *parent)
|
||||
: QWebPage(parent)
|
||||
{
|
||||
connect(this, SIGNAL(unsupportedContent(QNetworkReply*)),
|
||||
this, SLOT(handleUnsupportedContent(QNetworkReply*)));
|
||||
}
|
||||
|
||||
void WebPage::javaScriptAlert(QWebFrame *frame, const QString& msg)
|
||||
{
|
||||
Q_UNUSED(frame)
|
||||
Q_UNUSED(msg)
|
||||
}
|
||||
|
||||
WebPage::~WebPage()
|
||||
{
|
||||
disconnect(this);
|
||||
}
|
||||
|
||||
bool WebPage::acceptNavigationRequest(QWebFrame *frame, const QNetworkRequest &request, NavigationType type)
|
||||
{
|
||||
return QWebPage::acceptNavigationRequest(frame, request, type);
|
||||
}
|
||||
|
||||
void WebPage::handleUnsupportedContent(QNetworkReply *reply)
|
||||
{
|
||||
QString errorString = reply->errorString();
|
||||
|
||||
if (m_loadingUrl != reply->url()) {
|
||||
// sub resource of this page
|
||||
qWarning() << "Resource" << reply->url().toEncoded() << "has unknown Content-Type, will be ignored.";
|
||||
reply->deleteLater();
|
||||
return;
|
||||
}
|
||||
|
||||
if (reply->error() == QNetworkReply::NoError && !reply->header(QNetworkRequest::ContentTypeHeader).isValid()) {
|
||||
errorString = "Unknown Content-Type";
|
||||
}
|
||||
|
||||
QFile file(QLatin1String(":/notfound.html"));
|
||||
bool isOpened = file.open(QIODevice::ReadOnly);
|
||||
Q_ASSERT(isOpened);
|
||||
Q_UNUSED(isOpened)
|
||||
|
||||
QString title = QCoreApplication::translate("webview", "Error loading page: %1").arg(reply->url().toString());
|
||||
QString html = QString(QLatin1String(file.readAll()))
|
||||
.arg(title)
|
||||
.arg(errorString)
|
||||
.arg(reply->url().toString());
|
||||
|
||||
QBuffer imageBuffer;
|
||||
imageBuffer.open(QBuffer::ReadWrite);
|
||||
QIcon icon = view()->style()->standardIcon(QStyle::SP_MessageBoxWarning, nullptr, view());
|
||||
QPixmap pixmap = icon.pixmap(QSize(32,32));
|
||||
if (pixmap.save(&imageBuffer, "PNG")) {
|
||||
html.replace(QLatin1String("IMAGE_BINARY_DATA_HERE"),
|
||||
QString(QLatin1String(imageBuffer.buffer().toBase64())));
|
||||
}
|
||||
|
||||
QList<QWebFrame*> frames;
|
||||
frames.append(mainFrame());
|
||||
while (!frames.isEmpty()) {
|
||||
QWebFrame *frame = frames.takeFirst();
|
||||
if (frame->url() == reply->url()) {
|
||||
frame->setHtml(html, reply->url());
|
||||
return;
|
||||
}
|
||||
QList<QWebFrame *> children = frame->childFrames();
|
||||
foreach(QWebFrame *frame, children)
|
||||
frames.append(frame);
|
||||
}
|
||||
if (m_loadingUrl == reply->url()) {
|
||||
mainFrame()->setHtml(html, reply->url());
|
||||
}
|
||||
}
|
||||
|
||||
DesktopWebViewPrivate::DesktopWebViewPrivate(AmneziaWebView* q): AmneziaWebViewPrivate(q)
|
||||
, viewId(reinterpret_cast<quintptr>(this))
|
||||
, containerWindow(nullptr)
|
||||
, window(nullptr)
|
||||
{
|
||||
container = new QWidget(0, Qt::FramelessWindowHint | Qt::NoDropShadowWindowHint | Qt::Tool);
|
||||
container->setAttribute(Qt::WA_NativeWindow, true);
|
||||
container->setAttribute(Qt::WA_DontCreateNativeAncestors, true);
|
||||
|
||||
// Do not remove next line -> prevent some sort of spontaneous crashes
|
||||
QWebSettings::setObjectCacheCapacities(0, 0, 0);
|
||||
|
||||
view = new QWebView(container);
|
||||
WebPage *page = new WebPage(view);
|
||||
page->setForwardUnsupportedContent(true);
|
||||
page->setNetworkAccessManager(networkAccessManager());
|
||||
page->settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, true);
|
||||
view->setPage(page);
|
||||
|
||||
container->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
|
||||
container->setLayout(new QHBoxLayout(container));
|
||||
container->layout()->setSpacing(0);
|
||||
container->layout()->setMargin(0);
|
||||
container->layout()->addWidget(view);
|
||||
|
||||
setBackgroundColor(backgroundColor);
|
||||
g_webViews->insert(viewId, this);
|
||||
|
||||
connect(view, SIGNAL(loadFinished(bool)), this, SIGNAL(loadFinished(bool)));
|
||||
|
||||
connect(page, SIGNAL(loadFinished(bool)), this, SLOT(onLoadFinished(bool)), Qt::QueuedConnection);
|
||||
connect(page, SIGNAL(loadStarted()), this, SLOT(onPageStarted()), Qt::QueuedConnection);
|
||||
connect(view, SIGNAL(urlChanged(const QUrl &)), this, SLOT(onUrlChanged(const QUrl &)), Qt::QueuedConnection);
|
||||
container->createWinId();
|
||||
}
|
||||
|
||||
DesktopWebViewPrivate::~DesktopWebViewPrivate()
|
||||
{
|
||||
disconnect(this, SLOT(loadFinished(bool)));
|
||||
disconnect(this, SLOT(applicationStateChanged(Qt::ApplicationState)));
|
||||
disconnect(this, SLOT(onUrlChanged(const QUrl &)));
|
||||
disconnect(this, SLOT(onPageStarted()));
|
||||
disconnect(this, SLOT(onLoadFinished(bool)));
|
||||
|
||||
g_webViews->take(viewId);
|
||||
view->stop();
|
||||
view->setPage(nullptr);
|
||||
|
||||
container->deleteLater();
|
||||
}
|
||||
|
||||
AmneziaWebViewPrivate *AmneziaWebViewPrivate::create(AmneziaWebView *q)
|
||||
{
|
||||
return new DesktopWebViewPrivate(q);
|
||||
}
|
||||
|
||||
void DesktopWebViewPrivate::setWindowParent(QWindow *parent)
|
||||
{
|
||||
if (window) {
|
||||
window->removeEventFilter(this);
|
||||
}
|
||||
|
||||
if (parent) {
|
||||
|
||||
containerWindow = qobject_cast<QWindow*>(container->windowHandle());
|
||||
containerWindow->setTransientParent(parent);
|
||||
parent->installEventFilter(this);
|
||||
|
||||
}
|
||||
window = parent;
|
||||
}
|
||||
|
||||
void DesktopWebViewPrivate::setBackgroundColor(const QColor backgroundColor)
|
||||
{
|
||||
this->backgroundColor = backgroundColor;
|
||||
QPalette p = container->palette();
|
||||
p.setColor(QPalette::Background, backgroundColor);
|
||||
container->setPalette(p);
|
||||
p = view->palette();
|
||||
p.setColor(QPalette::Background, backgroundColor);
|
||||
view->setPalette(p);
|
||||
emit backgroundColorChanged();
|
||||
}
|
||||
|
||||
/// Deprecated
|
||||
void DesktopWebViewPrivate::setScale(qreal scale)
|
||||
{
|
||||
Q_UNUSED(scale)
|
||||
//qreal s = view->geometry().width() / view->page()->preferredContentsSize().width();
|
||||
//view->setZoomFactor(s);
|
||||
}
|
||||
|
||||
/// Deprecated
|
||||
qreal DesktopWebViewPrivate::scale() const
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
QIcon DesktopWebViewPrivate::icon() const
|
||||
{
|
||||
return QIcon();
|
||||
}
|
||||
|
||||
QSize DesktopWebViewPrivate::contentsSize() const
|
||||
{
|
||||
return QSize();
|
||||
}
|
||||
|
||||
void DesktopWebViewPrivate::takeSnapshot()
|
||||
{
|
||||
if (geometry.isEmpty() || !containerWindow) {
|
||||
return;
|
||||
}
|
||||
else {
|
||||
|
||||
container->updateGeometry();
|
||||
QPixmap pixmap = container->grab();
|
||||
snapshot = pixmap.toImage();
|
||||
emit snapshotChanged();
|
||||
}
|
||||
}
|
||||
|
||||
void DesktopWebViewPrivate::setGeometry(const QRect &geometry)
|
||||
{
|
||||
Q_Q(AmneziaWebView);
|
||||
QQuickWindow *window = q->window();
|
||||
if (!window) return;
|
||||
QRect newGeometry = QRect(window->mapToGlobal(geometry.topLeft()), QSize(geometry.width(), geometry.height()));
|
||||
if (newGeometry.isValid() && container->geometry() != newGeometry ) {
|
||||
|
||||
this->geometry = geometry;
|
||||
container->setGeometry(newGeometry);
|
||||
container->updateGeometry();
|
||||
}
|
||||
}
|
||||
|
||||
bool DesktopWebViewPrivate::eventFilter(QObject *obj, QEvent *event)
|
||||
{
|
||||
Q_UNUSED(obj)
|
||||
Q_Q(AmneziaWebView);
|
||||
|
||||
switch (event->type()) {
|
||||
case QEvent::Move: {
|
||||
QMoveEvent *moveEvent = static_cast<QMoveEvent*>(event);
|
||||
QPoint p = q->mapToScene(QPointF(moveEvent->pos())).toPoint();
|
||||
container->move(p);
|
||||
//container->updateGeometry();
|
||||
|
||||
if (visible) {
|
||||
show();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
case QEvent::Resize: {
|
||||
|
||||
//QRect newGeometry = QRect(window->mapToGlobal(geometry.topLeft()), QSize(geometry.width(), geometry.height()));
|
||||
//container->setGeometry(newGeometry);
|
||||
//container->updateGeometry();
|
||||
|
||||
if (visible) {
|
||||
show();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
case QEvent::WindowStateChange: {
|
||||
|
||||
Qt::WindowState state = window->windowState();
|
||||
if ((state == Qt::WindowMaximized) || (state == Qt::WindowFullScreen) || (state == Qt::WindowActive)) {
|
||||
show();
|
||||
}
|
||||
else {
|
||||
hide();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
default: {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void DesktopWebViewPrivate::hide()
|
||||
{
|
||||
Q_Q(AmneziaWebView);
|
||||
if (!q->window()) return;
|
||||
|
||||
if (visible) {
|
||||
|
||||
QMetaObject::invokeMethod(this, "requestSnapshot", Qt::QueuedConnection);
|
||||
QMetaObject::invokeMethod(container, "hide", Qt::QueuedConnection);
|
||||
visible = false;
|
||||
|
||||
//if (q->isVisible())
|
||||
// q->update();
|
||||
}
|
||||
}
|
||||
|
||||
void DesktopWebViewPrivate::show()
|
||||
{
|
||||
Q_Q(AmneziaWebView);
|
||||
if (!q->window()) return;
|
||||
if (!visible) {
|
||||
|
||||
QMetaObject::invokeMethod(container, "show", Qt::QueuedConnection);
|
||||
QMetaObject::invokeMethod(container, "update", Qt::QueuedConnection);
|
||||
visible = true;
|
||||
}
|
||||
|
||||
if ((qApp->topLevelWindows().at(0) != containerWindow) || !containerWindow->isVisible()) {
|
||||
|
||||
containerWindow->raise();
|
||||
}
|
||||
}
|
||||
|
||||
void DesktopWebViewPrivate::load(const QUrl& baseUrl)
|
||||
{
|
||||
QUrl url = baseUrl;
|
||||
if (!url.isValid()) {
|
||||
url = QUrl(QLatin1String("about:blank"));
|
||||
}
|
||||
view->load(url);
|
||||
history()->append(baseUrl);
|
||||
}
|
||||
|
||||
void DesktopWebViewPrivate::setContent(const QByteArray& data, const QString& mimeType, const QUrl& baseUrl)
|
||||
{
|
||||
QUrl url = baseUrl;
|
||||
if (!url.isValid()) {
|
||||
url = QUrl(QLatin1String("about:blank"));
|
||||
}
|
||||
view->setContent(data, mimeType, url);
|
||||
history()->append(url, data, mimeType);
|
||||
}
|
||||
|
||||
void DesktopWebViewPrivate::setHtml(const QString& html, const QUrl& baseUrl)
|
||||
{
|
||||
if(html.isNull()) return;
|
||||
QUrl url = baseUrl;
|
||||
if (!baseUrl.isValid())
|
||||
url = QUrl(QLatin1String("about:blank"));
|
||||
|
||||
view->setHtml(html, url);
|
||||
history()->append(url, html.toUtf8(), "text/html");
|
||||
}
|
||||
|
||||
void DesktopWebViewPrivate::evaluateJavaScript(const QString& scriptSource)
|
||||
{
|
||||
view->page()->mainFrame()->evaluateJavaScript(scriptSource);
|
||||
}
|
||||
|
||||
bool DesktopWebViewPrivate::canGoBack() const
|
||||
{
|
||||
QAction *pageAction = view->pageAction(QWebPage::Back);
|
||||
bool can = (pageAction && pageAction->isEnabled());
|
||||
return can;
|
||||
}
|
||||
|
||||
bool DesktopWebViewPrivate::canGoForward() const
|
||||
{
|
||||
QAction *pageAction = view->pageAction(QWebPage::Forward);
|
||||
bool can = (pageAction && pageAction->isEnabled());
|
||||
return can;
|
||||
}
|
||||
|
||||
void DesktopWebViewPrivate::back()
|
||||
{
|
||||
QAction *pageAction = view->pageAction(QWebPage::Back);
|
||||
if (pageAction)
|
||||
emit pageAction->trigger();
|
||||
}
|
||||
|
||||
void DesktopWebViewPrivate::forward()
|
||||
{
|
||||
QAction *pageAction = view->pageAction(QWebPage::Forward);
|
||||
if (pageAction)
|
||||
emit pageAction->trigger();
|
||||
}
|
||||
|
||||
void DesktopWebViewPrivate::reload()
|
||||
{
|
||||
QAction *pageAction = view->pageAction(QWebPage::Reload);
|
||||
if (pageAction)
|
||||
emit pageAction->trigger();
|
||||
}
|
||||
|
||||
void DesktopWebViewPrivate::stop()
|
||||
{
|
||||
QAction *pageAction = view->pageAction(QWebPage::Stop);
|
||||
if (pageAction)
|
||||
emit pageAction->trigger();
|
||||
}
|
||||
|
||||
bool DesktopWebViewPrivate::isLoading() const
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
QString DesktopWebViewPrivate::innerHTML() const
|
||||
{
|
||||
QVariant result = view->page()->mainFrame()->evaluateJavaScript("document.body.innerHTML");
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
void DesktopWebViewPrivate::onLoadFinished(bool success)
|
||||
{
|
||||
if (success) {
|
||||
QMetaObject::invokeMethod(this, "onPageFinished", Qt::QueuedConnection);
|
||||
}
|
||||
else {
|
||||
QMetaObject::invokeMethod(this, "onPageError", Qt::QueuedConnection);
|
||||
}
|
||||
}
|
||||
|
||||
void DesktopWebViewPrivate::setDefaultFontSize(int size)
|
||||
{
|
||||
view->settings()->setFontSize(QWebSettings::DefaultFontSize, size);
|
||||
}
|
||||
|
||||
void DesktopWebViewPrivate::setStandardFontFamily(const QString &family)
|
||||
{
|
||||
view->settings()->setFontFamily(QWebSettings::StandardFont, family);
|
||||
}
|
||||
|
||||
void DesktopWebViewPrivate::setTextZoom(int percent)
|
||||
{
|
||||
Q_UNUSED(percent)
|
||||
}
|
||||
@@ -1,96 +0,0 @@
|
||||
#ifndef AMNEZIAWEBVIEW_DESKTOP_P_H
|
||||
#define AMNEZIAWEBVIEW_DESKTOP_P_H
|
||||
|
||||
// QtWebKit is deprecated and not available in Qt 6
|
||||
// This file should only be used with Qt 5 when WebEngineWidgets is not available
|
||||
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
|
||||
#error "amneziawebview_desktop_p.h uses QtWebKit which is not available in Qt 6. Use amneziawebview_webengine_p.h instead."
|
||||
#endif
|
||||
|
||||
#include <QtWebKitWidgets/QWebView>
|
||||
#include <QtWebKitWidgets/QWebPage>
|
||||
#include <QtWebKitWidgets/QWebFrame>
|
||||
#include <QtWebKit/QWebSettings>
|
||||
|
||||
#include "amneziawebview.h"
|
||||
#include "amneziawebview_p.h"
|
||||
|
||||
class DesktopWebViewPrivate;
|
||||
|
||||
class WebPage : public QWebPage
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
signals:
|
||||
void loadingUrl(const QUrl &url);
|
||||
|
||||
public:
|
||||
explicit WebPage(QObject *parent = nullptr);
|
||||
virtual ~WebPage();
|
||||
|
||||
protected:
|
||||
bool acceptNavigationRequest(QWebFrame *frame, const QNetworkRequest &request, NavigationType type);
|
||||
virtual void javaScriptAlert(QWebFrame *frame, const QString& msg);
|
||||
|
||||
private slots:
|
||||
void handleUnsupportedContent(QNetworkReply *reply);
|
||||
|
||||
private:
|
||||
|
||||
friend class DesktopWebViewPrivate;
|
||||
QUrl m_loadingUrl;
|
||||
};
|
||||
|
||||
class DesktopWebViewPrivate : public AmneziaWebViewPrivate
|
||||
{
|
||||
Q_OBJECT
|
||||
Q_DECLARE_PUBLIC(AmneziaWebView)
|
||||
public:
|
||||
|
||||
explicit DesktopWebViewPrivate(AmneziaWebView* q);
|
||||
virtual ~DesktopWebViewPrivate();
|
||||
|
||||
virtual void setWindowParent(QWindow *parent);
|
||||
|
||||
virtual void setBackgroundColor(const QColor backgroundColor);
|
||||
virtual void show();
|
||||
virtual void hide();
|
||||
virtual void takeSnapshot();
|
||||
virtual void setGeometry(const QRect &);
|
||||
virtual QString innerHTML() const;
|
||||
virtual void load(const QUrl& url);
|
||||
virtual void setHtml(const QString& html, const QUrl& baseUrl = QUrl());
|
||||
virtual void setContent(const QByteArray& data, const QString& mimeType, const QUrl& baseUrl);
|
||||
virtual void evaluateJavaScript(const QString& scriptSource);
|
||||
virtual bool isLoading() const;
|
||||
virtual bool canGoBack() const;
|
||||
virtual bool canGoForward() const;
|
||||
virtual void back();
|
||||
virtual void forward();
|
||||
virtual void reload();
|
||||
virtual void stop();
|
||||
|
||||
virtual QIcon icon() const;
|
||||
virtual void setScale(qreal scale);
|
||||
virtual qreal scale() const;
|
||||
virtual QSize contentsSize() const;
|
||||
virtual void setDefaultFontSize(int size);
|
||||
virtual void setTextZoom(int percent) { Q_UNUSED(percent); }
|
||||
virtual void setStandardFontFamily(const QString &family);
|
||||
|
||||
protected:
|
||||
bool eventFilter(QObject *obj, QEvent *event);
|
||||
|
||||
private slots:
|
||||
void onLoadFinished(bool);
|
||||
|
||||
private:
|
||||
quintptr viewId;
|
||||
QWebView *view;
|
||||
QWidget *container;
|
||||
QWindow *containerWindow;
|
||||
QWindow *window;
|
||||
};
|
||||
|
||||
|
||||
#endif // AMNEZIAWEBVIEW_DESKTOP_P_H
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,423 +0,0 @@
|
||||
#include "amneziawebview_p.h"
|
||||
#include "amneziawebhistory.h"
|
||||
#include "websettings.h"
|
||||
|
||||
NetworkAccessManager::NetworkAccessManager(QNetworkAccessManager *manager, QObject *parent)
|
||||
: QNetworkAccessManager(parent)
|
||||
{
|
||||
this->manager = manager;
|
||||
setCache(manager->cache());
|
||||
setCookieJar(manager->cookieJar());
|
||||
setProxy(manager->proxy());
|
||||
setProxyFactory(manager->proxyFactory());
|
||||
|
||||
init();
|
||||
}
|
||||
|
||||
void NetworkAccessManager::init()
|
||||
{
|
||||
connect(this, SIGNAL(sslErrors(QNetworkReply*, const QList<QSslError> & )), this,
|
||||
SLOT(handleSslErrors(QNetworkReply*, const QList<QSslError> & )));
|
||||
}
|
||||
|
||||
QNetworkReply *NetworkAccessManager::createRequest(QNetworkAccessManager::Operation operation, const QNetworkRequest &request, QIODevice *device)
|
||||
{
|
||||
AmneziaWebView *view = qobject_cast<AmneziaWebView *>(parent());
|
||||
AmneziaWebViewPrivate *d = AmneziaWebViewPrivate::get(view);
|
||||
|
||||
if (!d || !d->canHandleUrl(request.url())) {
|
||||
return QNetworkAccessManager::createRequest(operation, request, device);
|
||||
}
|
||||
|
||||
if (operation == GetOperation) {
|
||||
return new DataReply(this, operation, request, view);
|
||||
}
|
||||
else
|
||||
|
||||
return QNetworkAccessManager::createRequest(operation, request, device);
|
||||
}
|
||||
|
||||
void NetworkAccessManager::handleSslErrors(QNetworkReply* reply, const QList<QSslError> &errors)
|
||||
{
|
||||
Q_UNUSED(errors)
|
||||
reply->ignoreSslErrors();
|
||||
}
|
||||
|
||||
DataReply::DataReply(QObject *parent, const QNetworkAccessManager::Operation operation, const QNetworkRequest &request, AmneziaWebView *view): QNetworkReply(parent)
|
||||
{
|
||||
setRequest(request);
|
||||
setUrl(request.url());
|
||||
setOperation(operation);
|
||||
setFinished(true);
|
||||
this->view = view;
|
||||
offset = 0;
|
||||
|
||||
//QUrl url = request.url();
|
||||
//url.setHost(QString());
|
||||
//if (url.path().isEmpty())
|
||||
// url.setPath(QLatin1String("/"));
|
||||
//setUrl(url);
|
||||
|
||||
QMetaObject::invokeMethod(this, "setContent", Qt::QueuedConnection );
|
||||
}
|
||||
|
||||
void DataReply::setContent()
|
||||
{
|
||||
if (!view || view.isNull()) return;
|
||||
|
||||
AmneziaWebViewPrivate *q = AmneziaWebViewPrivate::get(view);
|
||||
content = q->dataForUrl(url());
|
||||
QString mimeType = q->mimeTypeForUrl(url()).toLower();
|
||||
//open(ReadOnly | Unbuffered);
|
||||
QNetworkReply::open(QIODevice::ReadOnly);
|
||||
|
||||
int size = content.size();
|
||||
if (size <= 0 ) {
|
||||
|
||||
QString msg = QString("Error opening %1").arg(url().toString());
|
||||
qCritical() << msg;
|
||||
setError(QNetworkReply::ContentNotFoundError, msg);
|
||||
QMetaObject::invokeMethod(this, "error", Qt::QueuedConnection,
|
||||
Q_ARG(QNetworkReply::NetworkError, QNetworkReply::ContentNotFoundError));
|
||||
|
||||
QMetaObject::invokeMethod(this, "finished", Qt::QueuedConnection);
|
||||
return;
|
||||
}
|
||||
|
||||
setHeader(QNetworkRequest::ContentTypeHeader, QVariant(QString("%1; charset=%2").arg(mimeType, "utf-8")));
|
||||
|
||||
setHeader(QNetworkRequest::ContentLengthHeader, size);
|
||||
QMetaObject::invokeMethod(this, "metaDataChanged", Qt::QueuedConnection);
|
||||
QMetaObject::invokeMethod(this, "downloadProgress", Qt::QueuedConnection,
|
||||
Q_ARG(qint64, size), Q_ARG(qint64, size));
|
||||
QMetaObject::invokeMethod(this, "readyRead", Qt::QueuedConnection);
|
||||
QMetaObject::invokeMethod(this, "finished", Qt::QueuedConnection);
|
||||
}
|
||||
|
||||
void DataReply::abort()
|
||||
{
|
||||
QNetworkReply::close();
|
||||
}
|
||||
|
||||
void DataReply::close()
|
||||
{
|
||||
QNetworkReply::close();
|
||||
}
|
||||
|
||||
qint64 DataReply::size() const
|
||||
{
|
||||
return content.size();
|
||||
}
|
||||
|
||||
bool DataReply::isSequential() const
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
qint64 DataReply::bytesAvailable() const
|
||||
{
|
||||
return content.size() - offset + QIODevice::bytesAvailable();
|
||||
}
|
||||
qint64 DataReply::readData(char *data, qint64 maxSize)
|
||||
{
|
||||
if (offset < content.size()) {
|
||||
qint64 number = qMin(maxSize, content.size() - offset);
|
||||
memcpy(data, content.constData() + offset, number);
|
||||
offset += number;
|
||||
return number;
|
||||
} else {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
AmneziaWebViewPrivate::AmneziaWebViewPrivate(AmneziaWebView *q) : QObject(q)
|
||||
, pending(PendingNone)
|
||||
, status(AmneziaWebView::Null)
|
||||
, preferredwidth(0)
|
||||
, preferredheight(0)
|
||||
, progress(1.0)
|
||||
, newWindowComponent(nullptr)
|
||||
, newWindowParent(nullptr)
|
||||
, jsHandler(q)
|
||||
, rendering(true)
|
||||
, overlapped(false)
|
||||
, backgroundColor(QColor::fromRgb(28, 29, 33))
|
||||
, visible(false)
|
||||
, networkManager(nullptr)
|
||||
, q_ptr(q)
|
||||
, m_history(new AmneziaWebHistory(q))
|
||||
, m_settings(new AmneziaWebViewSettings(q))
|
||||
{
|
||||
}
|
||||
|
||||
void AmneziaWebViewPrivate::init()
|
||||
{
|
||||
Q_Q(AmneziaWebView);
|
||||
m_settings->apply();
|
||||
|
||||
actions.setMapping(new QAction(q), (int)AmneziaWebView::Back);
|
||||
actions.setMapping(new QAction(q), (int)AmneziaWebView::Forward);
|
||||
actions.setMapping(new QAction(q), (int)AmneziaWebView::Stop);
|
||||
actions.setMapping(new QAction(q), (int)AmneziaWebView::Reload);
|
||||
connect(action(AmneziaWebView::Back), SIGNAL(triggered()), &actions, SLOT(map()));
|
||||
connect(action(AmneziaWebView::Forward), SIGNAL(triggered()), &actions, SLOT(map()));
|
||||
connect(action(AmneziaWebView::Forward), SIGNAL(triggered()), &actions, SLOT(map()));
|
||||
connect(action(AmneziaWebView::Forward), SIGNAL(triggered()), &actions, SLOT(map()));
|
||||
connect(&actions, SIGNAL(mappedInt(int)), this, SLOT(onAction(int)));
|
||||
connect(qApp, SIGNAL(applicationStateChanged(Qt::ApplicationState)), this, SLOT(applicationStateChanged(Qt::ApplicationState)));
|
||||
}
|
||||
|
||||
AmneziaWebViewPrivate::~AmneziaWebViewPrivate()
|
||||
{
|
||||
Q_Q(AmneziaWebView);
|
||||
disconnect(this, SLOT(onAction(int)));
|
||||
disconnect(&actions, SLOT(map()));
|
||||
if (networkManager && networkManager->parent() == q)
|
||||
delete networkManager;
|
||||
}
|
||||
|
||||
AmneziaWebViewPrivate *AmneziaWebViewPrivate::get(AmneziaWebView *q)
|
||||
{
|
||||
if (!q) { return nullptr; }
|
||||
return q->d_func();
|
||||
}
|
||||
|
||||
void AmneziaWebViewPrivate::applicationStateChanged(Qt::ApplicationState state)
|
||||
{
|
||||
Q_Q(AmneziaWebView);
|
||||
if ((state == Qt::ApplicationActive) && q->isVisible()) {
|
||||
emit q->update();
|
||||
}
|
||||
else {
|
||||
hide();
|
||||
}
|
||||
}
|
||||
|
||||
void AmneziaWebViewPrivate::requestShow()
|
||||
{
|
||||
show();
|
||||
}
|
||||
|
||||
void AmneziaWebViewPrivate::requestHide()
|
||||
{
|
||||
hide();
|
||||
}
|
||||
|
||||
void AmneziaWebViewPrivate::move(const QPoint &point)
|
||||
{
|
||||
QRect newGeomentry = geometry;
|
||||
newGeomentry.moveTo(point);
|
||||
setGeometry(newGeomentry);
|
||||
}
|
||||
|
||||
void AmneziaWebViewPrivate::windowObjectsClear(QQmlListProperty<QObject>* prop)
|
||||
{
|
||||
static_cast<AmneziaWebViewPrivate*>(prop->data)->windowObjects.clear();
|
||||
}
|
||||
|
||||
QObject *AmneziaWebViewPrivate::windowObjectsAt(QQmlListProperty<QObject> *prop, qsizetype index)
|
||||
{
|
||||
return static_cast<AmneziaWebViewPrivate *>(prop->data)->windowObjects.at(index);
|
||||
}
|
||||
|
||||
qsizetype AmneziaWebViewPrivate::windowObjectsCount(QQmlListProperty<QObject> *prop)
|
||||
{
|
||||
return static_cast<AmneziaWebViewPrivate *>(prop->data)->windowObjects.count();
|
||||
}
|
||||
|
||||
void AmneziaWebViewPrivate::windowObjectsAppend(QQmlListProperty<QObject>* prop, QObject* o)
|
||||
{
|
||||
static_cast<AmneziaWebViewPrivate*>(prop->data)->windowObjects.append(o);
|
||||
static_cast<AmneziaWebViewPrivate*>(prop->data)->updateWindowObjects();
|
||||
}
|
||||
|
||||
void AmneziaWebViewPrivate::setTitle(const QString &title)
|
||||
{
|
||||
Q_Q(AmneziaWebView);
|
||||
if (this->title != title) {
|
||||
this->title = title;
|
||||
emit q->titleChanged(this->title);
|
||||
}
|
||||
}
|
||||
|
||||
QByteArray AmneziaWebViewPrivate::dataForUrl(const QUrl &url) const
|
||||
{
|
||||
QByteArray data;
|
||||
if (qrcHandler.canHandleUrl(url)) {
|
||||
data = qrcHandler.dataForUrl(url);
|
||||
}
|
||||
else if (jsHandler.canHandleUrl(url)) {
|
||||
|
||||
data = jsHandler.dataForUrl(url);
|
||||
}
|
||||
else if (fileHandler.canHandleUrl(url)) {
|
||||
|
||||
data = fileHandler.dataForUrl(url);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
QString AmneziaWebViewPrivate::mimeTypeForUrl(const QUrl &url) const
|
||||
{
|
||||
QString mimeType("application/octet-stream");
|
||||
if (qrcHandler.canHandleUrl(url)) {
|
||||
mimeType = qrcHandler.mimeTypeForUrl(url);
|
||||
}
|
||||
else if (jsHandler.canHandleUrl(url)) {
|
||||
mimeType = jsHandler.mimeTypeForUrl(url);
|
||||
}
|
||||
else if (fileHandler.canHandleUrl(url)) {
|
||||
mimeType = fileHandler.mimeTypeForUrl(url);
|
||||
}
|
||||
return mimeType;
|
||||
}
|
||||
|
||||
void AmneziaWebViewPrivate::onPageStarted()
|
||||
{
|
||||
Q_Q(AmneziaWebView);
|
||||
emit q->loadStarted();
|
||||
}
|
||||
|
||||
void AmneziaWebViewPrivate::onPageFinished()
|
||||
{
|
||||
Q_Q(AmneziaWebView);
|
||||
jsHandler.updateWebView();
|
||||
|
||||
if (lastError.length() > 0) {
|
||||
emit q->loadFinished(false);
|
||||
}
|
||||
else {
|
||||
emit q->loadFinished(true);
|
||||
}
|
||||
}
|
||||
|
||||
void AmneziaWebViewPrivate::onPageError()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
void AmneziaWebViewPrivate::onUrlChanged(const QUrl &url)
|
||||
{
|
||||
history()->append(url);
|
||||
setUrl(url);
|
||||
}
|
||||
|
||||
void AmneziaWebViewPrivate::setUrl(const QUrl &url)
|
||||
{
|
||||
Q_Q(AmneziaWebView);
|
||||
|
||||
QString urlString = url.toString();
|
||||
while ( urlString.endsWith('#')) urlString.chop(1);
|
||||
QUrl newUrl(urlString);
|
||||
|
||||
if (newUrl == QUrl(QLatin1String("about:blank")) ) {
|
||||
newUrl = QUrl("");
|
||||
}
|
||||
|
||||
if (this->url != newUrl) {
|
||||
|
||||
this->url = newUrl;
|
||||
emit q->urlChanged();
|
||||
}
|
||||
}
|
||||
|
||||
void AmneziaWebViewPrivate::addToJavaScriptWindowObject(const QString& name, QObject* object)
|
||||
{
|
||||
jsHandler.addToJavaScriptWindowObject(name, object);
|
||||
}
|
||||
|
||||
|
||||
bool AmneziaWebViewPrivate::canHandleUrl(const QUrl &url) const
|
||||
{
|
||||
bool can = (jsHandler.canHandleUrl(url) || qrcHandler.canHandleUrl(url) || fileHandler.canHandleUrl(url));
|
||||
return can;
|
||||
}
|
||||
|
||||
QString AmneziaWebViewPrivate::toHtml() const
|
||||
{
|
||||
return QString();
|
||||
}
|
||||
|
||||
void AmneziaWebViewPrivate::load(const QNetworkRequest& request, QNetworkAccessManager::Operation operation, const QByteArray& body)
|
||||
{
|
||||
Q_UNUSED(request)
|
||||
Q_UNUSED(operation)
|
||||
Q_UNUSED(body)
|
||||
}
|
||||
|
||||
QNetworkAccessManager* AmneziaWebViewPrivate::networkAccessManager()
|
||||
{
|
||||
Q_Q(AmneziaWebView);
|
||||
|
||||
if (!networkManager)
|
||||
networkManager = new NetworkAccessManager(q);
|
||||
return networkManager;
|
||||
}
|
||||
|
||||
void AmneziaWebViewPrivate::setNetworkAccessManager(QNetworkAccessManager* manager)
|
||||
{
|
||||
Q_Q(AmneziaWebView);
|
||||
if (manager == networkManager)
|
||||
return;
|
||||
if (networkManager && networkManager->parent() == q)
|
||||
delete networkManager;
|
||||
|
||||
NetworkAccessManager *newManager = qobject_cast<NetworkAccessManager *>(manager);
|
||||
if (!newManager && manager) {
|
||||
newManager = new NetworkAccessManager(manager, q);
|
||||
}
|
||||
networkManager = newManager;
|
||||
}
|
||||
|
||||
QAction *AmneziaWebViewPrivate::action(AmneziaWebView::WebAction action) const
|
||||
{
|
||||
QAction *ret = qobject_cast<QAction*>(actions.mapping((int)action));
|
||||
if (ret) {
|
||||
switch (action) {
|
||||
case AmneziaWebView::Back: {
|
||||
bool can = canGoBack() || history()->canGoBack();
|
||||
ret->setEnabled(can);
|
||||
}
|
||||
break;
|
||||
case AmneziaWebView::Forward: {
|
||||
bool can = canGoForward() || history()->canGoForward();
|
||||
ret->setEnabled(can);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
void AmneziaWebViewPrivate::onAction(int action)
|
||||
{
|
||||
switch (action) {
|
||||
case AmneziaWebView::Back: {
|
||||
if (canGoBack()) {
|
||||
back();
|
||||
}
|
||||
//else {
|
||||
// history()->back();
|
||||
//}
|
||||
}
|
||||
break;
|
||||
case AmneziaWebView::Forward:
|
||||
if (canGoForward()) forward();
|
||||
break;
|
||||
case AmneziaWebView::Stop:
|
||||
stop();
|
||||
break;
|
||||
case AmneziaWebView::Reload:
|
||||
reload();
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
AmneziaWebHistory* AmneziaWebViewPrivate::history() const
|
||||
{
|
||||
return m_history.data();
|
||||
}
|
||||
@@ -1,187 +0,0 @@
|
||||
#ifndef WEBVIEW_P_H
|
||||
#define WEBVIEW_P_H
|
||||
|
||||
#include "amneziawebview.h"
|
||||
#include "qrchandler.h"
|
||||
#include "jshandler.h"
|
||||
#include "filehandler.h"
|
||||
|
||||
#include "amneziawebhistory.h"
|
||||
|
||||
class WebSettings;
|
||||
class QIcon;
|
||||
class QSize;
|
||||
|
||||
|
||||
class WebViewSettings;
|
||||
class WebSettings;
|
||||
|
||||
class AmneziaWebViewPrivate : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
Q_DECLARE_PUBLIC(AmneziaWebView)
|
||||
|
||||
public:
|
||||
explicit AmneziaWebViewPrivate(AmneziaWebView *q);
|
||||
virtual ~AmneziaWebViewPrivate();
|
||||
static AmneziaWebViewPrivate *create(AmneziaWebView *q);
|
||||
void init();
|
||||
|
||||
virtual void setWindowParent(QWindow *parent) = 0;
|
||||
virtual void setBackgroundColor(const QColor backgroundColor) = 0;
|
||||
|
||||
virtual void setGeometry(const QRect &) = 0;
|
||||
virtual QString innerHTML() const = 0;
|
||||
virtual void load(const QUrl& url) = 0;
|
||||
virtual void setHtml(const QString& html, const QUrl& baseUrl = QUrl()) = 0;
|
||||
virtual void setContent(const QByteArray& data, const QString& mimeType, const QUrl& baseUrl) = 0;
|
||||
virtual void evaluateJavaScript(const QString& scriptSource) = 0;
|
||||
virtual bool isLoading() const = 0;
|
||||
virtual bool canGoBack() const = 0;
|
||||
virtual bool canGoForward() const = 0;
|
||||
virtual void back() = 0;
|
||||
virtual void forward() = 0;
|
||||
virtual void reload() = 0;
|
||||
virtual void stop() = 0;
|
||||
virtual QIcon icon() const = 0;
|
||||
virtual void setScale(qreal scale) = 0;
|
||||
virtual qreal scale() const = 0;
|
||||
virtual QSize contentsSize() const = 0;
|
||||
virtual void show() = 0;
|
||||
virtual void hide() = 0;
|
||||
virtual void setDefaultFontSize(int size) = 0;
|
||||
virtual void setStandardFontFamily(const QString &family) = 0;
|
||||
virtual void setTextZoom(int percent) = 0;
|
||||
|
||||
virtual void setUrl(const QUrl &url);
|
||||
|
||||
static AmneziaWebViewPrivate *get(AmneziaWebView *q);
|
||||
|
||||
enum { PendingNone, PendingUrl, PendingHtml, PendingContent } pending;
|
||||
|
||||
QString toHtml() const;
|
||||
AmneziaWebHistory* history() const;
|
||||
|
||||
QByteArray dataForUrl(const QUrl &url) const;
|
||||
QString mimeTypeForUrl(const QUrl &url) const;
|
||||
bool canHandleUrl(const QUrl &url) const;
|
||||
|
||||
static void windowObjectsClear(QQmlListProperty<QObject> *prop);
|
||||
static QObject *windowObjectsAt(QQmlListProperty<QObject> *prop, qsizetype index);
|
||||
static qsizetype windowObjectsCount(QQmlListProperty<QObject> *prop);
|
||||
static void windowObjectsAppend(QQmlListProperty<QObject> *prop, QObject *o);
|
||||
|
||||
void updateWindowObjects();
|
||||
QObjectList windowObjects;
|
||||
|
||||
QNetworkAccessManager* networkAccessManager();
|
||||
void setNetworkAccessManager(QNetworkAccessManager* manager);
|
||||
void load(const QNetworkRequest& request, QNetworkAccessManager::Operation operation, const QByteArray& body);
|
||||
QAction *action(AmneziaWebView::WebAction) const;
|
||||
|
||||
public Q_SLOTS:
|
||||
void setTitle(const QString &title);
|
||||
void move(const QPoint &);
|
||||
void requestHide();
|
||||
void requestShow();
|
||||
|
||||
Q_SIGNALS:
|
||||
void loadStarted();
|
||||
void loadFinished(bool ok);
|
||||
void loadProgress(int progress);
|
||||
void titleChanged(const QString& title);
|
||||
void urlChanged(const QUrl& url);
|
||||
void backgroundColorChanged();
|
||||
public:
|
||||
|
||||
QUrl url;
|
||||
AmneziaWebView::Status status;
|
||||
qreal preferredwidth, preferredheight;
|
||||
qreal progress;
|
||||
QString statusText;
|
||||
QUrl pendingUrl;
|
||||
QString pendingString;
|
||||
QByteArray pendingData;
|
||||
|
||||
QQmlComponent* newWindowComponent;
|
||||
QQuickItem* newWindowParent;
|
||||
|
||||
QrcHandler qrcHandler;
|
||||
JsHandler jsHandler;
|
||||
FileHandler fileHandler;
|
||||
|
||||
bool rendering;
|
||||
bool overlapped;
|
||||
|
||||
QColor backgroundColor;
|
||||
QUrl baseUrl;
|
||||
QString title;
|
||||
QRect geometry;
|
||||
QString lastError;
|
||||
mutable bool visible;
|
||||
|
||||
protected Q_SLOTS:
|
||||
void applicationStateChanged(Qt::ApplicationState state);
|
||||
void onPageStarted();
|
||||
void onPageFinished();
|
||||
void onPageError();
|
||||
void onUrlChanged(const QUrl &url);
|
||||
void onAction(int);
|
||||
|
||||
protected:
|
||||
|
||||
void addToJavaScriptWindowObject(const QString& name, QObject* object);
|
||||
|
||||
QMutex renderMutex;
|
||||
QNetworkAccessManager *networkManager;
|
||||
AmneziaWebView *q_ptr;
|
||||
|
||||
private:
|
||||
QSignalMapper actions;
|
||||
QScopedPointer<AmneziaWebHistory> m_history;
|
||||
QScopedPointer<AmneziaWebViewSettings> m_settings;
|
||||
};
|
||||
|
||||
//!internal
|
||||
class NetworkAccessManager : public QNetworkAccessManager
|
||||
{
|
||||
Q_OBJECT
|
||||
public:
|
||||
explicit NetworkAccessManager(QNetworkAccessManager *manager, QObject *parent);
|
||||
explicit NetworkAccessManager(QObject *parent): QNetworkAccessManager(parent) { init(); }
|
||||
|
||||
public Q_SLOTS:
|
||||
void handleSslErrors(QNetworkReply* reply, const QList<QSslError> &errors);
|
||||
|
||||
protected:
|
||||
virtual QNetworkReply *createRequest(Operation op, const QNetworkRequest &request, QIODevice *outgoingData = nullptr);
|
||||
private:
|
||||
void init();
|
||||
QNetworkAccessManager *manager;
|
||||
};
|
||||
|
||||
class DataReply : public QNetworkReply
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
explicit DataReply(QObject *parent, const QNetworkAccessManager::Operation operation, const QNetworkRequest &request, AmneziaWebView *view = nullptr);
|
||||
virtual ~DataReply() = default;
|
||||
|
||||
virtual void abort();
|
||||
virtual void close();
|
||||
virtual qint64 size() const;
|
||||
|
||||
virtual qint64 bytesAvailable() const;
|
||||
virtual bool isSequential() const;
|
||||
protected:
|
||||
virtual qint64 readData(char *data, qint64 maxSize);
|
||||
Q_INVOKABLE void setContent();
|
||||
|
||||
private:
|
||||
QByteArray content;
|
||||
qint64 offset;
|
||||
QPointer<AmneziaWebView> view;
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -1,494 +0,0 @@
|
||||
#include <QCoreApplication>
|
||||
#include <QWebEngineUrlScheme>
|
||||
|
||||
#include "amneziawebview_webengine_p.h"
|
||||
#include "qrchandler.h"
|
||||
#include "filehandler.h"
|
||||
#include "amneziawebhistory.h"
|
||||
|
||||
typedef QMap<quintptr, AmneziaWebViewPrivate *> WebViews;
|
||||
Q_GLOBAL_STATIC_WITH_ARGS(WebViews, g_webViews, ())
|
||||
|
||||
QrcHandler::QrcHandler()
|
||||
{}
|
||||
|
||||
FileHandler::FileHandler()
|
||||
{
|
||||
}
|
||||
|
||||
JsHandler::JsHandler(AmneziaWebView *host): _host(host), scriptObjectsInjected(false)
|
||||
{
|
||||
init();
|
||||
}
|
||||
|
||||
JsHandler::~JsHandler() {}
|
||||
|
||||
WebPage::WebPage(QObject *parent)
|
||||
: QWebEnginePage(parent)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
WebPage::WebPage(QWebEngineProfile *profile, QObject *parent)
|
||||
: QWebEnginePage(profile, parent)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
WebPage::~WebPage()
|
||||
{
|
||||
disconnect(this);
|
||||
}
|
||||
|
||||
bool WebPage::acceptNavigationRequest(const QUrl &url, QWebEnginePage::NavigationType type, bool isMainFrame)
|
||||
{
|
||||
Q_UNUSED(type);
|
||||
// Always accept navigation requests to open links within WebView
|
||||
// This prevents opening links in external browser
|
||||
if (isMainFrame) {
|
||||
m_loadingUrl = url;
|
||||
emit loadingUrl(url);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
QWebEnginePage *WebPage::createWindow(QWebEnginePage::WebWindowType type)
|
||||
{
|
||||
Q_UNUSED(type);
|
||||
// Return this page instead of creating a new window
|
||||
// This prevents opening new browser windows/tabs
|
||||
return this;
|
||||
}
|
||||
|
||||
void WebPage::handleUnsupportedContent(QNetworkReply *reply)
|
||||
{
|
||||
QString errorString = reply->errorString();
|
||||
|
||||
if (m_loadingUrl != reply->url()) {
|
||||
// sub resource of this page
|
||||
qWarning() << "Resource" << reply->url().toEncoded() << "has unknown Content-Type, will be ignored.";
|
||||
reply->deleteLater();
|
||||
return;
|
||||
}
|
||||
|
||||
if (reply->error() == QNetworkReply::NoError && !reply->header(QNetworkRequest::ContentTypeHeader).isValid()) {
|
||||
errorString = "Unknown Content-Type";
|
||||
}
|
||||
|
||||
QFile file(QLatin1String(":/notfound.html"));
|
||||
bool isOpened = file.open(QIODevice::ReadOnly);
|
||||
Q_ASSERT(isOpened);
|
||||
Q_UNUSED(isOpened)
|
||||
|
||||
QString title = QCoreApplication::translate("webview", "Error loading page: %1").arg(reply->url().toString());
|
||||
QString html = QString(QLatin1String(file.readAll()))
|
||||
.arg(title)
|
||||
.arg(errorString)
|
||||
.arg(reply->url().toString());
|
||||
|
||||
QBuffer imageBuffer;
|
||||
imageBuffer.open(QBuffer::ReadWrite);
|
||||
QIcon icon = qApp->style()->standardIcon(QStyle::SP_MessageBoxWarning, 0);
|
||||
QPixmap pixmap = icon.pixmap(QSize(32,32));
|
||||
if (pixmap.save(&imageBuffer, "PNG")) {
|
||||
html.replace(QLatin1String("IMAGE_BINARY_DATA_HERE"),
|
||||
QString(QLatin1String(imageBuffer.buffer().toBase64())));
|
||||
}
|
||||
|
||||
if (m_loadingUrl == reply->url()) {
|
||||
setHtml(html, reply->url());
|
||||
}
|
||||
}
|
||||
|
||||
const QString &LocalSchemeHandler::scheme()
|
||||
{
|
||||
static const QString localScheme("local");
|
||||
return localScheme;
|
||||
}
|
||||
|
||||
const QMimeDatabase &LocalSchemeHandler::mimeDatabase()
|
||||
{
|
||||
static const QMimeDatabase mimeDatabase;
|
||||
return mimeDatabase;
|
||||
}
|
||||
|
||||
void LocalSchemeHandler::requestStarted(QWebEngineUrlRequestJob *job)
|
||||
{
|
||||
const QByteArray requestMethod = job->requestMethod();
|
||||
const QUrl requestUrl = job->requestUrl();
|
||||
QString requestScheme = requestUrl.scheme();
|
||||
DesktopWebViewPrivate *d = qobject_cast<DesktopWebViewPrivate *>(parent());
|
||||
|
||||
if (!d) {
|
||||
job->fail(QWebEngineUrlRequestJob::RequestFailed);
|
||||
return;
|
||||
}
|
||||
|
||||
if (requestScheme != LocalSchemeHandler::scheme()) {
|
||||
job->fail(QWebEngineUrlRequestJob::UrlInvalid);
|
||||
return;
|
||||
}
|
||||
|
||||
QBuffer *buffer = nullptr;
|
||||
QMimeType mimeType = mimeDatabase().mimeTypeForFile(requestUrl.fileName(), QMimeDatabase::MatchExtension);
|
||||
|
||||
if (d->fileHandler.canHandleUrl(requestUrl)) {
|
||||
const QByteArray content = d->fileHandler.dataForUrl(requestUrl);
|
||||
if (!content.isNull()) {
|
||||
buffer = new QBuffer();
|
||||
buffer->setData(content);
|
||||
}
|
||||
}
|
||||
if (!buffer) {
|
||||
|
||||
auto historyItems = d->history()->items();
|
||||
const auto it = std::find_if(historyItems.begin(), historyItems.end(),
|
||||
[requestUrl](const auto &item) {
|
||||
bool urlsMatch = item.url().matches(requestUrl, QUrl::RemoveQuery | QUrl::RemoveFragment);
|
||||
bool hasData = (item.data().length() > 0);
|
||||
return urlsMatch && hasData; });
|
||||
|
||||
if (it != historyItems.end()) {
|
||||
buffer = new QBuffer();
|
||||
buffer->setData(it->data());
|
||||
mimeType = mimeDatabase().mimeTypeForName(it->mimeType());
|
||||
}
|
||||
}
|
||||
|
||||
if (!buffer) {
|
||||
job->fail(QWebEngineUrlRequestJob::UrlNotFound);
|
||||
return;
|
||||
}
|
||||
|
||||
connect(job, &QObject::destroyed, buffer, &QObject::deleteLater);
|
||||
job->reply(mimeType.name().toLocal8Bit(), buffer);
|
||||
}
|
||||
|
||||
DesktopWebViewPrivate::DesktopWebViewPrivate(AmneziaWebView* q): AmneziaWebViewPrivate(q)
|
||||
, viewId(reinterpret_cast<quintptr>(this))
|
||||
, containerWindow(0)
|
||||
, window(0)
|
||||
{
|
||||
m_localHandler = new LocalSchemeHandler(this);
|
||||
|
||||
container = new QWidget(0, Qt::FramelessWindowHint | Qt::NoDropShadowWindowHint | Qt::Tool);
|
||||
container->setAttribute(Qt::WA_NativeWindow, true);
|
||||
container->setAttribute(Qt::WA_DontCreateNativeAncestors, true);
|
||||
|
||||
QWebEngineUrlScheme localScheme(LocalSchemeHandler::scheme().toUtf8());
|
||||
localScheme.setFlags(QWebEngineUrlScheme::LocalAccessAllowed |
|
||||
QWebEngineUrlScheme::SecureScheme |
|
||||
QWebEngineUrlScheme::ViewSourceAllowed |
|
||||
QWebEngineUrlScheme::ContentSecurityPolicyIgnored |
|
||||
QWebEngineUrlScheme::CorsEnabled |
|
||||
QWebEngineUrlScheme::FetchApiAllowed);
|
||||
QWebEngineUrlScheme::registerScheme(localScheme);
|
||||
|
||||
QWebEngineUrlScheme qrcScheme("qrc");
|
||||
qrcScheme.setFlags(QWebEngineUrlScheme::LocalScheme |
|
||||
QWebEngineUrlScheme::LocalAccessAllowed |
|
||||
QWebEngineUrlScheme::SecureScheme |
|
||||
QWebEngineUrlScheme::ContentSecurityPolicyIgnored |
|
||||
QWebEngineUrlScheme::CorsEnabled |
|
||||
QWebEngineUrlScheme::FetchApiAllowed);
|
||||
QWebEngineUrlScheme::registerScheme(qrcScheme);
|
||||
|
||||
view = new QWebEngineView(container);
|
||||
QWebEngineProfile *profile = new QWebEngineProfile(view);
|
||||
profile->installUrlSchemeHandler(LocalSchemeHandler::scheme().toUtf8(), m_localHandler);
|
||||
|
||||
m_page = new WebPage(profile, profile);
|
||||
m_page->settings()->setAttribute(QWebEngineSettings::PluginsEnabled, true);
|
||||
connect(m_page, &QWebEnginePage::fileSystemAccessRequested, this, [](QWebEngineFileSystemAccessRequest request) {
|
||||
request.accept();
|
||||
});
|
||||
|
||||
view->settings()->setUnknownUrlSchemePolicy(QWebEngineSettings::AllowAllUnknownUrlSchemes);
|
||||
view->settings()->setAttribute(QWebEngineSettings::LocalContentCanAccessRemoteUrls, true);
|
||||
view->settings()->setAttribute(QWebEngineSettings::LocalContentCanAccessFileUrls, true);
|
||||
view->settings()->setAttribute(QWebEngineSettings::AllowRunningInsecureContent, true);
|
||||
view->settings()->setAttribute(QWebEngineSettings::AllowGeolocationOnInsecureOrigins, true);
|
||||
|
||||
view->setPage(m_page);
|
||||
container->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
|
||||
container->setLayout(new QHBoxLayout(container));
|
||||
container->layout()->setSpacing(0);
|
||||
container->layout()->setContentsMargins(0, 0, 0, 0);
|
||||
container->layout()->addWidget(view);
|
||||
|
||||
setBackgroundColor(backgroundColor);
|
||||
g_webViews->insert(viewId, this);
|
||||
|
||||
connect(view, SIGNAL(loadFinished(bool)), this, SIGNAL(loadFinished(bool)));
|
||||
connect(m_page, SIGNAL(loadFinished(bool)), this, SLOT(onLoadFinished(bool)), Qt::QueuedConnection);
|
||||
connect(m_page, SIGNAL(loadStarted()), this, SLOT(onPageStarted()), Qt::QueuedConnection);
|
||||
connect(view, SIGNAL(urlChanged(const QUrl &)), this, SLOT(onUrlChanged(const QUrl &)), Qt::QueuedConnection);
|
||||
container->createWinId();
|
||||
}
|
||||
|
||||
DesktopWebViewPrivate::~DesktopWebViewPrivate()
|
||||
{
|
||||
g_webViews->take(viewId);
|
||||
disconnect(this, SLOT(loadFinished(bool)));
|
||||
disconnect(this, SLOT(applicationStateChanged(Qt::ApplicationState)));
|
||||
disconnect(this, SLOT(onUrlChanged(const QUrl &)));
|
||||
disconnect(this, SLOT(onPageStarted()));
|
||||
disconnect(this, SLOT(onLoadFinished(bool)));
|
||||
|
||||
delete container;
|
||||
}
|
||||
|
||||
AmneziaWebViewPrivate *AmneziaWebViewPrivate::create(AmneziaWebView *q)
|
||||
{
|
||||
return new DesktopWebViewPrivate(q);
|
||||
}
|
||||
|
||||
void DesktopWebViewPrivate::setWindowParent(QWindow *parent)
|
||||
{
|
||||
if (window) {
|
||||
window->removeEventFilter(this);
|
||||
}
|
||||
|
||||
if (parent) {
|
||||
|
||||
containerWindow = qobject_cast<QWindow*>(container->windowHandle());
|
||||
containerWindow->setTransientParent(parent);
|
||||
parent->installEventFilter(this);
|
||||
|
||||
}
|
||||
window = parent;
|
||||
}
|
||||
|
||||
void DesktopWebViewPrivate::setBackgroundColor(const QColor backgroundColor)
|
||||
{
|
||||
this->backgroundColor = backgroundColor;
|
||||
QPalette p = container->palette();
|
||||
p.setColor(QPalette::Window, backgroundColor);
|
||||
container->setPalette(p);
|
||||
p = view->palette();
|
||||
p.setColor(QPalette::Window, backgroundColor);
|
||||
view->setPalette(p);
|
||||
emit backgroundColorChanged();
|
||||
}
|
||||
|
||||
/// Deprecated
|
||||
void DesktopWebViewPrivate::setScale(qreal scale)
|
||||
{
|
||||
Q_UNUSED(scale);
|
||||
}
|
||||
|
||||
/// Deprecated
|
||||
qreal DesktopWebViewPrivate::scale() const
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
QIcon DesktopWebViewPrivate::icon() const
|
||||
{
|
||||
return QIcon();
|
||||
}
|
||||
|
||||
QSize DesktopWebViewPrivate::contentsSize() const
|
||||
{
|
||||
return QSize();
|
||||
}
|
||||
|
||||
void DesktopWebViewPrivate::setGeometry(const QRect &geometry)
|
||||
{
|
||||
Q_Q(AmneziaWebView);
|
||||
QQuickWindow *window = q->window();
|
||||
if (!window) return;
|
||||
QRect newGeometry = QRect(window->mapToGlobal(geometry.topLeft()), QSize(geometry.width(), geometry.height()));
|
||||
if (newGeometry.isValid() && container->geometry() != newGeometry ) {
|
||||
|
||||
this->geometry = geometry;
|
||||
container->setGeometry(newGeometry);
|
||||
container->updateGeometry();
|
||||
}
|
||||
}
|
||||
|
||||
bool DesktopWebViewPrivate::eventFilter(QObject *obj, QEvent *event)
|
||||
{
|
||||
Q_UNUSED(obj);
|
||||
Q_Q(AmneziaWebView);
|
||||
|
||||
switch (event->type()) {
|
||||
case QEvent::Move: {
|
||||
QMoveEvent *moveEvent = static_cast<QMoveEvent*>(event);
|
||||
QPoint p = q->mapToScene(QPointF(moveEvent->pos())).toPoint();
|
||||
container->move(p);
|
||||
|
||||
if (visible) {
|
||||
show();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
break;
|
||||
case QEvent::Resize: {
|
||||
if (visible) {
|
||||
show();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
break;
|
||||
case QEvent::WindowStateChange: {
|
||||
|
||||
Qt::WindowState state = window->windowState();
|
||||
if ((state == Qt::WindowMaximized) || (state == Qt::WindowFullScreen) || (state == Qt::WindowActive)) {
|
||||
show();
|
||||
}
|
||||
else {
|
||||
hide();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
default: {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void DesktopWebViewPrivate::hide()
|
||||
{
|
||||
Q_Q(AmneziaWebView);
|
||||
if (!q->window()) return;
|
||||
|
||||
if (visible) {
|
||||
QMetaObject::invokeMethod(container, "hide", Qt::QueuedConnection);
|
||||
visible = false;
|
||||
}
|
||||
}
|
||||
|
||||
void DesktopWebViewPrivate::show()
|
||||
{
|
||||
Q_Q(AmneziaWebView);
|
||||
if (!q->window()) return;
|
||||
if (!visible) {
|
||||
|
||||
QMetaObject::invokeMethod(container, "show", Qt::QueuedConnection);
|
||||
QMetaObject::invokeMethod(container, "update", Qt::QueuedConnection);
|
||||
visible = true;
|
||||
}
|
||||
|
||||
containerWindow = qobject_cast<QWindow*>(container->windowHandle());
|
||||
|
||||
if ((containerWindow != nullptr) &&
|
||||
((qApp->topLevelWindows().at(0) != containerWindow) || !containerWindow->isVisible())) {
|
||||
|
||||
containerWindow->raise();
|
||||
}
|
||||
}
|
||||
|
||||
void DesktopWebViewPrivate::load(const QUrl& baseUrl)
|
||||
{
|
||||
QUrl url = baseUrl;
|
||||
if (!url.isValid()) {
|
||||
url = QUrl(QLatin1String("about:blank"));
|
||||
}
|
||||
view->load(url);
|
||||
history()->append(baseUrl);
|
||||
}
|
||||
|
||||
void DesktopWebViewPrivate::setContent(const QByteArray& data, const QString& mimeType, const QUrl& baseUrl)
|
||||
{
|
||||
QUrl url = baseUrl;
|
||||
if (!url.isValid()) {
|
||||
url = QUrl(QLatin1String("about:blank"));
|
||||
}
|
||||
view->setContent(data, mimeType, url);
|
||||
history()->append(url, data, mimeType);
|
||||
}
|
||||
|
||||
void DesktopWebViewPrivate::setHtml(const QString& html, const QUrl& baseUrl)
|
||||
{
|
||||
if(html.isNull()) return;
|
||||
QUrl url = baseUrl;
|
||||
if (!baseUrl.isValid())
|
||||
url = QUrl(QLatin1String("about:blank"));
|
||||
|
||||
view->setHtml(html, url);
|
||||
history()->append(url, html.toUtf8(), "text/html");
|
||||
}
|
||||
|
||||
void DesktopWebViewPrivate::evaluateJavaScript(const QString& scriptSource)
|
||||
{
|
||||
view->page()->runJavaScript(scriptSource);
|
||||
}
|
||||
|
||||
bool DesktopWebViewPrivate::canGoBack() const
|
||||
{
|
||||
QAction *pageAction = view->pageAction(QWebEnginePage::Back);
|
||||
bool can = (pageAction && pageAction->isEnabled());
|
||||
return can;
|
||||
}
|
||||
|
||||
bool DesktopWebViewPrivate::canGoForward() const
|
||||
{
|
||||
QAction *pageAction = view->pageAction(QWebEnginePage::Forward);
|
||||
bool can = (pageAction && pageAction->isEnabled());
|
||||
return can;
|
||||
}
|
||||
|
||||
void DesktopWebViewPrivate::back()
|
||||
{
|
||||
QAction *pageAction = view->pageAction(QWebEnginePage::Back);
|
||||
if (pageAction)
|
||||
emit pageAction->trigger();
|
||||
}
|
||||
|
||||
void DesktopWebViewPrivate::forward()
|
||||
{
|
||||
QAction *pageAction = view->pageAction(QWebEnginePage::Forward);
|
||||
if (pageAction)
|
||||
emit pageAction->trigger();
|
||||
}
|
||||
|
||||
void DesktopWebViewPrivate::reload()
|
||||
{
|
||||
QAction *pageAction = view->pageAction(QWebEnginePage::Reload);
|
||||
if (pageAction)
|
||||
emit pageAction->trigger();
|
||||
}
|
||||
|
||||
void DesktopWebViewPrivate::stop()
|
||||
{
|
||||
QAction *pageAction = view->pageAction(QWebEnginePage::Stop);
|
||||
if (pageAction)
|
||||
emit pageAction->trigger();
|
||||
}
|
||||
|
||||
bool DesktopWebViewPrivate::isLoading() const
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
QString DesktopWebViewPrivate::innerHTML() const
|
||||
{
|
||||
return QString();
|
||||
}
|
||||
|
||||
void DesktopWebViewPrivate::onLoadFinished(bool success)
|
||||
{
|
||||
if (success) {
|
||||
QMetaObject::invokeMethod(this, "onPageFinished", Qt::QueuedConnection);
|
||||
}
|
||||
else {
|
||||
QMetaObject::invokeMethod(this, "onPageError", Qt::QueuedConnection);
|
||||
}
|
||||
}
|
||||
|
||||
void DesktopWebViewPrivate::setDefaultFontSize(int size)
|
||||
{
|
||||
view->settings()->setFontSize(QWebEngineSettings::DefaultFontSize, size);
|
||||
}
|
||||
|
||||
void DesktopWebViewPrivate::setStandardFontFamily(const QString &family)
|
||||
{
|
||||
view->settings()->setFontFamily(QWebEngineSettings::StandardFont, family);
|
||||
}
|
||||
|
||||
void DesktopWebViewPrivate::setTextZoom(int percent)
|
||||
{
|
||||
Q_UNUSED(percent);
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
#ifndef AMNEZIAWEBVIEW_WEBENGINE_P_H
|
||||
#define AMNEZIAWEBVIEW_WEBENGINE_P_H
|
||||
|
||||
#include <QtWebEngineWidgets/QtWebEngineWidgets>
|
||||
|
||||
#include <QtWebEngineWidgets>
|
||||
#include <QWebEngineView>
|
||||
#include <QWebEnginePage>
|
||||
#include <QWebEngineUrlSchemeHandler>
|
||||
#include <QWebEngineUrlRequestJob>
|
||||
|
||||
#include "amneziawebview.h"
|
||||
#include "amneziawebview_p.h"
|
||||
|
||||
class DesktopWebViewPrivate;
|
||||
class LocalSchemeHandler;
|
||||
|
||||
class WebPage : public QWebEnginePage
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
signals:
|
||||
void loadingUrl(const QUrl &url);
|
||||
|
||||
public:
|
||||
explicit WebPage(QObject *parent = 0);
|
||||
explicit WebPage(QWebEngineProfile *profile, QObject *parent = 0);
|
||||
virtual ~WebPage();
|
||||
|
||||
protected:
|
||||
bool acceptNavigationRequest(const QUrl &url, QWebEnginePage::NavigationType type, bool isMainFrame) override;
|
||||
QWebEnginePage *createWindow(QWebEnginePage::WebWindowType type) override;
|
||||
|
||||
private slots:
|
||||
void handleUnsupportedContent(QNetworkReply *reply);
|
||||
|
||||
private:
|
||||
|
||||
friend class DesktopWebViewPrivate;
|
||||
QUrl m_loadingUrl;
|
||||
};
|
||||
|
||||
class DesktopWebViewPrivate : public AmneziaWebViewPrivate
|
||||
{
|
||||
Q_OBJECT
|
||||
Q_DECLARE_PUBLIC(AmneziaWebView)
|
||||
public:
|
||||
|
||||
explicit DesktopWebViewPrivate(AmneziaWebView* q);
|
||||
virtual ~DesktopWebViewPrivate();
|
||||
|
||||
virtual void setWindowParent(QWindow *parent);
|
||||
|
||||
virtual void setBackgroundColor(const QColor backgroundColor);
|
||||
virtual void show();
|
||||
virtual void hide();
|
||||
virtual void setGeometry(const QRect &);
|
||||
virtual QString innerHTML() const;
|
||||
virtual void load(const QUrl& url);
|
||||
virtual void setHtml(const QString& html, const QUrl& baseUrl = QUrl());
|
||||
virtual void setContent(const QByteArray& data, const QString& mimeType, const QUrl& baseUrl);
|
||||
virtual void evaluateJavaScript(const QString& scriptSource);
|
||||
virtual bool isLoading() const;
|
||||
virtual bool canGoBack() const;
|
||||
virtual bool canGoForward() const;
|
||||
virtual void back();
|
||||
virtual void forward();
|
||||
virtual void reload();
|
||||
virtual void stop();
|
||||
|
||||
virtual QIcon icon() const;
|
||||
virtual void setScale(qreal scale);
|
||||
virtual qreal scale() const;
|
||||
virtual QSize contentsSize() const;
|
||||
virtual void setDefaultFontSize(int size);
|
||||
virtual void setTextZoom(int percent);
|
||||
virtual void setStandardFontFamily(const QString &family);
|
||||
|
||||
protected:
|
||||
bool eventFilter(QObject *obj, QEvent *event);
|
||||
|
||||
private slots:
|
||||
void onLoadFinished(bool);
|
||||
|
||||
private:
|
||||
quintptr viewId;
|
||||
QWebEngineView *view;
|
||||
QWidget *container;
|
||||
QWindow *containerWindow;
|
||||
QWindow *window;
|
||||
WebPage *m_page;
|
||||
LocalSchemeHandler *m_localHandler;
|
||||
};
|
||||
|
||||
class LocalSchemeHandler : public QWebEngineUrlSchemeHandler
|
||||
{
|
||||
Q_OBJECT
|
||||
public:
|
||||
LocalSchemeHandler(QObject *parent) : QWebEngineUrlSchemeHandler(parent)
|
||||
{
|
||||
Q_UNUSED(parent);
|
||||
}
|
||||
|
||||
static const QString &scheme();
|
||||
static const QMimeDatabase &mimeDatabase();
|
||||
void requestStarted(QWebEngineUrlRequestJob *job) override;
|
||||
};
|
||||
|
||||
#endif // AMNEZIAWEBVIEW_WEBENGINE_P_H
|
||||
@@ -1,43 +0,0 @@
|
||||
#include <QtCore/QString>
|
||||
#include <QtCore/QUrl>
|
||||
#include <QtCore/QFile>
|
||||
#include <QtCore/QByteArray>
|
||||
|
||||
#include "filehandler.h"
|
||||
#include "mimecache.h"
|
||||
|
||||
QList<QString> FileHandler::schemes()
|
||||
{
|
||||
static QList<QString> list = QList<QString>() << "file" << "local";
|
||||
return list;
|
||||
}
|
||||
|
||||
QByteArray FileHandler::dataForUrl(const QUrl &url) const
|
||||
{
|
||||
QUrl fileUrl = url;
|
||||
if (fileUrl.scheme() != "file") {
|
||||
fileUrl.setScheme("file");
|
||||
}
|
||||
QString requestUrl(fileUrl.toLocalFile());
|
||||
QFile resource(requestUrl);
|
||||
QByteArray buffer;
|
||||
if (resource.exists() && resource.open(QIODevice::ReadOnly)) {
|
||||
|
||||
buffer = resource.readAll();
|
||||
resource.close();
|
||||
}
|
||||
return buffer;
|
||||
}
|
||||
|
||||
bool FileHandler::canHandleUrl(const QUrl &url) const
|
||||
{
|
||||
if (schemes().contains(url.scheme().toLower()))
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
QString FileHandler::mimeTypeForUrl(const QUrl &url) const
|
||||
{
|
||||
return mimeTypeForExtension(url.path().section('.', -1));
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
#ifndef FILEHANDLER_H
|
||||
#define FILEHANDLER_H
|
||||
|
||||
class QString;
|
||||
class QByteArray;
|
||||
class QUrl;
|
||||
|
||||
class FileHandler
|
||||
{
|
||||
public:
|
||||
explicit FileHandler();
|
||||
static QList<QString> schemes();
|
||||
bool canHandleUrl(const QUrl &url) const;
|
||||
QByteArray dataForUrl(const QUrl &url) const;
|
||||
QString mimeTypeForUrl(const QUrl &url) const;
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -1,10 +0,0 @@
|
||||
#include <QtCore/QString>
|
||||
#include <QtCore/QUrl>
|
||||
#include <QtCore/QFile>
|
||||
#include <QtCore/QByteArray>
|
||||
|
||||
#include "filehandler.h"
|
||||
|
||||
FileHandler::FileHandler()
|
||||
{
|
||||
}
|
||||
@@ -1,135 +0,0 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <MobileCoreServices/UTCoreTypes.h>
|
||||
#import <MobileCoreServices/UTType.h>
|
||||
|
||||
#include <QtCore/QFile>
|
||||
#include <QtCore/QString>
|
||||
#include <QtCore/QDebug>
|
||||
#include "mimecache.h"
|
||||
#include "filehandler.h"
|
||||
#define kProtocolFileScheme @"file"
|
||||
|
||||
#if !defined(ENABLE_WKWEBVIEW)
|
||||
|
||||
@interface FileProtocol : NSURLProtocol
|
||||
@end
|
||||
|
||||
#endif
|
||||
|
||||
FileHandler::FileHandler()
|
||||
{
|
||||
#if !defined(ENABLE_WKWEBVIEW)
|
||||
static bool protocolRegistered = false;
|
||||
if (!protocolRegistered) {
|
||||
[NSURLProtocol registerClass:[FileProtocol class]];
|
||||
protocolRegistered = true;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
#if !defined(ENABLE_WKWEBVIEW)
|
||||
|
||||
@implementation FileProtocol
|
||||
|
||||
+ (BOOL)canInitWithRequest:(NSURLRequest *)request
|
||||
{
|
||||
NSString *scheme = request.URL.scheme;
|
||||
if ([kProtocolFileScheme caseInsensitiveCompare:scheme] == NSOrderedSame) {
|
||||
return YES;
|
||||
}
|
||||
|
||||
return NO;
|
||||
}
|
||||
|
||||
+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request
|
||||
{
|
||||
return request;
|
||||
}
|
||||
|
||||
+ (NSString*)headFromHtml:(NSString*)html
|
||||
{
|
||||
if (!html) return nil;
|
||||
|
||||
NSString *head = nil;
|
||||
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(?<=<head>)[\\w\\W.]*(?=</head>)" options:NSRegularExpressionCaseInsensitive error:nil];
|
||||
NSTextCheckingResult *headResult = [regex firstMatchInString:html options:0 range:NSMakeRange(0, html.length)];
|
||||
|
||||
if (headResult && headResult.range.location != NSNotFound) {
|
||||
head = [html substringWithRange:[headResult range]];
|
||||
}
|
||||
return head;
|
||||
}
|
||||
|
||||
+ (NSString *)charsetFromHtml:(NSString *)html
|
||||
{
|
||||
if (!html) return nil;
|
||||
|
||||
NSString *charset = nil;
|
||||
NSString *charsetPattern = @"((?<=charset=)\\s*[a-zA-Z0-9-]*)";
|
||||
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:charsetPattern options: NSRegularExpressionCaseInsensitive error:nil];
|
||||
NSTextCheckingResult *charsetResult = [regex firstMatchInString:html options:kNilOptions range:NSMakeRange(0, [html length])];
|
||||
if (charsetResult && charsetResult.range.location != NSNotFound) {
|
||||
charset = [[html substringWithRange:[charsetResult range]] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
|
||||
charset = [charset lowercaseString];
|
||||
}
|
||||
return charset;
|
||||
}
|
||||
|
||||
- (void)startLoading
|
||||
{
|
||||
/* retrieve the current request. */
|
||||
NSURLRequest *request = [self request];
|
||||
NSString *url = [[request URL] path];
|
||||
NSString *mimeType = mimeTypeForExtension(QString::fromNSString(url.pathExtension)).toNSString();
|
||||
|
||||
QString requestUrl(QString("%1").arg(QString::fromNSString(url)));
|
||||
QFile resource(requestUrl);
|
||||
|
||||
NSData *pageData = nil;
|
||||
if (resource.exists() && resource.open(QIODevice::ReadOnly)) {
|
||||
|
||||
QByteArray buffer = resource.readAll();
|
||||
|
||||
//pageData = [[NSData alloc] initWithBytes:buffer.constData() length:buffer.size()];
|
||||
pageData = [NSData dataWithBytes:buffer.constData() length:buffer.size()];
|
||||
resource.close();
|
||||
}
|
||||
|
||||
if (pageData) {
|
||||
|
||||
NSString *encoding = @"utf-8";
|
||||
if ([mimeType isEqualToString:@"text/html"]) {
|
||||
|
||||
NSString *content = [[NSString alloc] initWithBytesNoCopy: (char* )[pageData bytes] length:pageData.length encoding:NSISOLatin1StringEncoding freeWhenDone:NO];
|
||||
|
||||
NSString *charset = [FileProtocol charsetFromHtml:[FileProtocol headFromHtml:content]];
|
||||
if (charset) {
|
||||
encoding = charset;
|
||||
}
|
||||
[content autorelease];
|
||||
}
|
||||
|
||||
NSURLResponse *response =[[NSURLResponse alloc]initWithURL:self.request.URL
|
||||
MIMEType:mimeType
|
||||
expectedContentLength:[pageData length]
|
||||
textEncodingName:encoding];
|
||||
|
||||
|
||||
[[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
|
||||
[[self client] URLProtocol:self didLoadData:pageData];
|
||||
[[self client] URLProtocolDidFinishLoading:self];
|
||||
[response autorelease];
|
||||
}
|
||||
else {
|
||||
[[self client] URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)stopLoading
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
@@ -1,432 +0,0 @@
|
||||
#include <QtCore/QString>
|
||||
#include <QtCore/QUrl>
|
||||
#include <QtCore/QFile>
|
||||
#include <QtCore/QByteArray>
|
||||
#include <QtCore/QDebug>
|
||||
#include <QtCore/QVariant>
|
||||
#include <QtCore/QMetaMethod>
|
||||
#include <QtCore/QMetaObject>
|
||||
#include <QtCore/QGenericArgument>
|
||||
#include <QtCore/QJsonObject>
|
||||
#include <QtCore/QJsonArray>
|
||||
#include <QtCore/QJsonDocument>
|
||||
|
||||
#include "amneziawebview_p.h"
|
||||
#include "mimecache.h"
|
||||
#include "jshandler.h"
|
||||
|
||||
QString JsHandler::scheme() const
|
||||
{
|
||||
return QString("js");
|
||||
}
|
||||
|
||||
QString JsHandler::host() const
|
||||
{
|
||||
qulonglong h = (qulonglong)(void*)_host;
|
||||
return QString("js%1").arg(h);
|
||||
}
|
||||
|
||||
QString JsHandler::scriptObjectsUrl() const
|
||||
{
|
||||
return QString("%1://%2/%3.js").arg(scheme()).arg(host()).arg(scriptObjectsId());
|
||||
}
|
||||
|
||||
QString JsHandler::scriptObjectsId() const
|
||||
{
|
||||
return QString("__scriptObjects__");
|
||||
}
|
||||
|
||||
QString JsHandler::scriptObjects() const
|
||||
{
|
||||
QString script;
|
||||
QList<QString> scripts = scriptParts.values();
|
||||
|
||||
for ( int i = 0; i < scripts.count(); i++) {
|
||||
script = QString("%1 %2").arg(script).arg(scripts.at(i)).trimmed();
|
||||
}
|
||||
return script;
|
||||
}
|
||||
|
||||
void JsHandler::updateWebView()
|
||||
{
|
||||
if (!scriptObjectsInjected) {
|
||||
|
||||
QString injector = QString(
|
||||
" var script = document.getElementById(\"%1\"); "
|
||||
" if(script === null) { "
|
||||
" script = document.createElement('script'); "
|
||||
" script.type = \"text/javascript\"; "
|
||||
" script.id = \"%2\"; "
|
||||
" document.getElementsByTagName('head')[0].appendChild(script); "
|
||||
" } "
|
||||
" script.text = \"%3\"; "
|
||||
).arg(scriptObjectsId()).arg(scriptObjectsId()).arg(scriptObjects());
|
||||
|
||||
|
||||
|
||||
/*
|
||||
QString injector = QString(
|
||||
" var script = document.getElementById(\"%1\"); "
|
||||
" if(script === null) { "
|
||||
" script = document.createElement('script'); "
|
||||
" script.type = \"text/javascript\"; "
|
||||
" script.id = \"%2\"; "
|
||||
" document.getElementsByTagName('head')[0].appendChild(script); "
|
||||
" } "
|
||||
" script.src = \"%3\"; "
|
||||
).arg(scriptObjectsId()).arg(scriptObjectsId()).arg(scriptObjectsUrl());
|
||||
|
||||
*/
|
||||
|
||||
//убрали, так как теперь есть рабочий вебинспектор
|
||||
//_host->evaluateJavaScript(injector);
|
||||
scriptObjectsInjected = true;
|
||||
}
|
||||
}
|
||||
|
||||
void JsHandler::addToJavaScriptWindowObject(const QString& name, QObject* object)
|
||||
{
|
||||
windowObjects[name] = object;
|
||||
QString script = windowScriptObject(name, object);
|
||||
scriptParts[name] = script;
|
||||
}
|
||||
|
||||
bool JsHandler::canHandleUrl(const QUrl &url) const
|
||||
{
|
||||
if (scheme() == url.scheme() && url.host() == host())
|
||||
return true;
|
||||
|
||||
if (this->host() == url.host() && (url.scheme() == QString("http")))
|
||||
return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
QString JsHandler::mimeTypeForUrl(const QUrl &url) const
|
||||
{
|
||||
if (scheme() == url.scheme() && url.host() == host())
|
||||
return mimeTypeForUrl(url);
|
||||
|
||||
if (this->host() == url.host() && (url.scheme() == QString("http")))
|
||||
return mimeTypeForExtension("json");
|
||||
|
||||
return QString("application/octet-stream");
|
||||
}
|
||||
|
||||
QString JsHandler::windowScriptObject(const QString& name, QObject* object) const
|
||||
{
|
||||
QString script = QString(" var %1 = {}; "
|
||||
" %2.responseText = null; "
|
||||
).arg(name).arg(name);
|
||||
if (object) {
|
||||
const QMetaObject *meta = object->metaObject();
|
||||
const QString prefix = QString("%1.").arg(name);
|
||||
|
||||
int methodCount = meta->methodCount();
|
||||
for (int i = 0; i < methodCount; i++) {
|
||||
QMetaMethod metaMethod = meta->method(i);
|
||||
|
||||
if ((metaMethod.access() == QMetaMethod::Public) && ((metaMethod.methodType() == QMetaMethod::Slot) ||
|
||||
(metaMethod.methodType() == QMetaMethod::Method)) ) {
|
||||
const QString methodName = QString("%1%2").arg(prefix).arg(QString(metaMethod.name()));
|
||||
|
||||
//Parameters
|
||||
QList<QByteArray> parametersNames = metaMethod.parameterNames();
|
||||
QString methodParameters = QString("");
|
||||
QString stringifyParameters = QString("");
|
||||
|
||||
for (int j = 0; j < parametersNames.count(); j++) {
|
||||
methodParameters += QString(parametersNames.at(j));
|
||||
|
||||
stringifyParameters += QString("'%1=' + encodeURIComponent(%2)").arg(QString(parametersNames.at(j)))
|
||||
.arg(QString(parametersNames.at(j)));
|
||||
|
||||
if(j < (parametersNames.count() -1)) {
|
||||
methodParameters += QString(", ");
|
||||
stringifyParameters += QString(" + '&' + ");
|
||||
}
|
||||
}
|
||||
if (stringifyParameters.length() > 0)
|
||||
stringifyParameters = QString(" + '?'+ %1").arg(stringifyParameters);
|
||||
|
||||
const QString methodUrl = QString("http://%1/%2").arg(host()).arg(methodName);
|
||||
//Body
|
||||
const QString bodyTemplate = QString(""
|
||||
" var obj = this; "
|
||||
" if (obj.responseText !== null) { "
|
||||
" var ret = eval( obj.responseText ); "
|
||||
" obj.responseText = null; "
|
||||
" return ret;"
|
||||
" }; "
|
||||
" var caller = arguments.callee.caller; "
|
||||
" var callerArgs = caller.arguments; "
|
||||
" var xhr = new XMLHttpRequest; "
|
||||
" xhr.onload=function(){ "
|
||||
" if (xhr.status == 200) { "
|
||||
" obj.responseText = xhr.responseText; "
|
||||
" if (obj.responseText == null) { "
|
||||
" obj.responceText = ''; "
|
||||
" } "
|
||||
" caller(callerArgs); "
|
||||
" }; "
|
||||
" }; "
|
||||
" xhr.open('GET', '%1'%2, true); "
|
||||
//" xhr.setRequestHeader('Access-Control-Allow-Origin', '*'); "
|
||||
//" xhr.setRequestHeader('Access-Control-Allow-Headers', 'Content-Type'); "
|
||||
" xhr.send(null);"
|
||||
).arg(methodUrl).arg(stringifyParameters);
|
||||
|
||||
|
||||
QString methodBody = QString("%1").arg(bodyTemplate);
|
||||
|
||||
script = script + QString("%1=function(%2){ %3 }; " )
|
||||
.arg(methodName)
|
||||
.arg(methodParameters)
|
||||
.arg(methodBody);
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
return script;
|
||||
}
|
||||
|
||||
|
||||
const QString createPopup = QString( ""
|
||||
" window.createPopup=function(){ "
|
||||
" var popup=document.createElement('iframe'), "
|
||||
" isShown=false, popupClicked=false; "
|
||||
" popup.src='about:blank'; "
|
||||
" popup.style.position='absolute'; "
|
||||
" popup.style.border='0px'; "
|
||||
" popup.style.display='none'; "
|
||||
" popup.addEventListener('load', function(e){ "
|
||||
" popup.document=(popup.contentWindow || popup.contentDocument); "
|
||||
" if(popup.document.document) popup.document=popup.document.document; "
|
||||
" }); "
|
||||
" document.body.appendChild(popup); "
|
||||
" var hidepopup=function(event){ "
|
||||
" if(isShown) "
|
||||
" setTimeout(function(){ "
|
||||
//" if(!popupClicked){ "
|
||||
" popup.hide(); "
|
||||
//" } "
|
||||
" popupClicked=false; "
|
||||
" }, 150); "
|
||||
" }; "
|
||||
" popup.show=function(x, y, w, h, pElement){ "
|
||||
" if(typeof(x) !== 'undefined'){ "
|
||||
" var elPos=[0, 0]; "
|
||||
" if(pElement) elPos=findPos(pElement); "
|
||||
" elPos[0]+=y, elPos[1]+=x; "
|
||||
" if(isNaN(w)) w=popup.document.scrollWidth; "
|
||||
" if(isNaN(h)) h=popup.document.scrollHeight; "
|
||||
" if(elPos[0] + w > document.body.clientWidth) elPos[0]=document.body.clientWidth - w - 5; "
|
||||
" if(elPos[1] + h > document.body.clientHeight) elPos[1]=document.body.clientHeight - h - 5; "
|
||||
" popup.style.left=elPos[0] + 'px'; "
|
||||
" popup.style.top=elPos[1] + 'px'; "
|
||||
" popup.style.width=(w + 'px'); "
|
||||
" popup.style.height=(h + 'px'); "
|
||||
" } "
|
||||
" popup.style.display='block'; "
|
||||
" isShown=true; "
|
||||
" }; "
|
||||
" popup.hide=function(){ "
|
||||
" isShown=false; "
|
||||
" popup.style.display='none'; "
|
||||
" }; "
|
||||
" window.addEventListener('click', hidepopup, true); "
|
||||
" window.addEventListener('blur', hidepopup, true); "
|
||||
" return popup; "
|
||||
" }; "
|
||||
" function findPos(obj, foundScrollLeft, foundScrollTop) { "
|
||||
" var curleft = 0; "
|
||||
" var curtop = 0; "
|
||||
" if(obj.offsetLeft) curleft += parseInt(obj.offsetLeft); "
|
||||
" if(obj.offsetTop) curtop += parseInt(obj.offsetTop); "
|
||||
" if(obj.scrollTop && obj.scrollTop > 0) { "
|
||||
" curtop -= parseInt(obj.scrollTop); "
|
||||
" foundScrollTop = true; "
|
||||
" } "
|
||||
" if(obj.scrollLeft && obj.scrollLeft > 0) { "
|
||||
" curleft -= parseInt(obj.scrollLeft); "
|
||||
" foundScrollLeft = true; "
|
||||
" } "
|
||||
" if(obj.offsetParent) { "
|
||||
" var pos = findPos(obj.offsetParent, foundScrollLeft, foundScrollTop); "
|
||||
" curleft += pos[0]; "
|
||||
" curtop += pos[1]; "
|
||||
" } else if(obj.ownerDocument) { "
|
||||
" var thewindow = obj.ownerDocument.defaultView; "
|
||||
" if(!thewindow && obj.ownerDocument.parentWindow) "
|
||||
" thewindow = obj.ownerDocument.parentWindow; "
|
||||
" if(thewindow) { "
|
||||
" if (!foundScrollTop && thewindow.scrollY && thewindow.scrollY > 0) curtop -= parseInt(thewindow.scrollY); "
|
||||
" if (!foundScrollLeft && thewindow.scrollX && thewindow.scrollX > 0) curleft -= parseInt(thewindow.scrollX); "
|
||||
" if(thewindow.frameElement) { "
|
||||
" var pos = findPos(thewindow.frameElement); "
|
||||
" curleft += pos[0]; "
|
||||
" curtop += pos[1]; "
|
||||
" } "
|
||||
" }"
|
||||
" }"
|
||||
" return [curleft,curtop]; "
|
||||
" } " );
|
||||
|
||||
|
||||
void JsHandler::init()
|
||||
{
|
||||
/*
|
||||
QString consoleObject = createPopup + QString (
|
||||
"function popup(msg){ "
|
||||
" var p = window.createPopup(); "
|
||||
" var pbody = p.document.body; "
|
||||
" pbody.style.backgroundColor='lime'; "
|
||||
" pbody.style.border='solid black 1px'; "
|
||||
" pbody.innerHTML=msg; "
|
||||
" p.show(NaN,NaN,NaN,NaN, document.body); }"
|
||||
" window.console={ "
|
||||
" log=function(msg){ popup(msg); }"
|
||||
" warning=function(msg){ popup(msg); }"
|
||||
" error=function(msg){ popup(msg); }"
|
||||
" info=function(msg){ popup(msg); }"
|
||||
" }");
|
||||
*/
|
||||
|
||||
QString consoleObject = QString ( ""
|
||||
" webviewPopup=function(msg){ "
|
||||
" var p = window.createPopup(); "
|
||||
" var pbody = p.document.body; "
|
||||
" pbody.style.backgroundColor='white'; "
|
||||
" pbody.style.border='solid black 1px'; "
|
||||
" pbody.innerHTML=msg + ' ' + document.body.clientWidth; "
|
||||
" p.show(0, 0, document.body.clientWidth, NaN, document.body); }; "
|
||||
" window.console.log=function(msg){ webviewPopup(msg); };"
|
||||
" window.console.warning=function(msg){ webviewPopup(msg); };"
|
||||
" window.console.error=function(msg){ webviewPopup(msg); };"
|
||||
" window.console.info=function(msg){ webviewPopup(msg); };"
|
||||
) + createPopup;
|
||||
/*
|
||||
QString object = QString( " var script = document.getElementById(\"consoleScriptObject\"); "
|
||||
" if(script === null) { "
|
||||
" script = document.createElement('script'); "
|
||||
" script.type = \"text/javascript\";"
|
||||
" script.text = \"%1\";"
|
||||
" script.id = \"consoleScriptObject\"; "
|
||||
" document.getElementsByTagName('head')[0].appendChild(script); "
|
||||
" } "
|
||||
).arg(consoleObject);
|
||||
*/
|
||||
|
||||
scriptParts["__console__"] = consoleObject;
|
||||
}
|
||||
|
||||
QByteArray JsHandler::dataForUrl(const QUrl &url) const
|
||||
{
|
||||
QByteArray buffer;
|
||||
QVariant ret = callMethodForUrl(url);
|
||||
if (ret.isValid()) {
|
||||
|
||||
QJsonValue value = QJsonValue::fromVariant(ret);
|
||||
QJsonArray jsonArray;
|
||||
jsonArray.append(value);
|
||||
QJsonDocument jsonDoc(jsonArray);
|
||||
buffer = jsonDoc.toJson();
|
||||
}
|
||||
return buffer;
|
||||
}
|
||||
|
||||
|
||||
// Method call specified by url of type: http://scripthost/object.methodname?paramName1=paramValue1¶mName2=paramValue2&...
|
||||
QVariant JsHandler::callMethodForUrl(const QUrl &url) const
|
||||
{
|
||||
qDebug() << url.toString();
|
||||
qDebug() << "Path: " << url.path();
|
||||
qDebug() << "Query: " << url.query();
|
||||
|
||||
QVariant ret;
|
||||
QStringList objectPath = url.path().trimmed().remove('/').split(".");
|
||||
QStringList query;
|
||||
if (url.query().trimmed().length() > 0)
|
||||
query = url.query().trimmed().split("&");
|
||||
QList<QGenericArgument> arguments;
|
||||
QList<QByteArray> parametersNames;
|
||||
QList<QByteArray> parametersTypes;
|
||||
QString methodName;
|
||||
QString signature;
|
||||
|
||||
AmneziaWebViewPrivate *d = AmneziaWebViewPrivate::get(_host);
|
||||
|
||||
if (d && objectPath.count() == 2) {
|
||||
qDebug() << "Called method: " << objectPath[0] << "."<< objectPath[1];
|
||||
QObject *object = d->jsHandler.windowObjects.value(objectPath[0]);
|
||||
if (object) {
|
||||
int methodCount = object->metaObject()->methodCount();
|
||||
int methodIndex = -1;
|
||||
for(int i = 0; i < methodCount; i++) {
|
||||
const QMetaMethod method = object->metaObject()->method(i);
|
||||
parametersNames = method.parameterNames();
|
||||
methodName = method.name();
|
||||
if ((query.count() == parametersNames.count()) && (methodName == objectPath[1])) {
|
||||
methodIndex = i;
|
||||
parametersTypes = method.parameterTypes();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (methodIndex >= 0) {
|
||||
const QMetaMethod method = object->metaObject()->method(methodIndex);
|
||||
QVariantList params;
|
||||
for (int i = 0; i < query.count(); i++) {
|
||||
QStringList param = query[i].split('=');
|
||||
|
||||
params.append(QVariant(QString(param[1].toLocal8Bit())));
|
||||
QGenericArgument arg(param[0].toLocal8Bit().constData(), ¶ms[i]);
|
||||
arguments.append(arg);
|
||||
}
|
||||
switch (arguments.count()) {
|
||||
case 1:
|
||||
method.invoke(object, Qt::DirectConnection, Q_RETURN_ARG(QVariant, ret), arguments[0]);
|
||||
break;
|
||||
|
||||
case 2:
|
||||
method.invoke(object, Qt::DirectConnection, Q_RETURN_ARG(QVariant, ret), arguments[0], arguments[1]);
|
||||
break;
|
||||
|
||||
case 3:
|
||||
method.invoke(object, Qt::DirectConnection, Q_RETURN_ARG(QVariant, ret), arguments[0], arguments[1], arguments[2]);
|
||||
break;
|
||||
|
||||
case 4:
|
||||
method.invoke(object, Qt::DirectConnection, Q_RETURN_ARG(QVariant, ret), arguments[0], arguments[1], arguments[2],
|
||||
arguments[3]);
|
||||
break;
|
||||
|
||||
case 5:
|
||||
method.invoke(object, Qt::DirectConnection, Q_RETURN_ARG(QVariant, ret), arguments[0], arguments[1], arguments[2],
|
||||
arguments[3], arguments[4]);
|
||||
break;
|
||||
case 6:
|
||||
method.invoke(object, Qt::DirectConnection, Q_RETURN_ARG(QVariant, ret), arguments[0], arguments[1], arguments[2],
|
||||
arguments[3], arguments[4], arguments[5]);
|
||||
break;
|
||||
|
||||
case 7:
|
||||
method.invoke(object, Qt::DirectConnection, Q_RETURN_ARG(QVariant, ret), arguments[0], arguments[1], arguments[2],
|
||||
arguments[3], arguments[4], arguments[5], arguments[6]);
|
||||
break;
|
||||
|
||||
case 8:
|
||||
method.invoke(object, Qt::DirectConnection, Q_RETURN_ARG(QVariant, ret), arguments[0], arguments[1], arguments[2],
|
||||
arguments[3], arguments[4], arguments[5], arguments[6], arguments[7]);
|
||||
break;
|
||||
|
||||
default:
|
||||
method.invoke(object, Qt::DirectConnection, Q_RETURN_ARG(QVariant, ret));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
@@ -1,41 +0,0 @@
|
||||
#ifndef JSHANDLER_H
|
||||
#define JSHANDLER_H
|
||||
|
||||
class QUrl;
|
||||
class QVariant;
|
||||
class AmneziaWebView;
|
||||
|
||||
class JsHandler
|
||||
{
|
||||
friend class AmneziaWebView;
|
||||
|
||||
public:
|
||||
explicit JsHandler(AmneziaWebView *host);
|
||||
virtual ~JsHandler();
|
||||
|
||||
bool canHandleUrl(const QUrl &url) const;
|
||||
QByteArray dataForUrl(const QUrl &url) const;
|
||||
void addToJavaScriptWindowObject(const QString& name, QObject* object);
|
||||
QString mimeTypeForUrl(const QUrl &url) const;
|
||||
|
||||
void updateWebView();
|
||||
QString host() const;
|
||||
QString scheme() const;
|
||||
QString scriptObjectsUrl() const;
|
||||
QString scriptObjectsId() const;
|
||||
QString scriptObjects() const;
|
||||
|
||||
private:
|
||||
|
||||
QVariant callMethodForUrl(const QUrl &url) const;
|
||||
QString windowScriptObject(const QString& name, QObject* object) const;
|
||||
|
||||
void init();
|
||||
AmneziaWebView *_host;
|
||||
bool scriptObjectsInjected;
|
||||
|
||||
QHash<QString, QObject*> windowObjects;
|
||||
QHash<QString, QString> scriptParts;
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -1,24 +0,0 @@
|
||||
#include <QtCore/QString>
|
||||
#include <QtCore/QUrl>
|
||||
#include <QtCore/QFile>
|
||||
#include <QtCore/QByteArray>
|
||||
#include <QtCore/QDebug>
|
||||
#include <QtCore/QVariant>
|
||||
#include <QtCore/QMetaMethod>
|
||||
#include <QtCore/QMetaObject>
|
||||
#include <QtCore/QGenericArgument>
|
||||
#include <QtCore/QJsonObject>
|
||||
#include <QtCore/QJsonArray>
|
||||
#include <QtCore/QJsonDocument>
|
||||
|
||||
#include "amneziawebview_p.h"
|
||||
#include "jshandler.h"
|
||||
#include "mimecache.h"
|
||||
|
||||
JsHandler::JsHandler(AmneziaWebView *host): _host(host)
|
||||
{
|
||||
init();
|
||||
}
|
||||
|
||||
JsHandler::~JsHandler() {}
|
||||
|
||||
@@ -1,185 +0,0 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <MobileCoreServices/UTCoreTypes.h>
|
||||
#import <MobileCoreServices/UTType.h>
|
||||
|
||||
#include <QtCore/QFile>
|
||||
#include <QtCore/QString>
|
||||
#include <QtCore/QHash>
|
||||
#include <QtCore/QDebug>
|
||||
#include <QtCore/QUrl>
|
||||
#include <QtCore/QRect>
|
||||
#include <QColor>
|
||||
#include <QtCore/QDebug>
|
||||
#include <QtCore/QVariant>
|
||||
#include <QtCore/QMetaMethod>
|
||||
#include <QtCore/QMetaObject>
|
||||
#include <QtCore/QGenericArgument>
|
||||
#include <QtCore/QJsonObject>
|
||||
#include <QtCore/QJsonArray>
|
||||
#include <QtCore/QJsonDocument>
|
||||
|
||||
#include "amneziawebview_p.h"
|
||||
#include "mimecache.h"
|
||||
#import "jshandler.h"
|
||||
|
||||
typedef QHash<QString, AmneziaWebView*> JavaScriptHosts;
|
||||
Q_GLOBAL_STATIC(JavaScriptHosts, hosts);
|
||||
|
||||
#if !defined(ENABLE_WKWEBVIEW)
|
||||
|
||||
@interface JsProtocol : NSURLProtocol
|
||||
+ (NSString*) requestVarsKey;
|
||||
@end
|
||||
|
||||
@interface NSURLRequest (JsProtocol)
|
||||
- (NSDictionary *)requestVars;
|
||||
@end
|
||||
|
||||
@interface NSMutableURLRequest (JsProtocol)
|
||||
- (void)setRequestVars:(NSDictionary *)vars;
|
||||
@end
|
||||
|
||||
#endif
|
||||
|
||||
JsHandler::JsHandler(AmneziaWebView *h): _host(h)
|
||||
, scriptObjectsInjected(false)
|
||||
{
|
||||
#if !defined(ENABLE_WKWEBVIEW)
|
||||
static bool protocolRegistered = false;
|
||||
if (!protocolRegistered) {
|
||||
[NSURLProtocol registerClass:[JsProtocol class]];
|
||||
protocolRegistered = true;
|
||||
}
|
||||
#endif
|
||||
QString key = host();
|
||||
if (!hosts()->keys().contains(key)) {
|
||||
hosts()->insert(key, h);
|
||||
}
|
||||
init();
|
||||
}
|
||||
|
||||
JsHandler::~JsHandler()
|
||||
{
|
||||
QString key = host();
|
||||
if (hosts()->keys().contains(key)) {
|
||||
hosts()->remove(key);
|
||||
}
|
||||
}
|
||||
|
||||
#if !defined(ENABLE_WKWEBVIEW)
|
||||
|
||||
@implementation NSURLRequest (JsProtocol)
|
||||
|
||||
- (NSDictionary *)requestVars {
|
||||
NSLog(@"%@ received %@", self, NSStringFromSelector(_cmd));
|
||||
return [NSURLProtocol propertyForKey:[JsProtocol requestVarsKey] inRequest:self];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
|
||||
@implementation NSMutableURLRequest (JsProtocol)
|
||||
|
||||
- (void)setRequestVars:(NSDictionary *)requestVars {
|
||||
|
||||
NSLog(@"%@ received %@", self, NSStringFromSelector(_cmd));
|
||||
|
||||
NSDictionary *specialVarsCopy = [requestVars copy];
|
||||
[NSURLProtocol setProperty:specialVarsCopy forKey:[JsProtocol requestVarsKey] inRequest:self];
|
||||
[specialVarsCopy release];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
|
||||
@implementation JsProtocol
|
||||
|
||||
+ (BOOL)canInitWithRequest:(NSURLRequest *)request
|
||||
{
|
||||
//NSString *url = request.URL.absoluteString;
|
||||
QString host = QString::fromNSString(request.URL.host).toLower();
|
||||
if (hosts()->keys().contains(host))
|
||||
return YES;
|
||||
|
||||
//NSLog(@"Requested Url: %@", url);
|
||||
return NO;
|
||||
}
|
||||
|
||||
+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request
|
||||
{
|
||||
return request;
|
||||
}
|
||||
|
||||
+ (NSString*) requestVarsKey
|
||||
{
|
||||
return @"requestVars";
|
||||
}
|
||||
|
||||
- (void)startLoading
|
||||
{
|
||||
QString host = QString::fromNSString(self.request.URL.host);
|
||||
AmneziaWebViewPrivate *d = AmneziaWebViewPrivate::get(hosts()->value(host));
|
||||
NSURLRequest *request = [self request];
|
||||
|
||||
if ([request.URL.absoluteString isEqualToString: d->jsHandler.scriptObjectsUrl().toNSString()]) {
|
||||
|
||||
//NSString *mimeType = mimeTypeForExtension(QString::fromNSString(request.URL.path.pathExtension)).toNSString();
|
||||
|
||||
NSString *mimeType = d->jsHandler.mimeTypeForUrl(QUrl::fromNSURL(request.URL)).toNSString();
|
||||
QByteArray buffer = d->jsHandler.scriptObjects().toLocal8Bit();
|
||||
|
||||
//NSData *data = [[NSData alloc] initWithBytes:buffer.constData() length:buffer.size()];
|
||||
NSData *data = [NSData dataWithBytes:buffer.constData() length:buffer.size()];
|
||||
|
||||
NSURLResponse *response =[[NSURLResponse alloc]initWithURL:self.request.URL
|
||||
MIMEType:mimeType
|
||||
expectedContentLength:[data length]
|
||||
textEncodingName:@"utf-8"];
|
||||
|
||||
|
||||
[[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
|
||||
[[self client] URLProtocol:self didLoadData:data];
|
||||
[[self client] URLProtocolDidFinishLoading:self];
|
||||
[response autorelease];
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if ( d && [request.URL.scheme isEqualToString:@"http"]
|
||||
&& [request.URL.host isEqualToString:host.toNSString()]) {
|
||||
|
||||
const QByteArray buffer = d->dataForUrl(QUrl::fromNSURL(request.URL));
|
||||
//NSData *data = data = [[NSData alloc] initWithBytes:buffer.constData() length:buffer.size()];
|
||||
NSData *data = data = [NSData dataWithBytes:buffer.constData() length:buffer.size()];
|
||||
|
||||
//NSString *mimeType = mimeTypeForExtension(QString("json")).toNSString();
|
||||
NSString *mimeType = d->jsHandler.mimeTypeForUrl(QUrl::fromNSURL(request.URL)).toNSString();
|
||||
|
||||
NSDictionary *headers = @{@"Access-Control-Allow-Origin" : @"*",
|
||||
@"Access-Control-Allow-Headers" : @"Content-Type",
|
||||
@"Cache-Control" : @"no-cache",
|
||||
@"Content-Type" : [NSString stringWithFormat:@"%@; %@", mimeType, @"charset=UTF-8"] };
|
||||
|
||||
NSHTTPURLResponse* response = [[NSHTTPURLResponse alloc] initWithURL:request.URL
|
||||
statusCode:200
|
||||
HTTPVersion:@"HTTP/1.1"
|
||||
headerFields:headers];
|
||||
|
||||
[self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
|
||||
[self.client URLProtocol:self didLoadData:data];
|
||||
[self.client URLProtocolDidFinishLoading:self];
|
||||
[response autorelease];
|
||||
return;
|
||||
}
|
||||
else {
|
||||
[[self client] URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)stopLoading
|
||||
{
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
@@ -1,274 +0,0 @@
|
||||
#include "mimecache.h"
|
||||
|
||||
#include <QtCore/QFile>
|
||||
#include <QtCore/QUrl>
|
||||
#include <QtCore/QString>
|
||||
#include <QtCore/QMimeDatabase>
|
||||
#include <QtCore/QMimeType>
|
||||
#include <QtCore/QHash>
|
||||
#include <QtCore/QDebug>
|
||||
|
||||
typedef QHash<QString, QString> MimeTypes;
|
||||
Q_GLOBAL_STATIC(MimeTypes, cache)
|
||||
Q_GLOBAL_STATIC(QMimeDatabase, mimeDatabase)
|
||||
|
||||
|
||||
void initCache()
|
||||
{
|
||||
if (cache()->isEmpty()) {
|
||||
|
||||
cache()->insert("323", "text/h323");
|
||||
cache()->insert("*", "application/octet-stream");
|
||||
cache()->insert("acx", "application/internet-property-stream");
|
||||
cache()->insert("ai", "application/postscript");
|
||||
cache()->insert("aif", "audio/x-aiff");
|
||||
cache()->insert("aifc", "audio/x-aiff");
|
||||
cache()->insert("aiff", "audio/x-aiff");
|
||||
cache()->insert("asf", "video/x-ms-asf");
|
||||
cache()->insert("asr", "video/x-ms-asf");
|
||||
cache()->insert("asx", "video/x-ms-asf");
|
||||
cache()->insert("au", "audio/basic");
|
||||
cache()->insert("avi", "video/x-msvideo");
|
||||
cache()->insert("axs", "application/olescript");
|
||||
cache()->insert("bas", "text/plain");
|
||||
cache()->insert("bcpio", "application/x-bcpio");
|
||||
cache()->insert("bin", "application/octet-stream");
|
||||
cache()->insert("bmp", "image/bmp");
|
||||
cache()->insert("c", "text/plain");
|
||||
cache()->insert("cat", "application/vnd.ms-pkiseccat");
|
||||
cache()->insert("cdf", "application/x-cdf");
|
||||
cache()->insert("cdf", "application/x-netcdf");
|
||||
cache()->insert("cer", "application/x-x509-ca-cert""cer");
|
||||
cache()->insert("class", "application/octet-stream");
|
||||
cache()->insert("clp", "application/x-msclip");
|
||||
cache()->insert("cmx", "image/x-cmx");
|
||||
cache()->insert("cod", "image/cis-cod");
|
||||
cache()->insert("cpio", "application/x-cpio");
|
||||
cache()->insert("crd", "application/x-mscardfile");
|
||||
cache()->insert("crl", "application/pkix-crl");
|
||||
cache()->insert("crt", "application/x-x509-ca-cert");
|
||||
cache()->insert("csh", "application/x-csh");
|
||||
cache()->insert("css", "text/css");
|
||||
cache()->insert("dcr", "application/x-director");
|
||||
cache()->insert("der", "application/x-x509-ca-cert");
|
||||
cache()->insert("dir", "application/x-director");
|
||||
cache()->insert("dll", "application/x-msdownload");
|
||||
cache()->insert("dms", "application/octet-stream");
|
||||
cache()->insert("doc", "application/msword");
|
||||
cache()->insert("dot", "application/msword");
|
||||
cache()->insert("dvi", "application/x-dvi");
|
||||
cache()->insert("dxr", "application/x-director");
|
||||
cache()->insert("eot", "application/vnd.ms-fontobject");
|
||||
cache()->insert("eps", "application/postscript");
|
||||
cache()->insert("etx", "text/x-setext");
|
||||
cache()->insert("evy", "application/envoy");
|
||||
cache()->insert("exe", "application/octet-stream");
|
||||
cache()->insert("fif", "application/fractals");
|
||||
cache()->insert("flr", "x-world/x-vrml");
|
||||
cache()->insert("gif", "image/gif");
|
||||
cache()->insert("gtar", "application/x-gtar");
|
||||
cache()->insert("gz", "application/x-gzip");
|
||||
cache()->insert("h", "text/plain");
|
||||
cache()->insert("hdf", "application/x-hdf");
|
||||
cache()->insert("hlp", "application/winhlp");
|
||||
cache()->insert("hqx", "application/mac-binhex40");
|
||||
cache()->insert("hta", "application/hta");
|
||||
cache()->insert("htc", "text/x-component");
|
||||
cache()->insert("htm", "text/html");
|
||||
cache()->insert("html", "text/html");
|
||||
cache()->insert("htt", "text/webviewhtml");
|
||||
cache()->insert("ico", "image/x-icon");
|
||||
cache()->insert("ief", "image/ief");
|
||||
cache()->insert("iii", "application/x-iphone");
|
||||
cache()->insert("ins", "application/x-internet-signup");
|
||||
cache()->insert("isp", "application/x-internet-signup");
|
||||
cache()->insert("jfif", "image/pipeg");
|
||||
cache()->insert("jpe", "image/jpeg");
|
||||
cache()->insert("jpeg", "image/jpeg");
|
||||
cache()->insert("jpg", "image/jpeg");
|
||||
cache()->insert("js", "application/x-javascript");
|
||||
cache()->insert("json", "application/json");
|
||||
cache()->insert("latex", "application/x-latex");
|
||||
cache()->insert("lha", "application/octet-stream");
|
||||
cache()->insert("lsf", "video/x-la-asf");
|
||||
cache()->insert("lsx", "video/x-la-asf");
|
||||
cache()->insert("lzh", "application/octet-stream");
|
||||
cache()->insert("m13", "application/x-msmediaview");
|
||||
cache()->insert("m14", "application/x-msmediaview");
|
||||
cache()->insert("m3u", "audio/x-mpegurl");
|
||||
cache()->insert("m4v", "video/x-m4v");
|
||||
cache()->insert("man", "application/x-troff-man");
|
||||
cache()->insert("mdb", "application/x-msaccess");
|
||||
cache()->insert("me", "application/x-troff-me");
|
||||
cache()->insert("mht", "message/rfc822");
|
||||
cache()->insert("mhtml", "message/rfc822");
|
||||
cache()->insert("mid", "audio/mid");
|
||||
cache()->insert("mny", "application/x-msmoney");
|
||||
cache()->insert("mov", "video/quicktime");
|
||||
cache()->insert("movie", "video/x-sgi-movie""movie");
|
||||
cache()->insert("mp2", "video/mpeg");
|
||||
cache()->insert("mp3", "audio/mpeg");
|
||||
cache()->insert("mpa", "video/mpeg");
|
||||
cache()->insert("mpe", "video/mpeg");
|
||||
cache()->insert("mpeg", "video/mpeg");
|
||||
cache()->insert("mpg", "video/mpeg");
|
||||
cache()->insert("mpp", "application/vnd.ms-project");
|
||||
cache()->insert("mpv2", "video/mpeg");
|
||||
cache()->insert("ms", "application/x-troff-ms");
|
||||
cache()->insert("msg", "application/vnd.ms-outlook");
|
||||
cache()->insert("mvb", "application/x-msmediaview");
|
||||
cache()->insert("nc", "application/x-netcdf");
|
||||
cache()->insert("nws", "message/rfc822");
|
||||
cache()->insert("oda", "application/oda");
|
||||
cache()->insert("otf", "application/font-sfnt");
|
||||
cache()->insert("p10", "application/pkcs10");
|
||||
cache()->insert("p12", "application/x-pkcs12");
|
||||
cache()->insert("p7b", "application/x-pkcs7-certificates");
|
||||
cache()->insert("p7c", "application/x-pkcs7-mime");
|
||||
cache()->insert("p7m", "application/x-pkcs7-mime");
|
||||
cache()->insert("p7r", "application/x-pkcs7-certreqresp");
|
||||
cache()->insert("p7s", "application/x-pkcs7-signature");
|
||||
cache()->insert("pbm", "image/x-portable-bitmap");
|
||||
cache()->insert("pdf", "application/pdf");
|
||||
cache()->insert("pfx", "application/x-pkcs12");
|
||||
cache()->insert("pgm", "image/x-portable-graymap");
|
||||
cache()->insert("pko", "application/ynd.ms-pkipko");
|
||||
cache()->insert("pma", "application/x-perfmon");
|
||||
cache()->insert("pmc", "application/x-perfmon");
|
||||
cache()->insert("pml", "application/x-perfmon");
|
||||
cache()->insert("pmr", "application/x-perfmon");
|
||||
cache()->insert("pmw", "application/x-perfmon");
|
||||
cache()->insert("pnm", "image/x-portable-anymap");
|
||||
cache()->insert("pot", "application/vnd.ms-powerpoint");
|
||||
cache()->insert("ppm", "image/x-portable-pixmap");
|
||||
cache()->insert("pps", "application/vnd.ms-powerpoint");
|
||||
cache()->insert("ppt", "application/vnd.ms-powerpoint");
|
||||
cache()->insert("prf", "application/pics-rules");
|
||||
cache()->insert("ps", "application/postscript");
|
||||
cache()->insert("pub", "application/x-mspublisher");
|
||||
cache()->insert("qt", "video/quicktime");
|
||||
cache()->insert("ra", "audio/x-pn-realaudio");
|
||||
cache()->insert("ram", "audio/x-pn-realaudio");
|
||||
cache()->insert("ras", "image/x-cmu-raster");
|
||||
cache()->insert("rgb", "image/x-rgb");
|
||||
cache()->insert("rmi", "audio/mid");
|
||||
cache()->insert("roff", "application/x-troff");
|
||||
cache()->insert("rtf", "application/rtf""rtf");
|
||||
cache()->insert("rtx", "text/richtext""rtx");
|
||||
cache()->insert("scd", "application/x-msschedule");
|
||||
cache()->insert("sct", "text/scriptlet");
|
||||
cache()->insert("setpay", "application/set-payment-initiation");
|
||||
cache()->insert("setreg", "application/set-registration-initiation");
|
||||
cache()->insert("sh", "application/x-sh");
|
||||
cache()->insert("shar", "application/x-shar");
|
||||
cache()->insert("sit", "application/x-stuffit");
|
||||
cache()->insert("snd", "audio/basic");
|
||||
cache()->insert("spc", "application/x-pkcs7-certificates");
|
||||
cache()->insert("spl", "application/futuresplash");
|
||||
cache()->insert("src", "application/x-wais-source");
|
||||
cache()->insert("sst", "application/vnd.ms-pkicertstore");
|
||||
cache()->insert("stl", "application/vnd.ms-pkistl");
|
||||
cache()->insert("stm", "text/html");
|
||||
cache()->insert("sv4cpio", "application/x-sv4cpio");
|
||||
cache()->insert("sv4crc", "application/x-sv4crc");
|
||||
cache()->insert("svg", "image/svg+xml");
|
||||
cache()->insert("swf", "application/x-shockwave-flash");
|
||||
cache()->insert("t", "application/x-troff");
|
||||
cache()->insert("tar", "application/x-tar");
|
||||
cache()->insert("tcl", "application/x-tcl");
|
||||
cache()->insert("tex", "application/x-tex");
|
||||
cache()->insert("texi", "application/x-texinfo");
|
||||
cache()->insert("texinfo", "application/x-texinfo");
|
||||
cache()->insert("tgz", "application/x-compressed");
|
||||
cache()->insert("tif", "image/tiff");
|
||||
cache()->insert("tiff", "image/tiff");
|
||||
cache()->insert("tr", "application/x-troff");
|
||||
cache()->insert("trm", "application/x-msterminal");
|
||||
cache()->insert("tsv", "text/tab-separated-values");
|
||||
cache()->insert("txt", "text/plain");
|
||||
cache()->insert("ttf", "application/font-sfnt");
|
||||
cache()->insert("uls", "text/iuls");
|
||||
cache()->insert("ustar", "application/x-ustar");
|
||||
cache()->insert("vcf", "text/x-vcard");
|
||||
cache()->insert("vrml", "x-world/x-vrml");
|
||||
cache()->insert("wav", "audio/x-wav");
|
||||
cache()->insert("wcm", "application/vnd.ms-works");
|
||||
cache()->insert("wdb", "application/vnd.ms-works");
|
||||
cache()->insert("wks", "application/vnd.ms-works");
|
||||
cache()->insert("wmf", "application/x-msmetafile");
|
||||
cache()->insert("woff", "application/font-woff");
|
||||
cache()->insert("wps", "application/vnd.ms-works");
|
||||
cache()->insert("wri", "application/x-mswrite");
|
||||
cache()->insert("wrl", "x-world/x-vrml");
|
||||
cache()->insert("wrz", "x-world/x-vrml");
|
||||
cache()->insert("xaf", "x-world/x-vrml");
|
||||
cache()->insert("xbm", "image/x-xbitmap");
|
||||
cache()->insert("xla", "application/vnd.ms-excel");
|
||||
cache()->insert("xlc", "application/vnd.ms-excel");
|
||||
cache()->insert("xlm", "application/vnd.ms-excel");
|
||||
cache()->insert("xls", "application/vnd.ms-excel");
|
||||
cache()->insert("xlt", "application/vnd.ms-excel");
|
||||
cache()->insert("xlw", "application/vnd.ms-excel");
|
||||
cache()->insert("xof", "x-world/x-vrml");
|
||||
cache()->insert("xpm", "image/x-xpixmap");
|
||||
cache()->insert("xwd", "image/x-xwindowdump");
|
||||
cache()->insert("z", "application/x-compress");
|
||||
cache()->insert("zip", "application/zip");
|
||||
}
|
||||
}
|
||||
|
||||
QString mimeTypeForExtension(const QString &extension)
|
||||
{
|
||||
initCache();
|
||||
QString ext = extension;
|
||||
|
||||
const int lastDot = ext.lastIndexOf(QLatin1Char('.'));
|
||||
if (lastDot != -1) {
|
||||
const int extLength = ext.length() - lastDot - 1;
|
||||
ext = ext.right(extLength).toLower();
|
||||
}
|
||||
|
||||
QString mimeType = cache()->value(ext);
|
||||
|
||||
if (mimeType.isNull()) {
|
||||
mimeType = QString("application/octet-stream");
|
||||
}
|
||||
|
||||
return mimeType;
|
||||
}
|
||||
|
||||
QString mimeTypeForUrl(const QUrl &url)
|
||||
{
|
||||
initCache();
|
||||
QString path = url.path();
|
||||
|
||||
QString extension;
|
||||
QString mimeType;
|
||||
|
||||
const int lastDot = path.lastIndexOf(QLatin1Char('.'));
|
||||
if (lastDot != -1) {
|
||||
const int extLength = path.length() - lastDot - 1;
|
||||
extension = path.right(extLength).toLower();
|
||||
}
|
||||
|
||||
if (!extension.isNull()) {
|
||||
mimeType = cache()->value(extension);
|
||||
}
|
||||
if (mimeType.isNull()) {
|
||||
QMimeType mime = mimeDatabase()->mimeTypeForUrl(url);
|
||||
if (mime.isValid()) {
|
||||
mimeType = mime.name();
|
||||
if(!extension.isNull()) {
|
||||
cache()->insert(extension, mimeType);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (mimeType.isNull()) {
|
||||
mimeType = QString("application/octet-stream");
|
||||
}
|
||||
|
||||
qDebug() << mimeType;
|
||||
return mimeType;
|
||||
}
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
#ifndef MIMECACHE_H
|
||||
#define MIMECACHE_H
|
||||
|
||||
class QString;
|
||||
class QUrl;
|
||||
|
||||
QString mimeTypeForExtension(const QString &extension);
|
||||
QString mimeTypeForUrl(const QUrl &url);
|
||||
|
||||
#endif
|
||||
@@ -1,66 +0,0 @@
|
||||
/****************************************************************************
|
||||
**
|
||||
** Copyright (C) 2016 The Qt Company Ltd.
|
||||
** Contact: https://www.qt.io/licensing/
|
||||
**
|
||||
** This file is part of the QtCore module of the Qt Toolkit.
|
||||
**
|
||||
** $QT_BEGIN_LICENSE:LGPL$
|
||||
** Commercial License Usage
|
||||
** Licensees holding valid commercial Qt licenses may use this file in
|
||||
** accordance with the commercial license agreement provided with the
|
||||
** Software or, alternatively, in accordance with the terms contained in
|
||||
** a written agreement between you and The Qt Company. For licensing terms
|
||||
** and conditions see https://www.qt.io/terms-conditions. For further
|
||||
** information use the contact form at https://www.qt.io/contact-us.
|
||||
**
|
||||
** GNU Lesser General Public License Usage
|
||||
** Alternatively, this file may be used under the terms of the GNU Lesser
|
||||
** General Public License version 3 as published by the Free Software
|
||||
** Foundation and appearing in the file LICENSE.LGPL3 included in the
|
||||
** packaging of this file. Please review the following information to
|
||||
** ensure the GNU Lesser General Public License version 3 requirements
|
||||
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
|
||||
**
|
||||
** GNU General Public License Usage
|
||||
** Alternatively, this file may be used under the terms of the GNU
|
||||
** General Public License version 2.0 or (at your option) the GNU General
|
||||
** Public license version 3 or any later version approved by the KDE Free
|
||||
** Qt Foundation. The licenses are as published by the Free Software
|
||||
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
|
||||
** included in the packaging of this file. Please review the following
|
||||
** information to ensure the GNU General Public License requirements will
|
||||
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
|
||||
** https://www.gnu.org/licenses/gpl-3.0.html.
|
||||
**
|
||||
** $QT_END_LICENSE$
|
||||
**
|
||||
****************************************************************************/
|
||||
|
||||
/*
|
||||
* This is a precompiled header file for use in Xcode / Mac GCC /
|
||||
* GCC >= 3.4 / VC to greatly speed the building of Qt. It may also be
|
||||
* of use to people developing their own project, but it is probably
|
||||
* better to define your own header. Use of this header is currently
|
||||
* UNSUPPORTED.
|
||||
*/
|
||||
|
||||
|
||||
#if defined __cplusplus
|
||||
// for rand_s, _CRT_RAND_S must be #defined before #including stdlib.h.
|
||||
// put it at the beginning so some indirect inclusion doesn't break it
|
||||
#ifndef _CRT_RAND_S
|
||||
#define _CRT_RAND_S
|
||||
#endif
|
||||
#include <stdlib.h>
|
||||
#include <qglobal.h>
|
||||
#ifdef Q_OS_WIN
|
||||
# define _POSIX_
|
||||
# include <limits.h>
|
||||
# undef _POSIX_
|
||||
#endif
|
||||
#include <QtCore/QtCore>
|
||||
#ifndef Q_OS_WIN
|
||||
#include <QtQuick/QtQuick>
|
||||
#endif
|
||||
#endif
|
||||
@@ -1,17 +0,0 @@
|
||||
#include "plugin.h"
|
||||
|
||||
#include "amneziawebview.h"
|
||||
|
||||
QT_BEGIN_NAMESPACE
|
||||
|
||||
void WebViewPlugin::registerTypes(const char* uri)
|
||||
{
|
||||
#ifndef QT_NO_ACTION
|
||||
qmlRegisterAnonymousType<QAction>(uri, 1);
|
||||
#endif
|
||||
qmlRegisterAnonymousType<AmneziaWebViewSettings>(uri, 1);
|
||||
qmlRegisterType<AmneziaWebView>(uri, 1, 0, "AmneziaWebView");
|
||||
qmlRegisterRevision<AmneziaWebView, 0>("AmneziaWebView", 1, 0);
|
||||
}
|
||||
|
||||
QT_END_NAMESPACE
|
||||
@@ -1,15 +0,0 @@
|
||||
#include <QQmlExtensionPlugin>
|
||||
|
||||
QT_BEGIN_NAMESPACE
|
||||
|
||||
class WebViewPlugin : public QQmlExtensionPlugin
|
||||
{
|
||||
Q_OBJECT
|
||||
Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QQmlExtensionInterface" FILE "webview.json")
|
||||
Q_INTERFACES(QQmlExtensionInterface)
|
||||
|
||||
public:
|
||||
void registerTypes(const char* uri) override;
|
||||
};
|
||||
|
||||
QT_END_NAMESPACE
|
||||
@@ -1,2 +0,0 @@
|
||||
module AmneziaWebView
|
||||
plugin webview
|
||||
@@ -1,37 +0,0 @@
|
||||
#include <QtCore/QString>
|
||||
#include <QtCore/QUrl>
|
||||
#include <QtCore/QFile>
|
||||
#include <QtCore/QByteArray>
|
||||
|
||||
#include "qrchandler.h"
|
||||
#include "mimecache.h"
|
||||
|
||||
QString QrcHandler::scheme()
|
||||
{
|
||||
return QString("qrc");
|
||||
}
|
||||
|
||||
QByteArray QrcHandler::dataForUrl(const QUrl &url) const
|
||||
{
|
||||
QString requestUrl(QString(":/%1").arg(url.path()));
|
||||
QFile resource(requestUrl);
|
||||
QByteArray buffer;
|
||||
if (resource.exists() && resource.open(QIODevice::ReadOnly)) {
|
||||
|
||||
buffer = resource.readAll();
|
||||
resource.close();
|
||||
}
|
||||
return buffer;
|
||||
}
|
||||
|
||||
bool QrcHandler::canHandleUrl(const QUrl &url) const
|
||||
{
|
||||
if (scheme() == url.scheme())
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
QString QrcHandler::mimeTypeForUrl(const QUrl &url) const
|
||||
{
|
||||
return mimeTypeForExtension(url.path().section('.', -1));
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
#ifndef QRCHANDLER_H
|
||||
#define QRCHANDLER_H
|
||||
|
||||
class QString;
|
||||
class QByteArray;
|
||||
class QUrl;
|
||||
|
||||
class QrcHandler
|
||||
{
|
||||
public:
|
||||
explicit QrcHandler();
|
||||
static QString scheme();
|
||||
bool canHandleUrl(const QUrl &url) const;
|
||||
QByteArray dataForUrl(const QUrl &url) const;
|
||||
QString mimeTypeForUrl(const QUrl &url) const;
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -1,10 +0,0 @@
|
||||
#include <QtCore/QString>
|
||||
#include <QtCore/QUrl>
|
||||
#include <QtCore/QFile>
|
||||
#include <QtCore/QByteArray>
|
||||
|
||||
#include "qrchandler.h"
|
||||
#include "mimecache.h"
|
||||
|
||||
QrcHandler::QrcHandler()
|
||||
{}
|
||||
@@ -1,189 +0,0 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <MobileCoreServices/UTCoreTypes.h>
|
||||
#import <MobileCoreServices/UTType.h>
|
||||
|
||||
#include <QtCore/QFile>
|
||||
#include <QtCore/QUrl>
|
||||
#include <QtCore/QString>
|
||||
#include <QtCore/QDebug>
|
||||
#include "mimecache.h"
|
||||
|
||||
#include "qrchandler.h"
|
||||
#define kProtocolQrcScheme @"qrc"
|
||||
|
||||
#if !defined(ENABLE_WKWEBVIEW)
|
||||
@interface QrcProtocol : NSURLProtocol
|
||||
|
||||
+ (NSString*)protocolScheme;
|
||||
+ (NSString*)requestVarsKey;
|
||||
+ (void)registerProtocol;
|
||||
|
||||
@end
|
||||
|
||||
@interface NSURLRequest (QrcProtocol)
|
||||
- (NSDictionary *)requestVars;
|
||||
@end
|
||||
|
||||
@interface NSMutableURLRequest (QrcProtocol)
|
||||
- (void)setRequestVars:(NSDictionary *)vars;
|
||||
@end
|
||||
#endif
|
||||
|
||||
QrcHandler::QrcHandler()
|
||||
{
|
||||
#if !defined(ENABLE_WKWEBVIEW)
|
||||
[QrcProtocol registerProtocol];
|
||||
#endif
|
||||
}
|
||||
|
||||
#if !defined(ENABLE_WKWEBVIEW)
|
||||
|
||||
@implementation NSURLRequest (QrcProtocol)
|
||||
|
||||
- (NSDictionary *)requestVars {
|
||||
NSLog(@"%@ received %@", self, NSStringFromSelector(_cmd));
|
||||
return [NSURLProtocol propertyForKey:[QrcProtocol requestVarsKey] inRequest:self];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation NSMutableURLRequest (QrcProtocol)
|
||||
|
||||
- (void)setRequestVars:(NSDictionary *)requestVars {
|
||||
|
||||
NSLog(@"%@ received %@", self, NSStringFromSelector(_cmd));
|
||||
|
||||
NSDictionary *specialVarsCopy = [requestVars copy];
|
||||
[NSURLProtocol setProperty:specialVarsCopy forKey:[QrcProtocol requestVarsKey] inRequest:self];
|
||||
[specialVarsCopy release];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation QrcProtocol
|
||||
|
||||
+ (BOOL)canInitWithRequest:(NSURLRequest *)request
|
||||
{
|
||||
NSString *scheme = request.URL.scheme;
|
||||
if ([kProtocolQrcScheme caseInsensitiveCompare:scheme] == NSOrderedSame) {
|
||||
return YES;
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request
|
||||
{
|
||||
return request;
|
||||
}
|
||||
|
||||
+ (NSString*) protocolScheme
|
||||
{
|
||||
return kProtocolQrcScheme;
|
||||
}
|
||||
|
||||
+ (NSString*) requestVarsKey {
|
||||
return @"requestVars";
|
||||
}
|
||||
|
||||
+ (void)registerProtocol
|
||||
{
|
||||
static bool qrcProtocolRegistered = false;
|
||||
if (!qrcProtocolRegistered) {
|
||||
[NSURLProtocol registerClass:[QrcProtocol class]];
|
||||
qrcProtocolRegistered = true;
|
||||
}
|
||||
}
|
||||
|
||||
+ (NSString*)headFromHtml:(NSString*)html
|
||||
{
|
||||
if (!html) return nil;
|
||||
|
||||
NSString *head = nil;
|
||||
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(?<=<head>)[\\w\\W.]*(?=</head>)" options:NSRegularExpressionCaseInsensitive error:nil];
|
||||
NSTextCheckingResult *headResult = [regex firstMatchInString:html options:0 range:NSMakeRange(0, html.length)];
|
||||
|
||||
if (headResult && headResult.range.location != NSNotFound) {
|
||||
head = [html substringWithRange:[headResult range]];
|
||||
}
|
||||
return head;
|
||||
}
|
||||
|
||||
+ (NSString *)charsetFromHtml:(NSString *)html
|
||||
{
|
||||
if (!html) return nil;
|
||||
|
||||
NSString *charset = nil;
|
||||
NSString *charsetPattern = @"((?<=charset=)\\s*[a-zA-Z0-9-]*)";
|
||||
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:charsetPattern options: NSRegularExpressionCaseInsensitive error:nil];
|
||||
NSTextCheckingResult *charsetResult = [regex firstMatchInString:html options:kNilOptions range:NSMakeRange(0, [html length])];
|
||||
if (charsetResult && charsetResult.range.location != NSNotFound) {
|
||||
charset = [[html substringWithRange:[charsetResult range]] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
|
||||
charset = [charset lowercaseString];
|
||||
}
|
||||
return charset;
|
||||
}
|
||||
|
||||
|
||||
- (void)startLoading
|
||||
{
|
||||
/* retrieve the current request. */
|
||||
NSURLRequest *request = [self request];
|
||||
NSString *url = [[request URL] path];
|
||||
//NSString *absoluteString = request.URL.absoluteString;
|
||||
|
||||
//NSString *mimeType = [self mimeTypeForExtension: [url pathExtension]];
|
||||
NSString *mimeType = mimeTypeForExtension(QString::fromNSString(url.pathExtension)).toNSString();
|
||||
|
||||
/* extract our special variables from the request. */
|
||||
//NSDictionary *requestVars = [request requestVars];
|
||||
NSData *pageData = nil;
|
||||
|
||||
QString requestUrl(QString(":/%1").arg(QString::fromNSString(url)));
|
||||
QFile resource(requestUrl);
|
||||
if (resource.exists() && resource.open(QIODevice::ReadOnly)) {
|
||||
|
||||
QByteArray buffer = resource.readAll();
|
||||
|
||||
//pageData = [[NSData alloc] initWithBytes:buffer.constData() length:buffer.size()];
|
||||
pageData = [NSData dataWithBytes:buffer.constData() length:buffer.size()];
|
||||
|
||||
resource.close();
|
||||
}
|
||||
|
||||
if (pageData) {
|
||||
|
||||
NSString *encoding = @"utf-8";
|
||||
if ([mimeType isEqualToString:@"text/html"]) {
|
||||
|
||||
NSString *content = [[NSString alloc] initWithBytesNoCopy: (char* )[pageData bytes] length:pageData.length encoding:NSISOLatin1StringEncoding freeWhenDone:NO];
|
||||
|
||||
NSString *charset = [QrcProtocol charsetFromHtml:[QrcProtocol headFromHtml:content]];
|
||||
if (charset) {
|
||||
encoding = charset;
|
||||
}
|
||||
[content autorelease];
|
||||
}
|
||||
|
||||
NSURLResponse *response = [[NSURLResponse alloc]initWithURL:self.request.URL
|
||||
MIMEType:mimeType
|
||||
expectedContentLength:[pageData length]
|
||||
textEncodingName:encoding];
|
||||
|
||||
[[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
|
||||
[[self client] URLProtocol:self didLoadData:pageData];
|
||||
[[self client] URLProtocolDidFinishLoading:self];
|
||||
[response autorelease];
|
||||
}
|
||||
else {
|
||||
[[self client] URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)stopLoading
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
@@ -1,202 +0,0 @@
|
||||
|
||||
#include <QDir>
|
||||
#include <QFileInfo>
|
||||
#include <QFont>
|
||||
#include <QGuiApplication>
|
||||
#include <QHash>
|
||||
#include <QSharedData>
|
||||
#include <QStandardPaths>
|
||||
#include <QUrl>
|
||||
|
||||
#include "websettings.h"
|
||||
#include "amneziawebview_p.h"
|
||||
|
||||
AmneziaWebViewSettings::AmneziaWebViewSettings(AmneziaWebView *view): QObject(view), s(new WebSettings(view))
|
||||
{}
|
||||
|
||||
Q_GLOBAL_STATIC(QList<WebSettings*>, allSettings)
|
||||
|
||||
void WebSettings::apply()
|
||||
{
|
||||
if (view) {
|
||||
|
||||
WebSettings* global = WebSettings::globalSettings();
|
||||
|
||||
|
||||
QString family = fontFamilies.value(WebSettings::StandardFont,
|
||||
global->fontFamilies.value(WebSettings::StandardFont));
|
||||
view->setStandardFontFamily(family);
|
||||
|
||||
|
||||
int size = fontSizes.value(WebSettings::DefaultFontSize,
|
||||
global->fontSizes.value(WebSettings::DefaultFontSize));
|
||||
view->setDefaultFontSize(size);
|
||||
|
||||
bool value = attributes.value(WebSettings::AutoLoadImages,
|
||||
global->attributes.value(WebSettings::AutoLoadImages));
|
||||
|
||||
QString encoding = !defaultTextEncoding.isEmpty() ? defaultTextEncoding: global->defaultTextEncoding;
|
||||
|
||||
|
||||
Q_UNUSED(value)
|
||||
|
||||
} else {
|
||||
|
||||
QList<WebSettings*> settings = *::allSettings();
|
||||
for (int i = 0; i < settings.count(); ++i)
|
||||
settings[i]->apply();
|
||||
}
|
||||
}
|
||||
|
||||
WebSettings* WebSettings::globalSettings()
|
||||
{
|
||||
static WebSettings *global = nullptr;
|
||||
if (!global) {
|
||||
global = new WebSettings;
|
||||
}
|
||||
return global;
|
||||
}
|
||||
|
||||
WebSettings::WebSettings()
|
||||
{
|
||||
// Initialize our global defaults
|
||||
fontSizes.insert(WebSettings::MinimumFontSize, 0);
|
||||
fontSizes.insert(WebSettings::MinimumLogicalFontSize, 0);
|
||||
fontSizes.insert(WebSettings::DefaultFontSize, 16);
|
||||
fontSizes.insert(WebSettings::DefaultFixedFontSize, 13);
|
||||
|
||||
QFont defaultFont;
|
||||
defaultFont.setStyleHint(QFont::Serif);
|
||||
fontFamilies.insert(WebSettings::StandardFont, defaultFont.defaultFamily());
|
||||
fontFamilies.insert(WebSettings::SerifFont, defaultFont.defaultFamily());
|
||||
|
||||
defaultFont.setStyleHint(QFont::Fantasy);
|
||||
fontFamilies.insert(WebSettings::FantasyFont, defaultFont.defaultFamily());
|
||||
|
||||
defaultFont.setStyleHint(QFont::Cursive);
|
||||
fontFamilies.insert(WebSettings::CursiveFont, defaultFont.defaultFamily());
|
||||
|
||||
defaultFont.setStyleHint(QFont::SansSerif);
|
||||
fontFamilies.insert(WebSettings::SansSerifFont, defaultFont.defaultFamily());
|
||||
|
||||
defaultFont.setStyleHint(QFont::Monospace);
|
||||
fontFamilies.insert(WebSettings::FixedFont, defaultFont.defaultFamily());
|
||||
|
||||
attributes.insert(WebSettings::AutoLoadImages, true);
|
||||
attributes.insert(WebSettings::DnsPrefetchEnabled, false);
|
||||
attributes.insert(WebSettings::JavascriptEnabled, true);
|
||||
attributes.insert(WebSettings::SpatialNavigationEnabled, false);
|
||||
attributes.insert(WebSettings::LinksIncludedInFocusChain, true);
|
||||
attributes.insert(WebSettings::ZoomTextOnly, false);
|
||||
attributes.insert(WebSettings::PrintElementBackgrounds, true);
|
||||
attributes.insert(WebSettings::OfflineStorageDatabaseEnabled, false);
|
||||
attributes.insert(WebSettings::OfflineWebApplicationCacheEnabled, false);
|
||||
attributes.insert(WebSettings::LocalStorageEnabled, false);
|
||||
attributes.insert(WebSettings::LocalContentCanAccessRemoteUrls, false);
|
||||
attributes.insert(WebSettings::LocalContentCanAccessFileUrls, true);
|
||||
attributes.insert(WebSettings::AcceleratedCompositingEnabled, true);
|
||||
attributes.insert(WebSettings::WebGLEnabled, true);
|
||||
attributes.insert(WebSettings::WebAudioEnabled, false);
|
||||
attributes.insert(WebSettings::CSSRegionsEnabled, true);
|
||||
attributes.insert(WebSettings::CSSGridLayoutEnabled, false);
|
||||
attributes.insert(WebSettings::HyperlinkAuditingEnabled, false);
|
||||
attributes.insert(WebSettings::TiledBackingStoreEnabled, false);
|
||||
attributes.insert(WebSettings::FrameFlatteningEnabled, false);
|
||||
attributes.insert(WebSettings::SiteSpecificQuirksEnabled, true);
|
||||
attributes.insert(WebSettings::ScrollAnimatorEnabled, false);
|
||||
attributes.insert(WebSettings::CaretBrowsingEnabled, false);
|
||||
attributes.insert(WebSettings::NotificationsEnabled, true);
|
||||
|
||||
#if defined(Q_OS_WIN32) && defined(DEBUG)
|
||||
attributes.insert(WebSettings::DeveloperExtrasEnabled,true);
|
||||
#endif
|
||||
}
|
||||
|
||||
/*!
|
||||
\internal
|
||||
*/
|
||||
WebSettings::WebSettings(AmneziaWebView *v)
|
||||
: view(v)
|
||||
|
||||
{
|
||||
allSettings()->append(this);
|
||||
}
|
||||
|
||||
WebSettings::~WebSettings()
|
||||
{
|
||||
if (view)
|
||||
allSettings()->removeAll(this);
|
||||
|
||||
}
|
||||
|
||||
void WebSettings::setFontSize(FontSize type, int size)
|
||||
{
|
||||
fontSizes.insert(type, size);
|
||||
apply();
|
||||
}
|
||||
|
||||
int WebSettings::fontSize(FontSize type) const
|
||||
{
|
||||
int defaultValue = 0;
|
||||
if (view) {
|
||||
WebSettings* global = WebSettings::globalSettings();
|
||||
defaultValue = global->fontSizes.value(type);
|
||||
}
|
||||
return fontSizes.value(type, defaultValue);
|
||||
}
|
||||
|
||||
void WebSettings::resetFontSize(FontSize type)
|
||||
{
|
||||
if (view) {
|
||||
fontSizes.remove(type);
|
||||
apply();
|
||||
}
|
||||
}
|
||||
|
||||
void WebSettings::setFontFamily(FontFamily which, const QString& family)
|
||||
{
|
||||
fontFamilies.insert(which, family);
|
||||
apply();
|
||||
}
|
||||
|
||||
QString WebSettings::fontFamily(FontFamily which) const
|
||||
{
|
||||
QString defaultValue;
|
||||
if (view) {
|
||||
WebSettings* global = WebSettings::globalSettings();
|
||||
defaultValue = global->fontFamilies.value(which);
|
||||
}
|
||||
return fontFamilies.value(which, defaultValue);
|
||||
}
|
||||
|
||||
void WebSettings::resetFontFamily(FontFamily which)
|
||||
{
|
||||
if (view) {
|
||||
fontFamilies.remove(which);
|
||||
apply();
|
||||
}
|
||||
}
|
||||
|
||||
void WebSettings::setAttribute(WebAttribute attr, bool on)
|
||||
{
|
||||
attributes.insert(attr, on);
|
||||
apply();
|
||||
}
|
||||
|
||||
bool WebSettings::testAttribute(WebAttribute attr) const
|
||||
{
|
||||
bool defaultValue = false;
|
||||
if (view) {
|
||||
WebSettings* global = WebSettings::globalSettings();
|
||||
defaultValue = global->attributes.value(attr);
|
||||
}
|
||||
return attributes.value(attr, defaultValue);
|
||||
}
|
||||
|
||||
void WebSettings::resetAttribute(WebAttribute attr)
|
||||
{
|
||||
if (view) {
|
||||
attributes.remove(attr);
|
||||
apply();
|
||||
}
|
||||
}
|
||||
@@ -1,144 +0,0 @@
|
||||
#ifndef WEBSETTINGS_H
|
||||
#define WEBSETTINGS_H
|
||||
|
||||
#include <QtQml>
|
||||
|
||||
class AmneziaWebView;
|
||||
class AmneziaWebViewPrivate;
|
||||
class WebSettingsData;
|
||||
|
||||
class WebSettings
|
||||
{
|
||||
public:
|
||||
enum FontFamily {
|
||||
StandardFont,
|
||||
FixedFont,
|
||||
SerifFont,
|
||||
SansSerifFont,
|
||||
CursiveFont,
|
||||
FantasyFont
|
||||
};
|
||||
enum WebAttribute {
|
||||
AutoLoadImages,
|
||||
JavascriptEnabled,
|
||||
JavaEnabled,
|
||||
PluginsEnabled,
|
||||
PrivateBrowsingEnabled,
|
||||
JavascriptCanOpenWindows,
|
||||
JavascriptCanAccessClipboard,
|
||||
DeveloperExtrasEnabled,
|
||||
LinksIncludedInFocusChain,
|
||||
ZoomTextOnly,
|
||||
PrintElementBackgrounds,
|
||||
OfflineStorageDatabaseEnabled,
|
||||
OfflineWebApplicationCacheEnabled,
|
||||
LocalStorageEnabled,
|
||||
LocalContentCanAccessRemoteUrls,
|
||||
DnsPrefetchEnabled,
|
||||
XSSAuditingEnabled,
|
||||
AcceleratedCompositingEnabled,
|
||||
SpatialNavigationEnabled,
|
||||
LocalContentCanAccessFileUrls,
|
||||
TiledBackingStoreEnabled,
|
||||
FrameFlatteningEnabled,
|
||||
SiteSpecificQuirksEnabled,
|
||||
JavascriptCanCloseWindows,
|
||||
WebGLEnabled,
|
||||
CSSRegionsEnabled,
|
||||
HyperlinkAuditingEnabled,
|
||||
CSSGridLayoutEnabled,
|
||||
ScrollAnimatorEnabled,
|
||||
CaretBrowsingEnabled,
|
||||
NotificationsEnabled,
|
||||
WebAudioEnabled
|
||||
};
|
||||
enum WebGraphic {
|
||||
MissingImageGraphic,
|
||||
MissingPluginGraphic,
|
||||
DefaultFrameIconGraphic,
|
||||
TextAreaSizeGripCornerGraphic,
|
||||
DeleteButtonGraphic,
|
||||
InputSpeechButtonGraphic,
|
||||
SearchCancelButtonGraphic,
|
||||
SearchCancelButtonPressedGraphic
|
||||
};
|
||||
enum FontSize {
|
||||
MinimumFontSize,
|
||||
MinimumLogicalFontSize,
|
||||
DefaultFontSize,
|
||||
DefaultFixedFontSize
|
||||
};
|
||||
enum ThirdPartyCookiePolicy {
|
||||
AlwaysAllowThirdPartyCookies,
|
||||
AlwaysBlockThirdPartyCookies,
|
||||
AllowThirdPartyWithExistingCookies
|
||||
};
|
||||
|
||||
static WebSettings *globalSettings();
|
||||
|
||||
void setFontSize(FontSize type, int size);
|
||||
int fontSize(FontSize type) const;
|
||||
void resetFontSize(FontSize type);
|
||||
|
||||
|
||||
void setFontFamily(FontFamily which, const QString &family);
|
||||
QString fontFamily(FontFamily which) const;
|
||||
void resetFontFamily(FontFamily which);
|
||||
|
||||
void setAttribute(WebAttribute attr, bool on);
|
||||
bool testAttribute(WebAttribute attr) const;
|
||||
void resetAttribute(WebAttribute attr);
|
||||
|
||||
void apply();
|
||||
|
||||
WebSettings();
|
||||
explicit WebSettings(AmneziaWebView *v);
|
||||
virtual ~WebSettings();
|
||||
|
||||
private:
|
||||
friend class WebSettingsData;
|
||||
friend class AmneziaWebViewPrivate;
|
||||
friend class WebViewPrivate;
|
||||
|
||||
|
||||
|
||||
Q_DISABLE_COPY(WebSettings)
|
||||
|
||||
QHash<int, QString> fontFamilies;
|
||||
QHash<int, int> fontSizes;
|
||||
QHash<int, bool> attributes;
|
||||
QString defaultTextEncoding;
|
||||
AmneziaWebView *view;
|
||||
|
||||
};
|
||||
|
||||
class AmneziaWebViewSettings : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
Q_PROPERTY(int defaultFontSize READ defaultFontSize WRITE setDefaultFontSize)
|
||||
Q_PROPERTY(QString standardFontFamily READ standardFontFamily WRITE setStandardFontFamily)
|
||||
Q_PROPERTY(bool developerExtrasEnabled READ developerExtrasEnabled WRITE setDeveloperExtrasEnabled)
|
||||
|
||||
public:
|
||||
explicit AmneziaWebViewSettings(AmneziaWebView *parent);
|
||||
|
||||
int defaultFontSize() const { return s->fontSize(WebSettings::DefaultFontSize); }
|
||||
void setDefaultFontSize(int size) { s->setFontSize(WebSettings::DefaultFontSize, size); }
|
||||
|
||||
QString standardFontFamily() const { return s->fontFamily(WebSettings::StandardFont); }
|
||||
void setStandardFontFamily(const QString& f) { s->setFontFamily(WebSettings::StandardFont, f); }
|
||||
|
||||
bool developerExtrasEnabled() const { return s->testAttribute(WebSettings::DeveloperExtrasEnabled); }
|
||||
void setDeveloperExtrasEnabled(bool on) { s->setAttribute(WebSettings::DeveloperExtrasEnabled, on); }
|
||||
|
||||
void apply() { s->apply(); }
|
||||
|
||||
private:
|
||||
QScopedPointer<WebSettings> s;
|
||||
};
|
||||
|
||||
QML_DECLARE_TYPE(AmneziaWebViewSettings)
|
||||
|
||||
|
||||
#endif
|
||||
@@ -1,3 +0,0 @@
|
||||
{
|
||||
"Keys": [ "AmneziaWebView" ]
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
{
|
||||
"primary": "http",
|
||||
"retry_count": 3,
|
||||
"timeout_ms": 10000,
|
||||
|
||||
"http": {
|
||||
"enabled": true,
|
||||
"endpoint": "https://your-gateway.example.com/"
|
||||
},
|
||||
|
||||
"dns_transports": [
|
||||
{
|
||||
"type": "udp",
|
||||
"server": "your-gateway.example.com",
|
||||
"domain": "gateway.example.com",
|
||||
"port": 5453
|
||||
},
|
||||
{
|
||||
"type": "tcp",
|
||||
"server": "your-gateway.example.com",
|
||||
"domain": "gateway.example.com",
|
||||
"port": 5453
|
||||
},
|
||||
{
|
||||
"type": "dot",
|
||||
"server": "your-gateway.example.com",
|
||||
"domain": "gateway.example.com",
|
||||
"port": 8853
|
||||
},
|
||||
{
|
||||
"type": "doh",
|
||||
"server": "your-gateway.example.com",
|
||||
"domain": "gateway.example.com",
|
||||
"port": 443,
|
||||
"path": "/dns-query"
|
||||
},
|
||||
{
|
||||
"type": "doq",
|
||||
"server": "your-gateway.example.com",
|
||||
"domain": "gateway.example.com",
|
||||
"port": 8854
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -163,7 +163,6 @@
|
||||
<file>ui/qml/Controls2/ListViewWithRadioButtonType.qml</file>
|
||||
<file>ui/qml/Controls2/PageType.qml</file>
|
||||
<file>ui/qml/Controls2/PopupType.qml</file>
|
||||
<file>ui/qml/Controls2/PremiumBannerType.qml</file>
|
||||
<file>ui/qml/Controls2/ProgressBarType.qml</file>
|
||||
<file>ui/qml/Controls2/ScrollBarType.qml</file>
|
||||
<file>ui/qml/Controls2/StackViewType.qml</file>
|
||||
@@ -227,7 +226,6 @@
|
||||
<file>ui/qml/Pages2/PageProtocolWireGuardClientSettings.qml</file>
|
||||
<file>ui/qml/Pages2/PageSetupWizardApiServiceInfo.qml</file>
|
||||
<file>ui/qml/Pages2/PageSetupWizardApiServicesList.qml</file>
|
||||
<file>ui/qml/Pages2/PageSetupWizardPremiumWebView.qml</file>
|
||||
<file>ui/qml/Pages2/PageSetupWizardConfigSource.qml</file>
|
||||
<file>ui/qml/Pages2/PageSetupWizardCredentials.qml</file>
|
||||
<file>ui/qml/Pages2/PageSetupWizardEasy.qml</file>
|
||||
@@ -249,16 +247,9 @@
|
||||
<file>ui/qml/Pages2/PageSettingsApiNativeConfigs.qml</file>
|
||||
<file>ui/qml/Pages2/PageSettingsApiDevices.qml</file>
|
||||
<file>images/controls/monitor.svg</file>
|
||||
<file>ui/qml/Components/ApiPremV1MigrationDrawer.qml</file>
|
||||
<file>ui/qml/Components/ApiPremV1SubListDrawer.qml</file>
|
||||
<file>ui/qml/Components/OtpCodeDrawer.qml</file>
|
||||
<file>ui/qml/Components/AwgTextField.qml</file>
|
||||
<file>ui/qml/Pages2/PageSettingsApiSubscriptionKey.qml</file>
|
||||
<file>ui/qml/Components/SmartScroll.qml</file>
|
||||
<file>ui/qml/Components/AmneziaWebViewPanel.qml</file>
|
||||
</qresource>
|
||||
<qresource prefix="/AmneziaWebView">
|
||||
<file>core/webview/qmldir</file>
|
||||
</qresource>
|
||||
<qresource prefix="/countriesFlags">
|
||||
<file>images/flagKit/ZW.svg</file>
|
||||
|
||||
+2
-1
@@ -14,7 +14,8 @@ namespace
|
||||
const char cloudFlareNs1[] = "1.1.1.1";
|
||||
const char cloudFlareNs2[] = "1.0.0.1";
|
||||
|
||||
constexpr char gatewayEndpoint[] = "http://gw.amnezia.org:80/";
|
||||
//constexpr char gatewayEndpoint[] = "http://localhost:80/";
|
||||
constexpr char gatewayEndpoint[] = "http://localhost:80/";
|
||||
}
|
||||
|
||||
Settings::Settings(QObject *parent) : QObject(parent), m_settings(ORGANIZATION_NAME, APPLICATION_NAME, this)
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
cmake_minimum_required(VERSION 3.25.0)
|
||||
project(TransportTest)
|
||||
|
||||
set(CLIENT_ROOT_DIR ${CMAKE_CURRENT_LIST_DIR}/..)
|
||||
|
||||
find_package(Qt6 REQUIRED COMPONENTS Core Network Test)
|
||||
|
||||
set(QSIMPLECRYPTO_DIR ${CLIENT_ROOT_DIR}/3rd/QSimpleCrypto/src)
|
||||
|
||||
set(OPENSSL_ROOT_DIR "${CLIENT_ROOT_DIR}/3rd-prebuilt/3rd-prebuilt/openssl/")
|
||||
if(WIN32)
|
||||
set(OPENSSL_INCLUDE_DIR "${OPENSSL_ROOT_DIR}/windows/include")
|
||||
if("${CMAKE_SIZEOF_VOID_P}" STREQUAL "8")
|
||||
set(OPENSSL_LIB_SSL "${OPENSSL_ROOT_DIR}/windows/win64/libssl.lib")
|
||||
set(OPENSSL_LIB_CRYPTO "${OPENSSL_ROOT_DIR}/windows/win64/libcrypto.lib")
|
||||
else()
|
||||
set(OPENSSL_LIB_SSL "${OPENSSL_ROOT_DIR}/windows/win32/libssl.lib")
|
||||
set(OPENSSL_LIB_CRYPTO "${OPENSSL_ROOT_DIR}/windows/win32/libcrypto.lib")
|
||||
endif()
|
||||
elseif(APPLE AND NOT IOS)
|
||||
set(OPENSSL_INCLUDE_DIR "${OPENSSL_ROOT_DIR}/macos/include")
|
||||
set(OPENSSL_LIB_SSL "${OPENSSL_ROOT_DIR}/macos/lib/libssl.a")
|
||||
set(OPENSSL_LIB_CRYPTO "${OPENSSL_ROOT_DIR}/macos/lib/libcrypto.a")
|
||||
elseif(LINUX)
|
||||
set(OPENSSL_INCLUDE_DIR "${OPENSSL_ROOT_DIR}/linux/include")
|
||||
set(OPENSSL_LIB_SSL "${OPENSSL_ROOT_DIR}/linux/x86_64/libssl.a")
|
||||
set(OPENSSL_LIB_CRYPTO "${OPENSSL_ROOT_DIR}/linux/x86_64/libcrypto.a")
|
||||
endif()
|
||||
|
||||
add_definitions(-DPROD_AGW_PUBLIC_KEY="$ENV{PROD_AGW_PUBLIC_KEY}")
|
||||
add_definitions(-DDEV_AGW_PUBLIC_KEY="$ENV{DEV_AGW_PUBLIC_KEY}")
|
||||
|
||||
add_definitions(-DAGW_DNS_SERVER="$ENV{AGW_DNS_SERVER}")
|
||||
add_definitions(-DAGW_DNS_DOMAIN="$ENV{AGW_DNS_DOMAIN}")
|
||||
add_definitions(-DAGW_DNS_PRIMARY="$ENV{AGW_DNS_PRIMARY}")
|
||||
add_definitions(-DAGW_DNS_PORT_UDP="$ENV{AGW_DNS_PORT_UDP}")
|
||||
add_definitions(-DAGW_DNS_PORT_DOT="$ENV{AGW_DNS_PORT_DOT}")
|
||||
add_definitions(-DAGW_DNS_PORT_DOH="$ENV{AGW_DNS_PORT_DOH}")
|
||||
add_definitions(-DAGW_DNS_PORT_DOQ="$ENV{AGW_DNS_PORT_DOQ}")
|
||||
add_definitions(-DAGW_DNS_DOH_PATH="$ENV{AGW_DNS_DOH_PATH}")
|
||||
add_definitions(-DAGW_DNS_RETRY_COUNT="$ENV{AGW_DNS_RETRY_COUNT}")
|
||||
add_definitions(-DAGW_DNS_TIMEOUT_MS="$ENV{AGW_DNS_TIMEOUT_MS}")
|
||||
|
||||
qt_add_executable(${PROJECT_NAME}
|
||||
tst_transports.cpp
|
||||
${CLIENT_ROOT_DIR}/core/transport/dns/dnsResolver.cpp
|
||||
${CLIENT_ROOT_DIR}/core/transport/dns/dnsTunnel.cpp
|
||||
${CLIENT_ROOT_DIR}/core/transport/dns/dnsPacket.cpp
|
||||
${QSIMPLECRYPTO_DIR}/sources/QBlockCipher.cpp
|
||||
${QSIMPLECRYPTO_DIR}/sources/QRsa.cpp
|
||||
${QSIMPLECRYPTO_DIR}/sources/QX509.cpp
|
||||
${QSIMPLECRYPTO_DIR}/sources/QX509Store.cpp
|
||||
${QSIMPLECRYPTO_DIR}/sources/QAead.cpp
|
||||
)
|
||||
|
||||
target_include_directories(${PROJECT_NAME} PRIVATE
|
||||
${CLIENT_ROOT_DIR}
|
||||
${CLIENT_ROOT_DIR}/core
|
||||
${CLIENT_ROOT_DIR}/core/transport
|
||||
${QSIMPLECRYPTO_DIR}
|
||||
${QSIMPLECRYPTO_DIR}/include
|
||||
${OPENSSL_INCLUDE_DIR}
|
||||
)
|
||||
|
||||
target_compile_definitions(${PROJECT_NAME} PRIVATE
|
||||
CLIENT_SOURCE_DIR="${CLIENT_ROOT_DIR}"
|
||||
)
|
||||
|
||||
target_link_libraries(${PROJECT_NAME} PRIVATE
|
||||
Qt6::Core
|
||||
Qt6::Network
|
||||
Qt6::Test
|
||||
${OPENSSL_LIB_SSL}
|
||||
${OPENSSL_LIB_CRYPTO}
|
||||
)
|
||||
|
||||
if(WIN32)
|
||||
target_link_libraries(${PROJECT_NAME} PRIVATE ws2_32 crypt32)
|
||||
endif()
|
||||
|
||||
add_test(NAME TransportTest COMMAND ${PROJECT_NAME})
|
||||
@@ -0,0 +1,406 @@
|
||||
#include <QCoreApplication>
|
||||
#include <QDebug>
|
||||
#include <QElapsedTimer>
|
||||
#include <QEventLoop>
|
||||
#include <QHostAddress>
|
||||
#include <QHostInfo>
|
||||
#include <QNetworkAccessManager>
|
||||
#include <QNetworkReply>
|
||||
#include <QNetworkRequest>
|
||||
#include <QSslConfiguration>
|
||||
#include <QSslError>
|
||||
#include <QTest>
|
||||
#include <QUrl>
|
||||
|
||||
#include "transport/dns/dnsResolver.h"
|
||||
#include "transport/dns/dnsTunnel.h"
|
||||
#include "QBlockCipher.h"
|
||||
#include "QRsa.h"
|
||||
|
||||
#include <openssl/evp.h>
|
||||
#include <openssl/rsa.h>
|
||||
|
||||
using amnezia::transport::dns::DnsProtocol;
|
||||
|
||||
struct TransportResult {
|
||||
QString name;
|
||||
bool success = false;
|
||||
int elapsedMs = 0;
|
||||
int responseSize = 0;
|
||||
QString error;
|
||||
QByteArray responseBody;
|
||||
};
|
||||
|
||||
struct TestConfig {
|
||||
QString httpEndpoint;
|
||||
struct DnsEntry {
|
||||
QString name;
|
||||
DnsProtocol type;
|
||||
QString server;
|
||||
QString domain;
|
||||
quint16 port;
|
||||
QString dohPath;
|
||||
};
|
||||
QList<DnsEntry> dnsTransports;
|
||||
int timeoutMs = 15000;
|
||||
};
|
||||
|
||||
static TestConfig buildConfigFromEnv()
|
||||
{
|
||||
TestConfig cfg;
|
||||
|
||||
QString server(AGW_DNS_SERVER);
|
||||
QString domain(AGW_DNS_DOMAIN);
|
||||
|
||||
cfg.httpEndpoint = QString(DEV_AGW_PUBLIC_KEY).isEmpty()
|
||||
? QString() : QString("http://%1/").arg(server);
|
||||
|
||||
int timeout = QString(AGW_DNS_TIMEOUT_MS).toInt();
|
||||
cfg.timeoutMs = (timeout > 0) ? timeout : 15000;
|
||||
|
||||
if (server.isEmpty() || domain.isEmpty()) return cfg;
|
||||
|
||||
auto addEntry = [&](DnsProtocol type, const QString &name,
|
||||
const char *portDefine, quint16 defaultPort, const QString &dohPath = QString()) {
|
||||
TestConfig::DnsEntry e;
|
||||
e.type = type;
|
||||
e.name = name;
|
||||
e.server = server;
|
||||
e.domain = domain;
|
||||
quint16 port = QString(portDefine).toUShort();
|
||||
e.port = (port > 0) ? port : defaultPort;
|
||||
if (!dohPath.isEmpty()) e.dohPath = dohPath;
|
||||
cfg.dnsTransports.append(e);
|
||||
};
|
||||
|
||||
addEntry(DnsProtocol::Udp, "UDP", AGW_DNS_PORT_UDP, 5353);
|
||||
addEntry(DnsProtocol::Tcp, "TCP", AGW_DNS_PORT_UDP, 5353);
|
||||
addEntry(DnsProtocol::Tls, "DoT", AGW_DNS_PORT_DOT, 853);
|
||||
|
||||
QString dohPath = QString(AGW_DNS_DOH_PATH);
|
||||
if (dohPath.isEmpty()) dohPath = "/dns-query";
|
||||
addEntry(DnsProtocol::Https, "DoH", AGW_DNS_PORT_DOH, 443, dohPath);
|
||||
|
||||
addEntry(DnsProtocol::Quic, "DoQ", AGW_DNS_PORT_DOQ, 8853);
|
||||
|
||||
return cfg;
|
||||
}
|
||||
|
||||
static QString resolveHost(const QString &host)
|
||||
{
|
||||
QHostAddress addr(host);
|
||||
if (!addr.isNull()) return host;
|
||||
QHostInfo info = QHostInfo::fromName(host);
|
||||
if (!info.addresses().isEmpty())
|
||||
return info.addresses().first().toString();
|
||||
return host;
|
||||
}
|
||||
|
||||
struct EncryptedPayload {
|
||||
QByteArray body;
|
||||
QByteArray key;
|
||||
QByteArray iv;
|
||||
QByteArray salt;
|
||||
bool ok = false;
|
||||
QString error;
|
||||
};
|
||||
|
||||
static EncryptedPayload encryptPayload(const QJsonObject &apiPayload, const QByteArray &rsaPubKeyPem)
|
||||
{
|
||||
EncryptedPayload result;
|
||||
|
||||
QSimpleCrypto::QBlockCipher blockCipher;
|
||||
result.key = blockCipher.generatePrivateSalt(32);
|
||||
result.iv = blockCipher.generatePrivateSalt(32);
|
||||
result.salt = blockCipher.generatePrivateSalt(8);
|
||||
|
||||
QJsonObject keyPayload;
|
||||
keyPayload["aes_key"] = QString(result.key.toBase64());
|
||||
keyPayload["aes_iv"] = QString(result.iv.toBase64());
|
||||
keyPayload["aes_salt"] = QString(result.salt.toBase64());
|
||||
|
||||
try {
|
||||
QSimpleCrypto::QRsa rsa;
|
||||
QByteArray pemData = rsaPubKeyPem;
|
||||
pemData.replace("\\n", "\n");
|
||||
EVP_PKEY *pubKey = rsa.getPublicKeyFromByteArray(pemData);
|
||||
if (!pubKey) {
|
||||
result.error = "Failed to load RSA public key";
|
||||
return result;
|
||||
}
|
||||
|
||||
QByteArray encKeyPayload = rsa.encrypt(QJsonDocument(keyPayload).toJson(), pubKey, RSA_PKCS1_PADDING);
|
||||
EVP_PKEY_free(pubKey);
|
||||
|
||||
QByteArray encApiPayload = blockCipher.encryptAesBlockCipher(
|
||||
QJsonDocument(apiPayload).toJson(), result.key, result.iv, "", result.salt);
|
||||
|
||||
QJsonObject requestBody;
|
||||
requestBody["key_payload"] = QString(encKeyPayload.toBase64());
|
||||
requestBody["api_payload"] = QString(encApiPayload.toBase64());
|
||||
|
||||
result.body = QJsonDocument(requestBody).toJson();
|
||||
result.ok = true;
|
||||
} catch (const std::exception &ex) {
|
||||
result.error = QString("Encryption failed: %1").arg(ex.what());
|
||||
} catch (...) {
|
||||
result.error = "Encryption failed: unknown error";
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
static QByteArray decryptResponse(const QByteArray &encrypted, const QByteArray &key,
|
||||
const QByteArray &iv, const QByteArray &salt)
|
||||
{
|
||||
try {
|
||||
QSimpleCrypto::QBlockCipher blockCipher;
|
||||
return blockCipher.decryptAesBlockCipher(encrypted, key, iv, "", salt);
|
||||
} catch (...) {
|
||||
return QByteArray();
|
||||
}
|
||||
}
|
||||
|
||||
class TransportTest : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
private:
|
||||
TestConfig m_config;
|
||||
QByteArray m_rsaKey;
|
||||
bool m_hasRsaKey = false;
|
||||
QList<TransportResult> m_results;
|
||||
|
||||
void logResult(const TransportResult &r) {
|
||||
QString status = r.success ? "OK" : "FAIL";
|
||||
qDebug().noquote() << QString("[%1] %2 | %3ms | %4 bytes | %5")
|
||||
.arg(status, -4)
|
||||
.arg(r.name, -20)
|
||||
.arg(r.elapsedMs, 5)
|
||||
.arg(r.responseSize, 6)
|
||||
.arg(r.error.isEmpty() ? "---" : r.error);
|
||||
}
|
||||
|
||||
TransportResult doHttpTransport(const QString &endpoint, const QByteArray &payload) {
|
||||
TransportResult r;
|
||||
r.name = "HTTP";
|
||||
QElapsedTimer timer;
|
||||
timer.start();
|
||||
|
||||
QNetworkAccessManager nam;
|
||||
QNetworkRequest request(QUrl(endpoint));
|
||||
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
|
||||
request.setTransferTimeout(m_config.timeoutMs);
|
||||
|
||||
QNetworkReply *reply = nam.post(request, payload);
|
||||
|
||||
QEventLoop loop;
|
||||
QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
|
||||
loop.exec();
|
||||
|
||||
r.elapsedMs = static_cast<int>(timer.elapsed());
|
||||
|
||||
if (reply->error() != QNetworkReply::NoError) {
|
||||
r.error = QString("HTTP %1: %2")
|
||||
.arg(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt())
|
||||
.arg(reply->errorString());
|
||||
r.responseBody = reply->readAll();
|
||||
r.responseSize = r.responseBody.size();
|
||||
} else {
|
||||
r.responseBody = reply->readAll();
|
||||
r.responseSize = r.responseBody.size();
|
||||
r.success = !r.responseBody.isEmpty();
|
||||
if (!r.success) r.error = "Empty response";
|
||||
}
|
||||
reply->deleteLater();
|
||||
return r;
|
||||
}
|
||||
|
||||
TransportResult doDnsTransport(const TestConfig::DnsEntry &entry, const QByteArray &payload,
|
||||
const QString &resolvedIp) {
|
||||
TransportResult r;
|
||||
r.name = QString("DNS-%1").arg(entry.name);
|
||||
QElapsedTimer timer;
|
||||
timer.start();
|
||||
|
||||
bool needsHostname = (entry.type == DnsProtocol::Https || entry.type == DnsProtocol::Tls);
|
||||
QString serverAddr = needsHostname ? entry.server : resolvedIp;
|
||||
|
||||
r.responseBody = amnezia::transport::dns::DnsTunnel::send(
|
||||
payload, "services", entry.domain,
|
||||
serverAddr, entry.type, entry.port,
|
||||
m_config.timeoutMs, entry.dohPath);
|
||||
|
||||
r.elapsedMs = static_cast<int>(timer.elapsed());
|
||||
r.responseSize = r.responseBody.size();
|
||||
r.success = !r.responseBody.isEmpty();
|
||||
if (!r.success) r.error = "Empty/no response";
|
||||
return r;
|
||||
}
|
||||
|
||||
private slots:
|
||||
void initTestCase()
|
||||
{
|
||||
m_config = buildConfigFromEnv();
|
||||
|
||||
QVERIFY2(!m_config.dnsTransports.isEmpty(),
|
||||
"AGW_DNS_SERVER / AGW_DNS_DOMAIN not set -- cannot run transport tests");
|
||||
|
||||
qDebug() << "HTTP endpoint:" << m_config.httpEndpoint;
|
||||
qDebug() << "DNS transports:" << m_config.dnsTransports.size();
|
||||
qDebug() << "Timeout:" << m_config.timeoutMs << "ms";
|
||||
|
||||
QByteArray prodKey(PROD_AGW_PUBLIC_KEY);
|
||||
QByteArray devKey(DEV_AGW_PUBLIC_KEY);
|
||||
if (!prodKey.isEmpty()) {
|
||||
m_rsaKey = prodKey;
|
||||
m_hasRsaKey = true;
|
||||
qDebug() << "Using PROD_AGW_PUBLIC_KEY for E2E tests";
|
||||
} else if (!devKey.isEmpty()) {
|
||||
m_rsaKey = devKey;
|
||||
m_hasRsaKey = true;
|
||||
qDebug() << "Using DEV_AGW_PUBLIC_KEY for E2E tests";
|
||||
} else {
|
||||
qWarning() << "No RSA public key found -- E2E tests will be SKIPPED";
|
||||
}
|
||||
}
|
||||
|
||||
void test_transport_http()
|
||||
{
|
||||
QByteArray payload = R"({"test":true})";
|
||||
TransportResult r = doHttpTransport(m_config.httpEndpoint, payload);
|
||||
m_results.append(r);
|
||||
logResult(r);
|
||||
QVERIFY2(r.success || r.responseSize > 0,
|
||||
qPrintable(QString("HTTP transport failed: %1").arg(r.error)));
|
||||
}
|
||||
|
||||
void test_transport_dns_data()
|
||||
{
|
||||
QTest::addColumn<int>("transportIndex");
|
||||
for (int i = 0; i < m_config.dnsTransports.size(); ++i) {
|
||||
const auto &e = m_config.dnsTransports[i];
|
||||
if (e.type == DnsProtocol::Quic) continue;
|
||||
QTest::newRow(qPrintable(e.name)) << i;
|
||||
}
|
||||
}
|
||||
|
||||
void test_transport_dns()
|
||||
{
|
||||
QFETCH(int, transportIndex);
|
||||
const auto &entry = m_config.dnsTransports[transportIndex];
|
||||
QString resolvedIp = resolveHost(entry.server);
|
||||
qDebug() << "Server:" << entry.server << "-> IP:" << resolvedIp
|
||||
<< "Port:" << entry.port;
|
||||
|
||||
QByteArray payload = R"({"test":true})";
|
||||
TransportResult r = doDnsTransport(entry, payload, resolvedIp);
|
||||
m_results.append(r);
|
||||
logResult(r);
|
||||
|
||||
if (!r.success) {
|
||||
qWarning() << "DNS" << entry.name << "transport failed (server may be down):" << r.error;
|
||||
}
|
||||
}
|
||||
|
||||
void test_e2e_http()
|
||||
{
|
||||
if (!m_hasRsaKey) QSKIP("No RSA key -- skipping E2E");
|
||||
|
||||
QJsonObject apiPayload;
|
||||
apiPayload["protocol"] = "any";
|
||||
EncryptedPayload enc = encryptPayload(apiPayload, m_rsaKey);
|
||||
QVERIFY2(enc.ok, qPrintable(enc.error));
|
||||
|
||||
TransportResult r = doHttpTransport(m_config.httpEndpoint, enc.body);
|
||||
r.name = "E2E-HTTP";
|
||||
|
||||
if (r.success) {
|
||||
QByteArray decrypted = decryptResponse(r.responseBody, enc.key, enc.iv, enc.salt);
|
||||
if (!decrypted.isEmpty()) {
|
||||
r.responseBody = decrypted;
|
||||
r.responseSize = decrypted.size();
|
||||
qDebug() << "Decrypted response:" << decrypted.left(200);
|
||||
} else {
|
||||
r.error = "Decryption failed (raw body size: " + QString::number(r.responseBody.size()) + ")";
|
||||
r.success = false;
|
||||
}
|
||||
}
|
||||
|
||||
m_results.append(r);
|
||||
logResult(r);
|
||||
QVERIFY2(r.success, qPrintable(QString("E2E HTTP failed: %1").arg(r.error)));
|
||||
}
|
||||
|
||||
void test_e2e_dns_data()
|
||||
{
|
||||
QTest::addColumn<int>("transportIndex");
|
||||
for (int i = 0; i < m_config.dnsTransports.size(); ++i) {
|
||||
const auto &e = m_config.dnsTransports[i];
|
||||
if (e.type == DnsProtocol::Quic) continue;
|
||||
QTest::newRow(qPrintable(QString("E2E-%1").arg(e.name))) << i;
|
||||
}
|
||||
}
|
||||
|
||||
void test_e2e_dns()
|
||||
{
|
||||
if (!m_hasRsaKey) QSKIP("No RSA key -- skipping E2E");
|
||||
|
||||
QFETCH(int, transportIndex);
|
||||
const auto &entry = m_config.dnsTransports[transportIndex];
|
||||
QString resolvedIp = resolveHost(entry.server);
|
||||
qDebug() << "E2E via" << entry.name << "server:" << entry.server
|
||||
<< "-> IP:" << resolvedIp << "port:" << entry.port;
|
||||
|
||||
QJsonObject apiPayload;
|
||||
apiPayload["protocol"] = "any";
|
||||
EncryptedPayload enc = encryptPayload(apiPayload, m_rsaKey);
|
||||
QVERIFY2(enc.ok, qPrintable(enc.error));
|
||||
|
||||
TransportResult r = doDnsTransport(entry, enc.body, resolvedIp);
|
||||
r.name = QString("E2E-%1").arg(entry.name);
|
||||
|
||||
if (r.success) {
|
||||
QByteArray decrypted = decryptResponse(r.responseBody, enc.key, enc.iv, enc.salt);
|
||||
if (!decrypted.isEmpty()) {
|
||||
r.responseBody = decrypted;
|
||||
r.responseSize = decrypted.size();
|
||||
qDebug() << "Decrypted response:" << decrypted.left(200);
|
||||
} else {
|
||||
r.error = "Decryption failed (raw body size: " + QString::number(r.responseBody.size()) + ")";
|
||||
r.success = false;
|
||||
}
|
||||
}
|
||||
|
||||
m_results.append(r);
|
||||
logResult(r);
|
||||
|
||||
if (!r.success) {
|
||||
qWarning() << "E2E DNS" << entry.name << "failed:" << r.error;
|
||||
}
|
||||
}
|
||||
|
||||
void cleanupTestCase()
|
||||
{
|
||||
qDebug() << "";
|
||||
qDebug() << "============================================================";
|
||||
qDebug() << " TRANSPORT TEST SUMMARY";
|
||||
qDebug() << "============================================================";
|
||||
qDebug().noquote() << QString(" %-4s | %-20s | %5s | %6s | %s")
|
||||
.arg("", "Transport", "ms", "bytes", "Error");
|
||||
qDebug() << "------------------------------------------------------------";
|
||||
|
||||
int passed = 0, failed = 0;
|
||||
for (const auto &r : m_results) {
|
||||
logResult(r);
|
||||
if (r.success) ++passed; else ++failed;
|
||||
}
|
||||
|
||||
qDebug() << "------------------------------------------------------------";
|
||||
qDebug().noquote() << QString("Total: %1 passed, %2 failed, %3 total")
|
||||
.arg(passed).arg(failed).arg(m_results.size());
|
||||
qDebug() << "============================================================";
|
||||
}
|
||||
};
|
||||
|
||||
QTEST_MAIN(TransportTest)
|
||||
#include "tst_transports.moc"
|
||||
File diff suppressed because it is too large
Load Diff
@@ -5,6 +5,7 @@
|
||||
#include "core/api/apiDefs.h"
|
||||
#include "core/api/apiUtils.h"
|
||||
#include "core/controllers/gatewayController.h"
|
||||
#include "core/networkUtilities.h"
|
||||
#include "core/qrCodeUtils.h"
|
||||
#include "ui/controllers/systemController.h"
|
||||
#include "version.h"
|
||||
@@ -723,9 +724,6 @@ bool ApiConfigsController::updateServiceFromTelegram(const int serverIndex)
|
||||
QThread::msleep(10);
|
||||
#endif
|
||||
|
||||
GatewayController gatewayController(m_settings->getGatewayEndpoint(), m_settings->isDevGatewayEnv(), apiDefs::requestTimeoutMsecs,
|
||||
m_settings->isStrictKillSwitchEnabled());
|
||||
|
||||
auto serverConfig = m_serversModel->getServerConfig(serverIndex);
|
||||
auto installationUuid = m_settings->getInstallationUuid(true);
|
||||
|
||||
@@ -741,7 +739,17 @@ bool ApiConfigsController::updateServiceFromTelegram(const int serverIndex)
|
||||
apiPayload[configKey::apiEndpoint] = serverConfig.value(configKey::apiEndpoint).toString();
|
||||
|
||||
QByteArray responseBody;
|
||||
ErrorCode errorCode = gatewayController.post(QString("%1v1/proxy_config"), apiPayload, responseBody);
|
||||
QString endpoint = QString("%1v1/proxy_config");
|
||||
|
||||
// Use GatewayController with parallel transports
|
||||
GatewayController gatewayController(m_settings->getGatewayEndpoint(),
|
||||
m_settings->isDevGatewayEnv(),
|
||||
apiDefs::requestTimeoutMsecs,
|
||||
m_settings->isStrictKillSwitchEnabled());
|
||||
|
||||
gatewayController.setTransportsConfig(GatewayController::buildTransportsConfig());
|
||||
|
||||
ErrorCode errorCode = gatewayController.post(endpoint, apiPayload, responseBody);
|
||||
|
||||
if (errorCode == ErrorCode::NoError) {
|
||||
errorCode = fillServerConfig(serviceProtocol, protocolData, responseBody, serverConfig);
|
||||
@@ -948,7 +956,12 @@ ErrorCode ApiConfigsController::importServiceFromBilling(const QByteArray &respo
|
||||
ErrorCode ApiConfigsController::executeRequest(const QString &endpoint, const QJsonObject &apiPayload, QByteArray &responseBody,
|
||||
bool isTestPurchase)
|
||||
{
|
||||
GatewayController gatewayController(m_settings->getGatewayEndpoint(isTestPurchase), m_settings->isDevGatewayEnv(isTestPurchase),
|
||||
apiDefs::requestTimeoutMsecs, m_settings->isStrictKillSwitchEnabled());
|
||||
GatewayController gatewayController(m_settings->getGatewayEndpoint(isTestPurchase),
|
||||
m_settings->isDevGatewayEnv(isTestPurchase),
|
||||
apiDefs::requestTimeoutMsecs,
|
||||
m_settings->isStrictKillSwitchEnabled());
|
||||
|
||||
gatewayController.setTransportsConfig(GatewayController::buildTransportsConfig());
|
||||
|
||||
return gatewayController.post(endpoint, apiPayload, responseBody);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
#include "apiNewsController.h"
|
||||
|
||||
#include "core/api/apiUtils.h"
|
||||
#include "core/controllers/gatewayController.h"
|
||||
#include "core/networkUtilities.h"
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
|
||||
@@ -31,8 +33,6 @@ void ApiNewsController::fetchNews(bool showError)
|
||||
return;
|
||||
}
|
||||
|
||||
auto gatewayController = QSharedPointer<GatewayController>::create(m_settings->getGatewayEndpoint(), m_settings->isDevGatewayEnv(),
|
||||
apiDefs::requestTimeoutMsecs, m_settings->isStrictKillSwitchEnabled());
|
||||
QJsonObject payload;
|
||||
payload.insert("locale", m_settings->getAppLanguage().name().split("_").first());
|
||||
|
||||
@@ -44,26 +44,35 @@ void ApiNewsController::fetchNews(bool showError)
|
||||
payload.insert(configKey::serviceType, stacksJson.value(configKey::serviceType));
|
||||
}
|
||||
|
||||
auto future = gatewayController->postAsync(QString("%1v1/news"), payload);
|
||||
future.then(this, [this, showError, gatewayController](QPair<ErrorCode, QByteArray> result) {
|
||||
auto [errorCode, responseBody] = result;
|
||||
if (errorCode != ErrorCode::NoError) {
|
||||
emit errorOccurred(errorCode, showError);
|
||||
return;
|
||||
QString endpoint = QString("%1v1/news");
|
||||
|
||||
// Use GatewayController with parallel transports
|
||||
GatewayController gatewayController(m_settings->getGatewayEndpoint(),
|
||||
m_settings->isDevGatewayEnv(),
|
||||
apiDefs::requestTimeoutMsecs,
|
||||
m_settings->isStrictKillSwitchEnabled());
|
||||
|
||||
gatewayController.setTransportsConfig(GatewayController::buildTransportsConfig());
|
||||
|
||||
QByteArray responseBody;
|
||||
ErrorCode errorCode = gatewayController.post(endpoint, payload, responseBody);
|
||||
|
||||
if (errorCode != ErrorCode::NoError) {
|
||||
emit errorOccurred(errorCode, showError);
|
||||
return;
|
||||
}
|
||||
|
||||
// Parse response
|
||||
QJsonDocument doc = QJsonDocument::fromJson(responseBody);
|
||||
QJsonArray newsArray;
|
||||
if (doc.isArray()) {
|
||||
newsArray = doc.array();
|
||||
} else if (doc.isObject()) {
|
||||
QJsonObject obj = doc.object();
|
||||
if (obj.value("news").isArray()) {
|
||||
newsArray = obj.value("news").toArray();
|
||||
}
|
||||
|
||||
QJsonDocument doc = QJsonDocument::fromJson(responseBody);
|
||||
QJsonArray newsArray;
|
||||
if (doc.isArray()) {
|
||||
newsArray = doc.array();
|
||||
} else if (doc.isObject()) {
|
||||
QJsonObject obj = doc.object();
|
||||
if (obj.value("news").isArray()) {
|
||||
newsArray = obj.value("news").toArray();
|
||||
}
|
||||
}
|
||||
|
||||
m_newsModel->updateModel(newsArray);
|
||||
emit fetchNewsFinished();
|
||||
});
|
||||
}
|
||||
m_newsModel->updateModel(newsArray);
|
||||
emit fetchNewsFinished();
|
||||
}
|
||||
|
||||
@@ -1,133 +0,0 @@
|
||||
#include "apiPremV1MigrationController.h"
|
||||
|
||||
#include <QEventLoop>
|
||||
#include <QTimer>
|
||||
|
||||
#include "core/api/apiDefs.h"
|
||||
#include "core/api/apiUtils.h"
|
||||
#include "core/controllers/gatewayController.h"
|
||||
|
||||
ApiPremV1MigrationController::ApiPremV1MigrationController(const QSharedPointer<ServersModel> &serversModel,
|
||||
const std::shared_ptr<Settings> &settings, QObject *parent)
|
||||
: QObject(parent), m_serversModel(serversModel), m_settings(settings)
|
||||
{
|
||||
}
|
||||
|
||||
bool ApiPremV1MigrationController::hasConfigsToMigration()
|
||||
{
|
||||
QJsonArray vpnKeys;
|
||||
|
||||
auto serversCount = m_serversModel->getServersCount();
|
||||
for (size_t i = 0; i < serversCount; i++) {
|
||||
auto serverConfigObject = m_serversModel->getServerConfig(i);
|
||||
|
||||
if (apiUtils::getConfigType(serverConfigObject) != apiDefs::ConfigType::AmneziaPremiumV1) {
|
||||
continue;
|
||||
}
|
||||
|
||||
QString vpnKey = apiUtils::getPremiumV1VpnKey(serverConfigObject);
|
||||
vpnKeys.append(vpnKey);
|
||||
}
|
||||
|
||||
if (!vpnKeys.isEmpty()) {
|
||||
GatewayController gatewayController(m_settings->getGatewayEndpoint(), m_settings->isDevGatewayEnv(), apiDefs::requestTimeoutMsecs,
|
||||
m_settings->isStrictKillSwitchEnabled());
|
||||
QJsonObject apiPayload;
|
||||
|
||||
apiPayload["configs"] = vpnKeys;
|
||||
QByteArray responseBody;
|
||||
ErrorCode errorCode = gatewayController.post(QString("%1v1/prem-v1/is-active-subscription"), apiPayload, responseBody);
|
||||
|
||||
auto migrationsStatus = QJsonDocument::fromJson(responseBody).object();
|
||||
for (const auto &migrationStatus : migrationsStatus) {
|
||||
if (migrationStatus == "not_found") {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
void ApiPremV1MigrationController::getSubscriptionList(const QString &email)
|
||||
{
|
||||
GatewayController gatewayController(m_settings->getGatewayEndpoint(), m_settings->isDevGatewayEnv(), apiDefs::requestTimeoutMsecs,
|
||||
m_settings->isStrictKillSwitchEnabled());
|
||||
QJsonObject apiPayload;
|
||||
|
||||
apiPayload[apiDefs::key::email] = email;
|
||||
QByteArray responseBody;
|
||||
ErrorCode errorCode = gatewayController.post(QString("%1v1/prem-v1/subscription-list"), apiPayload, responseBody);
|
||||
|
||||
if (errorCode == ErrorCode::NoError) {
|
||||
m_email = email;
|
||||
m_subscriptionsModel = QJsonDocument::fromJson(responseBody).array();
|
||||
if (m_subscriptionsModel.isEmpty()) {
|
||||
emit noSubscriptionToMigrate();
|
||||
return;
|
||||
}
|
||||
|
||||
emit subscriptionsModelChanged();
|
||||
} else {
|
||||
emit errorOccurred(ErrorCode::ApiMigrationError);
|
||||
}
|
||||
}
|
||||
|
||||
QJsonArray ApiPremV1MigrationController::getSubscriptionModel()
|
||||
{
|
||||
return m_subscriptionsModel;
|
||||
}
|
||||
|
||||
void ApiPremV1MigrationController::sendMigrationCode(const int subscriptionIndex)
|
||||
{
|
||||
QEventLoop wait;
|
||||
QTimer::singleShot(1000, &wait, &QEventLoop::quit);
|
||||
wait.exec(QEventLoop::ExcludeUserInputEvents);
|
||||
|
||||
GatewayController gatewayController(m_settings->getGatewayEndpoint(), m_settings->isDevGatewayEnv(), apiDefs::requestTimeoutMsecs,
|
||||
m_settings->isStrictKillSwitchEnabled());
|
||||
QJsonObject apiPayload;
|
||||
|
||||
apiPayload[apiDefs::key::email] = m_email;
|
||||
QByteArray responseBody;
|
||||
ErrorCode errorCode = gatewayController.post(QString("%1v1/prem-v1/migration-code"), apiPayload, responseBody);
|
||||
|
||||
if (errorCode == ErrorCode::NoError) {
|
||||
m_subscriptionIndex = subscriptionIndex;
|
||||
emit otpSuccessfullySent();
|
||||
} else {
|
||||
emit errorOccurred(ErrorCode::ApiMigrationError);
|
||||
}
|
||||
}
|
||||
|
||||
void ApiPremV1MigrationController::migrate(const QString &migrationCode)
|
||||
{
|
||||
GatewayController gatewayController(m_settings->getGatewayEndpoint(), m_settings->isDevGatewayEnv(), apiDefs::requestTimeoutMsecs,
|
||||
m_settings->isStrictKillSwitchEnabled());
|
||||
QJsonObject apiPayload;
|
||||
|
||||
apiPayload[apiDefs::key::email] = m_email;
|
||||
apiPayload[apiDefs::key::orderId] = m_subscriptionsModel.at(m_subscriptionIndex).toObject().value(apiDefs::key::id).toString();
|
||||
apiPayload[apiDefs::key::migrationCode] = migrationCode;
|
||||
QByteArray responseBody;
|
||||
ErrorCode errorCode = gatewayController.post(QString("%1v1/prem-v1/migrate"), apiPayload, responseBody);
|
||||
|
||||
if (errorCode == ErrorCode::NoError) {
|
||||
auto responseObject = QJsonDocument::fromJson(responseBody).object();
|
||||
QString premiumV2VpnKey = responseObject.value(apiDefs::key::config).toString();
|
||||
|
||||
emit importPremiumV2VpnKey(premiumV2VpnKey);
|
||||
} else {
|
||||
emit errorOccurred(ErrorCode::ApiMigrationError);
|
||||
}
|
||||
}
|
||||
|
||||
bool ApiPremV1MigrationController::isPremV1MigrationReminderActive()
|
||||
{
|
||||
return m_settings->isPremV1MigrationReminderActive();
|
||||
}
|
||||
|
||||
void ApiPremV1MigrationController::disablePremV1MigrationReminder()
|
||||
{
|
||||
m_settings->disablePremV1MigrationReminder();
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
#ifndef APIPREMV1MIGRATIONCONTROLLER_H
|
||||
#define APIPREMV1MIGRATIONCONTROLLER_H
|
||||
|
||||
#include <QObject>
|
||||
|
||||
#include "ui/models/servers_model.h"
|
||||
|
||||
class ApiPremV1MigrationController : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
public:
|
||||
ApiPremV1MigrationController(const QSharedPointer<ServersModel> &serversModel, const std::shared_ptr<Settings> &settings,
|
||||
QObject *parent = nullptr);
|
||||
|
||||
Q_PROPERTY(QJsonArray subscriptionsModel READ getSubscriptionModel NOTIFY subscriptionsModelChanged)
|
||||
|
||||
public slots:
|
||||
bool hasConfigsToMigration();
|
||||
void getSubscriptionList(const QString &email);
|
||||
QJsonArray getSubscriptionModel();
|
||||
void sendMigrationCode(const int subscriptionIndex);
|
||||
void migrate(const QString &migrationCode);
|
||||
|
||||
bool isPremV1MigrationReminderActive();
|
||||
void disablePremV1MigrationReminder();
|
||||
|
||||
signals:
|
||||
void subscriptionsModelChanged();
|
||||
|
||||
void otpSuccessfullySent();
|
||||
|
||||
void importPremiumV2VpnKey(const QString &vpnKey);
|
||||
|
||||
void errorOccurred(ErrorCode errorCode);
|
||||
|
||||
void showMigrationDrawer();
|
||||
void migrationFinished();
|
||||
|
||||
void noSubscriptionToMigrate();
|
||||
|
||||
private:
|
||||
QSharedPointer<ServersModel> m_serversModel;
|
||||
std::shared_ptr<Settings> m_settings;
|
||||
|
||||
QJsonArray m_subscriptionsModel;
|
||||
int m_subscriptionIndex;
|
||||
QString m_email;
|
||||
};
|
||||
|
||||
#endif // APIPREMV1MIGRATIONCONTROLLER_H
|
||||
@@ -3,9 +3,13 @@
|
||||
#include <QEventLoop>
|
||||
#include <QTimer>
|
||||
|
||||
#include "core/api/apiDefs.h"
|
||||
#include "core/api/apiUtils.h"
|
||||
#include "core/controllers/gatewayController.h"
|
||||
#include "core/networkUtilities.h"
|
||||
#ifdef Q_OS_IOS
|
||||
#include "platforms/ios/ios_controller.h"
|
||||
#endif
|
||||
#include "version.h"
|
||||
|
||||
namespace
|
||||
@@ -56,8 +60,6 @@ bool ApiSettingsController::getAccountInfo(bool reload)
|
||||
auto authData = serverConfig.value(configKey::authData).toObject();
|
||||
|
||||
bool isTestPurchase = apiConfig.value(apiDefs::key::isTestPurchase).toBool(false);
|
||||
GatewayController gatewayController(m_settings->getGatewayEndpoint(isTestPurchase), m_settings->isDevGatewayEnv(isTestPurchase),
|
||||
requestTimeoutMsecs, m_settings->isStrictKillSwitchEnabled());
|
||||
|
||||
QJsonObject apiPayload;
|
||||
apiPayload[configKey::userCountryCode] = apiConfig.value(configKey::userCountryCode).toString();
|
||||
@@ -67,8 +69,18 @@ bool ApiSettingsController::getAccountInfo(bool reload)
|
||||
apiPayload[apiDefs::key::appLanguage] = m_settings->getAppLanguage().name().split("_").first();
|
||||
|
||||
QByteArray responseBody;
|
||||
|
||||
ErrorCode errorCode = gatewayController.post(QString("%1v1/account_info"), apiPayload, responseBody);
|
||||
QString endpoint = QString("%1v1/account_info");
|
||||
|
||||
// Use GatewayController with parallel transports
|
||||
GatewayController gatewayController(m_settings->getGatewayEndpoint(isTestPurchase),
|
||||
m_settings->isDevGatewayEnv(isTestPurchase),
|
||||
requestTimeoutMsecs,
|
||||
m_settings->isStrictKillSwitchEnabled());
|
||||
|
||||
gatewayController.setTransportsConfig(GatewayController::buildTransportsConfig());
|
||||
|
||||
ErrorCode errorCode = gatewayController.post(endpoint, apiPayload, responseBody);
|
||||
|
||||
if (errorCode != ErrorCode::NoError) {
|
||||
emit errorOccurred(errorCode);
|
||||
return false;
|
||||
|
||||
@@ -451,6 +451,13 @@ ErrorCode InstallController::getAlreadyInstalledContainers(const ServerCredentia
|
||||
containerConfig[config_key::transportPacketMagicHeader] =
|
||||
serverConfigMap.value(config_key::transportPacketMagicHeader);
|
||||
|
||||
// hack to parse i1-i5 from commented lines in server config
|
||||
containerConfig[config_key::specialJunk1] = serverConfigMap.value(QString("# ") + config_key::specialJunk1);
|
||||
containerConfig[config_key::specialJunk2] = serverConfigMap.value(QString("# ") + config_key::specialJunk2);
|
||||
containerConfig[config_key::specialJunk3] = serverConfigMap.value(QString("# ") + config_key::specialJunk3);
|
||||
containerConfig[config_key::specialJunk4] = serverConfigMap.value(QString("# ") + config_key::specialJunk4);
|
||||
containerConfig[config_key::specialJunk5] = serverConfigMap.value(QString("# ") + config_key::specialJunk5);
|
||||
|
||||
if (container == DockerContainer::Awg2) {
|
||||
containerConfig[config_key::protocolVersion] = "2";
|
||||
containerConfig[config_key::cookieReplyPacketJunkSize] =
|
||||
|
||||
@@ -60,7 +60,6 @@ namespace PageLoader
|
||||
PageSetupWizardQrReader,
|
||||
PageSetupWizardApiServicesList,
|
||||
PageSetupWizardApiServiceInfo,
|
||||
PageSetupWizardPremiumWebView,
|
||||
|
||||
PageProtocolOpenVpnSettings,
|
||||
PageProtocolShadowSocksSettings,
|
||||
|
||||
@@ -1,261 +0,0 @@
|
||||
import QtQuick 2.2
|
||||
import AmneziaWebView 1.0
|
||||
import Style 1.0
|
||||
|
||||
Rectangle {
|
||||
|
||||
id: panel
|
||||
|
||||
property alias title: webView.title
|
||||
property alias icon: webView.icon
|
||||
property alias progress: webView.progress
|
||||
property alias html: webView.html
|
||||
property alias url: webView.url
|
||||
property alias back: webView.back
|
||||
property alias stop: webView.stop
|
||||
property alias reload: webView.reload
|
||||
property alias forward: webView.forward
|
||||
property alias pressGrabTime: webView.pressGrabTime
|
||||
|
||||
property string onFailedUrl: ""
|
||||
property string onFailedHtml: "<h2>" + qsTr("Can`t load page") + "</h2>"
|
||||
property int preferredWidth: panel.width
|
||||
property int preferredHeight: panel.height
|
||||
|
||||
property var scriptResult: undefined
|
||||
property var requestResult: undefined
|
||||
|
||||
property var call_provider: undefined
|
||||
property var call_data: undefined
|
||||
|
||||
property string status: "unknown" // success, failed
|
||||
|
||||
signal urlCalled(variant url)
|
||||
signal alertCalled(variant message)
|
||||
signal scriptCalled(string funName, variant args)
|
||||
signal reloadCalled()
|
||||
signal eventSended(variant event)
|
||||
signal requestSended(variant request)
|
||||
signal loadFinished()
|
||||
signal loadFailed()
|
||||
|
||||
color: AmneziaStyle.color.onyxBlack
|
||||
|
||||
function call(funName, args) {
|
||||
var script
|
||||
if (panel.call_provider) {
|
||||
panel.call_data = args
|
||||
script = "call(" + funName + ")"
|
||||
} else {
|
||||
script = funName + "(" + JSON.stringify(args) + ")"
|
||||
}
|
||||
|
||||
webView.evaluateJavaScript(script)
|
||||
}
|
||||
|
||||
function event(e) {
|
||||
call("receiveEvent", e)
|
||||
}
|
||||
|
||||
function request(r) {
|
||||
var req = r
|
||||
req.result = call("receiveRequest", req)
|
||||
return req
|
||||
}
|
||||
|
||||
function newEvent(type) {
|
||||
var e = {}
|
||||
e.type = type
|
||||
return e
|
||||
}
|
||||
|
||||
function newRequest(type) {
|
||||
var r = {}
|
||||
r.type = type
|
||||
r.result = null
|
||||
return r
|
||||
}
|
||||
|
||||
function toogleScale() {
|
||||
webView.doToogleScale()
|
||||
}
|
||||
|
||||
function zoomIn() {
|
||||
webView.doZoomIn()
|
||||
}
|
||||
|
||||
function zoomOut() {
|
||||
webView.doZoomOut()
|
||||
}
|
||||
|
||||
|
||||
AmneziaWebView {
|
||||
id: webView
|
||||
anchors.fill: parent
|
||||
|
||||
property bool loaded: false
|
||||
focus: true
|
||||
smooth: false
|
||||
backgroundColor: AmneziaStyle.color.onyxBlack
|
||||
|
||||
property int panelPreferredWidth: panel.preferredWidth
|
||||
onPanelPreferredWidthChanged: {
|
||||
webView.preferredWidth = panel.preferredWidth;
|
||||
// if (webView.loaded)
|
||||
// doZoomOrScale();
|
||||
}
|
||||
|
||||
preferredWidth: panel.preferredWidth //webView.flexible ? panel.preferredWidth : Math.max(webView.contentsSize.width, 1024)
|
||||
preferredHeight: panel.preferredHeight
|
||||
|
||||
contentsScale: 1
|
||||
// onDoubleClick: {
|
||||
// if (webView.flexible)
|
||||
// return
|
||||
|
||||
// async.call(doToogleScale)
|
||||
// }
|
||||
|
||||
function doToogleScale() {
|
||||
// webView.needScale = !webView.needScale
|
||||
// if (webView.needScale) {
|
||||
// doScale()
|
||||
// } else {
|
||||
// webView.contentsScale = webView.zoomvalue
|
||||
// }
|
||||
}
|
||||
|
||||
function doZoomOrScale() {
|
||||
// if (webView.needScale)
|
||||
// doScale()
|
||||
// else
|
||||
// webView.contentsScale = webView.zoomvalue;
|
||||
}
|
||||
|
||||
function doZoomIn() {
|
||||
// if (webView.zoomvalue > 0.3) {
|
||||
// webView.zoomvalue = webView.contentsScale
|
||||
// webView.zoomvalue -= 0.1
|
||||
// webView.contentsScale = webView.zoomvalue
|
||||
// webView.needScale = false
|
||||
// }
|
||||
}
|
||||
|
||||
function doZoomOut() {
|
||||
// if (webView.zoomvalue < 2.5) {
|
||||
// webView.zoomvalue = webView.contentsScale
|
||||
// webView.zoomvalue += 0.1
|
||||
// webView.contentsScale = webView.zoomvalue
|
||||
// webView.needScale = false
|
||||
// }
|
||||
}
|
||||
|
||||
function doScale() {
|
||||
// var zoom = flickableItem.width / webView.preferredWidth
|
||||
// webView.contentsScale = zoom;
|
||||
}
|
||||
|
||||
pressGrabTime: 400
|
||||
settings.defaultFontSize: 14
|
||||
settings.standardFontFamily: "Arial"
|
||||
//settings.developerExtrasEnabled: isDebugEnabled
|
||||
onAlert: panel.alertCalled(message)
|
||||
onUrlChanged: {
|
||||
//flickableItem.contentX = 0
|
||||
//flickableItem.contentY = 0
|
||||
panel.urlCalled(url)
|
||||
}
|
||||
onLoadStarted: {
|
||||
webView.loaded = false
|
||||
//webView.contentsScale = 1
|
||||
}
|
||||
onLoadFinished: {
|
||||
panel.status = "success"
|
||||
webView.loaded = true
|
||||
panel.loadFinished()
|
||||
//async.call(doZoomOrScale)
|
||||
}
|
||||
onLoadFailed: {
|
||||
console.debug("qml: html load failed: " + html)
|
||||
if(html == ""){
|
||||
if (panel.onFailedUrl !== "")
|
||||
panel.url = panel.onFailedUrl;
|
||||
else if (panel.onFailedHtml !== "")
|
||||
panel.html = panel.onFailedHtml;
|
||||
}
|
||||
|
||||
panel.status = "failed"
|
||||
panel.loadFailed()
|
||||
}
|
||||
javaScriptWindowObjects: [
|
||||
QtObject {
|
||||
AmneziaWebView.windowObjectName: "script"
|
||||
function call(functionName, args) {
|
||||
panel.scriptCalled(functionName, args)
|
||||
return scriptResult;
|
||||
}
|
||||
},
|
||||
|
||||
QtObject {
|
||||
AmneziaWebView.windowObjectName: "send"
|
||||
function event(e) {
|
||||
panel.eventSended(e)
|
||||
}
|
||||
function request(r) {
|
||||
var req = r
|
||||
panel.requestSended(req)
|
||||
req.result = requestResult
|
||||
return req;
|
||||
}
|
||||
},
|
||||
QtObject {
|
||||
AmneziaWebView.windowObjectName: "log"
|
||||
|
||||
function error(msg){
|
||||
webView.evaluateJavaScript("console.error('" + msg + "')")
|
||||
return api.log.error(msg)
|
||||
}
|
||||
function warn(msg){
|
||||
webView.evaluateJavaScript("console.warn('" + msg + "')")
|
||||
return api.log.warn(msg)
|
||||
}
|
||||
|
||||
function info(msg){
|
||||
webView.evaluateJavaScript("console.info('" + msg + "')")
|
||||
return api.log.info(msg)
|
||||
}
|
||||
|
||||
function debug(msg){
|
||||
webView.evaluateJavaScript("console.log('" + msg + "')")
|
||||
return api.log.debug(msg)
|
||||
}
|
||||
|
||||
function time(tag, msg){
|
||||
webView.evaluateJavaScript("console.log('" + msg + "')")
|
||||
return api.log.time(tag, msg)
|
||||
}
|
||||
},
|
||||
|
||||
QtObject {
|
||||
AmneziaWebView.windowObjectName: "webView"
|
||||
|
||||
function scrollUp() {
|
||||
//flickableItem.contentY = 0;
|
||||
}
|
||||
|
||||
function reload() {
|
||||
//panel.reloadCalled()
|
||||
}
|
||||
},
|
||||
|
||||
QtObject {
|
||||
AmneziaWebView.windowObjectName: "call_provider"
|
||||
function data(fn) {
|
||||
return panel.call_provider ? panel.call_provider.data(fn, panel.call_data) : panel.call_data
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,194 +0,0 @@
|
||||
pragma ComponentBehavior: Bound
|
||||
|
||||
import QtQuick
|
||||
import QtQuick.Controls
|
||||
import QtQuick.Layouts
|
||||
|
||||
import QtCore
|
||||
|
||||
import PageEnum 1.0
|
||||
import Style 1.0
|
||||
|
||||
import "./"
|
||||
import "../Controls2"
|
||||
import "../Controls2/TextTypes"
|
||||
import "../Config"
|
||||
import "../Components"
|
||||
|
||||
DrawerType2 {
|
||||
id: root
|
||||
|
||||
expandedHeight: parent.height * 0.9
|
||||
|
||||
Connections {
|
||||
target: ApiPremV1MigrationController
|
||||
|
||||
function onErrorOccurred(error, goToPageHome) {
|
||||
PageController.showErrorMessage(error)
|
||||
root.closeTriggered()
|
||||
}
|
||||
}
|
||||
|
||||
expandedStateContent: Item {
|
||||
implicitHeight: root.expandedHeight
|
||||
|
||||
ListViewType {
|
||||
id: listView
|
||||
|
||||
anchors.fill: parent
|
||||
|
||||
model: 1 // fake model to force the ListView to be created without a model
|
||||
snapMode: ListView.NoSnap
|
||||
|
||||
header: ColumnLayout {
|
||||
width: listView.width
|
||||
|
||||
Header2Type {
|
||||
id: header
|
||||
Layout.fillWidth: true
|
||||
Layout.topMargin: 20
|
||||
Layout.leftMargin: 16
|
||||
Layout.rightMargin: 16
|
||||
|
||||
headerText: qsTr("Switch to the new Amnezia Premium subscription")
|
||||
}
|
||||
}
|
||||
|
||||
delegate: ColumnLayout {
|
||||
width: listView.width
|
||||
|
||||
anchors.left: parent.left
|
||||
anchors.right: parent.right
|
||||
anchors.leftMargin: 16
|
||||
anchors.rightMargin: 16
|
||||
|
||||
ParagraphTextType {
|
||||
Layout.fillWidth: true
|
||||
Layout.topMargin: 24
|
||||
Layout.bottomMargin: 24
|
||||
|
||||
horizontalAlignment: Text.AlignLeft
|
||||
textFormat: Text.RichText
|
||||
text: {
|
||||
var str = qsTr("We'll preserve all remaining days of your current subscription and give you an extra month as a thank you. ")
|
||||
str += qsTr("This new subscription type will be actively developed with more locations and features added regularly. Currently available:")
|
||||
str += "<ul style='margin-left: -16px;'>"
|
||||
str += qsTr("<li>20 locations (with more coming soon)</li>")
|
||||
str += qsTr("<li>Easier switching between countries in the app</li>")
|
||||
str += qsTr("<li>Personal dashboard to manage your subscription</li>")
|
||||
str += "</ul>"
|
||||
str += qsTr("Old keys will be deactivated after switching.")
|
||||
}
|
||||
}
|
||||
|
||||
TextFieldWithHeaderType {
|
||||
id: emailLabel
|
||||
Layout.fillWidth: true
|
||||
|
||||
borderColor: AmneziaStyle.color.mutedGray
|
||||
headerTextColor: AmneziaStyle.color.paleGray
|
||||
|
||||
headerText: qsTr("Email")
|
||||
textField.placeholderText: qsTr("mail@example.com")
|
||||
|
||||
|
||||
textField.onFocusChanged: {
|
||||
textField.text = textField.text.replace(/^\s+|\s+$/g, '')
|
||||
}
|
||||
|
||||
Connections {
|
||||
target: ApiPremV1MigrationController
|
||||
|
||||
function onNoSubscriptionToMigrate() {
|
||||
emailLabel.errorText = qsTr("No old format subscriptions for a given email")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
CaptionTextType {
|
||||
Layout.fillWidth: true
|
||||
Layout.topMargin: 16
|
||||
|
||||
color: AmneziaStyle.color.mutedGray
|
||||
|
||||
text: qsTr("Enter the email you used for your current subscription")
|
||||
}
|
||||
|
||||
ApiPremV1SubListDrawer {
|
||||
id: apiPremV1SubListDrawer
|
||||
parent: root
|
||||
|
||||
anchors.fill: parent
|
||||
}
|
||||
|
||||
OtpCodeDrawer {
|
||||
id: otpCodeDrawer
|
||||
parent: root
|
||||
|
||||
anchors.fill: parent
|
||||
}
|
||||
|
||||
BasicButtonType {
|
||||
id: yesButton
|
||||
Layout.fillWidth: true
|
||||
Layout.topMargin: 32
|
||||
|
||||
text: qsTr("Continue")
|
||||
|
||||
clickedFunc: function() {
|
||||
PageController.showBusyIndicator(true)
|
||||
ApiPremV1MigrationController.getSubscriptionList(emailLabel.textField.text)
|
||||
PageController.showBusyIndicator(false)
|
||||
}
|
||||
}
|
||||
|
||||
BasicButtonType {
|
||||
id: noButton
|
||||
Layout.fillWidth: true
|
||||
|
||||
defaultColor: AmneziaStyle.color.transparent
|
||||
hoveredColor: AmneziaStyle.color.translucentWhite
|
||||
pressedColor: AmneziaStyle.color.sheerWhite
|
||||
disabledColor: AmneziaStyle.color.mutedGray
|
||||
textColor: AmneziaStyle.color.paleGray
|
||||
borderWidth: 1
|
||||
|
||||
text: qsTr("Remind me later")
|
||||
|
||||
clickedFunc: function() {
|
||||
root.closeTriggered()
|
||||
}
|
||||
}
|
||||
|
||||
BasicButtonType {
|
||||
Layout.alignment: Qt.AlignHCenter
|
||||
Layout.topMargin: 32
|
||||
Layout.bottomMargin: 32
|
||||
implicitHeight: 32
|
||||
|
||||
defaultColor: "transparent"
|
||||
hoveredColor: AmneziaStyle.color.translucentWhite
|
||||
pressedColor: AmneziaStyle.color.sheerWhite
|
||||
textColor: AmneziaStyle.color.vibrantRed
|
||||
|
||||
text: qsTr("Don't remind me again")
|
||||
|
||||
clickedFunc: function() {
|
||||
var headerText = qsTr("No more reminders? You can always switch to the new format in the server settings")
|
||||
var yesButtonText = qsTr("Continue")
|
||||
var noButtonText = qsTr("Cancel")
|
||||
|
||||
var yesButtonFunction = function() {
|
||||
ApiPremV1MigrationController.disablePremV1MigrationReminder()
|
||||
root.closeTriggered()
|
||||
}
|
||||
var noButtonFunction = function() {
|
||||
}
|
||||
|
||||
showQuestionDrawer(headerText, "", yesButtonText, noButtonText, yesButtonFunction, noButtonFunction)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
import QtQuick
|
||||
import QtQuick.Controls
|
||||
import QtQuick.Layouts
|
||||
|
||||
import Style 1.0
|
||||
|
||||
import "../Controls2"
|
||||
import "../Controls2/TextTypes"
|
||||
import "../Config"
|
||||
|
||||
DrawerType2 {
|
||||
id: root
|
||||
|
||||
Connections {
|
||||
target: ApiPremV1MigrationController
|
||||
|
||||
function onSubscriptionsModelChanged() {
|
||||
if (ApiPremV1MigrationController.subscriptionsModel.length > 1) {
|
||||
root.openTriggered()
|
||||
} else {
|
||||
sendMigrationCode(0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function sendMigrationCode(index) {
|
||||
PageController.showBusyIndicator(true)
|
||||
ApiPremV1MigrationController.sendMigrationCode(index)
|
||||
root.closeTriggered()
|
||||
PageController.showBusyIndicator(false)
|
||||
}
|
||||
|
||||
expandedHeight: parent.height * 0.9
|
||||
|
||||
expandedStateContent: Item {
|
||||
implicitHeight: root.expandedHeight
|
||||
|
||||
ListViewType {
|
||||
id: listView
|
||||
|
||||
anchors.fill: parent
|
||||
|
||||
model: ApiPremV1MigrationController.subscriptionsModel
|
||||
|
||||
header: ColumnLayout {
|
||||
width: listView.width
|
||||
|
||||
Header2Type {
|
||||
id: header
|
||||
Layout.fillWidth: true
|
||||
Layout.topMargin: 20
|
||||
Layout.leftMargin: 16
|
||||
Layout.rightMargin: 16
|
||||
|
||||
headerText: qsTr("Choose Subscription")
|
||||
}
|
||||
}
|
||||
|
||||
delegate: Item {
|
||||
implicitWidth: listView.width
|
||||
implicitHeight: delegateContent.implicitHeight
|
||||
|
||||
ColumnLayout {
|
||||
id: delegateContent
|
||||
|
||||
anchors.top: parent.top
|
||||
anchors.left: parent.left
|
||||
anchors.right: parent.right
|
||||
|
||||
LabelWithButtonType {
|
||||
id: server
|
||||
Layout.fillWidth: true
|
||||
|
||||
text: qsTr("Order ID: ") + modelData.id
|
||||
|
||||
descriptionText: qsTr("Purchase Date: ") + Qt.formatDateTime(new Date(modelData.created_at), "dd.MM.yyyy hh:mm")
|
||||
rightImageSource: "qrc:/images/controls/chevron-right.svg"
|
||||
|
||||
clickedFunction: function() {
|
||||
sendMigrationCode(index)
|
||||
}
|
||||
}
|
||||
|
||||
DividerType {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
pragma ComponentBehavior: Bound
|
||||
|
||||
import QtQuick
|
||||
import QtQuick.Controls
|
||||
import QtQuick.Layouts
|
||||
|
||||
import Style 1.0
|
||||
|
||||
import "../Controls2"
|
||||
import "../Controls2/TextTypes"
|
||||
|
||||
import "../Config"
|
||||
|
||||
DrawerType2 {
|
||||
id: root
|
||||
|
||||
Connections {
|
||||
target: ApiPremV1MigrationController
|
||||
|
||||
function onOtpSuccessfullySent() {
|
||||
root.openTriggered()
|
||||
}
|
||||
}
|
||||
|
||||
expandedHeight: parent.height * 0.6
|
||||
|
||||
expandedStateContent: Item {
|
||||
implicitHeight: root.expandedHeight
|
||||
|
||||
ColumnLayout {
|
||||
|
||||
anchors.top: parent.top
|
||||
anchors.left: parent.left
|
||||
anchors.right: parent.right
|
||||
anchors.leftMargin: 16
|
||||
anchors.rightMargin: 16
|
||||
spacing: 0
|
||||
|
||||
Header2Type {
|
||||
id: header
|
||||
Layout.fillWidth: true
|
||||
Layout.topMargin: 20
|
||||
|
||||
headerText: qsTr("OTP code was sent to your email")
|
||||
}
|
||||
|
||||
TextFieldWithHeaderType {
|
||||
id: otpFiled
|
||||
|
||||
borderColor: AmneziaStyle.color.mutedGray
|
||||
headerTextColor: AmneziaStyle.color.paleGray
|
||||
|
||||
Layout.fillWidth: true
|
||||
Layout.topMargin: 16
|
||||
headerText: qsTr("OTP Code")
|
||||
textField.maximumLength: 30
|
||||
checkEmptyText: true
|
||||
}
|
||||
|
||||
BasicButtonType {
|
||||
id: saveButton
|
||||
|
||||
Layout.fillWidth: true
|
||||
Layout.topMargin: 16
|
||||
|
||||
text: qsTr("Continue")
|
||||
|
||||
clickedFunc: function() {
|
||||
PageController.showBusyIndicator(true)
|
||||
ApiPremV1MigrationController.migrate(otpFiled.textField.text)
|
||||
PageController.showBusyIndicator(false)
|
||||
root.closeTriggered()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,123 +0,0 @@
|
||||
import QtQuick
|
||||
import QtQuick.Controls
|
||||
import QtQuick.Layouts
|
||||
|
||||
import Style 1.0
|
||||
|
||||
Button {
|
||||
id: root
|
||||
|
||||
property string headerText: qsTr("Try Amnesia Premium")
|
||||
property string bodyText: qsTr("High speed and 20 countries to connect to 7 days free.")
|
||||
|
||||
property string hoveredColor: AmneziaStyle.color.charcoalGray
|
||||
property string defaultColor: AmneziaStyle.color.onyxBlack
|
||||
property int paddingContent: 20
|
||||
|
||||
hoverEnabled: true
|
||||
height: contentItemRoot.implicitHeight
|
||||
width: contentItemRoot.implicitWidth
|
||||
|
||||
background: Rectangle {
|
||||
id: backgroundRect
|
||||
|
||||
anchors.fill: parent
|
||||
radius: 16
|
||||
|
||||
color: root.hovered ? hoveredColor : defaultColor
|
||||
|
||||
Behavior on color {
|
||||
PropertyAnimation { duration: 200 }
|
||||
}
|
||||
}
|
||||
|
||||
contentItem: Item {
|
||||
id: contentItemRoot
|
||||
anchors.fill: parent
|
||||
implicitHeight: content.implicitHeight + root.paddingContent * 2
|
||||
implicitWidth: content.implicitWidth + root.paddingContent * 2
|
||||
anchors.margins: root.paddingContent
|
||||
|
||||
GridLayout {
|
||||
id: content
|
||||
anchors.fill: parent
|
||||
columns: 2
|
||||
columnSpacing: 5
|
||||
|
||||
Item {
|
||||
Layout.fillWidth: true
|
||||
Layout.minimumWidth: 0 // Позволяет сжиматься
|
||||
implicitHeight: textColumn.implicitHeight
|
||||
|
||||
Column {
|
||||
id: textColumn
|
||||
anchors.left: parent.left
|
||||
anchors.right: parent.right
|
||||
spacing: 6
|
||||
|
||||
// Заголовок с выделением "Premium"
|
||||
Text {
|
||||
width: parent.width
|
||||
text: qsTr("Try Amnezia ") + '<span style="color: #E6007A;">Premium</span>'
|
||||
textFormat: Text.RichText
|
||||
color: AmneziaStyle.color.paleGray
|
||||
font.pixelSize: 20
|
||||
font.weight: 700
|
||||
font.family: "PT Root UI VF"
|
||||
wrapMode: Text.WordWrap
|
||||
}
|
||||
|
||||
// Описание
|
||||
Text {
|
||||
text: root.bodyText
|
||||
wrapMode: Text.WordWrap
|
||||
color: AmneziaStyle.color.mutedGray
|
||||
font.pixelSize: 14
|
||||
font.weight: 400
|
||||
font.family: "PT Root UI VF"
|
||||
lineHeight: 20
|
||||
lineHeightMode: Text.FixedHeight
|
||||
width: parent.width
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Стрелка справа
|
||||
Item {
|
||||
implicitWidth: 40
|
||||
implicitHeight: 40
|
||||
Layout.alignment: Qt.AlignRight | Qt.AlignVCenter
|
||||
Layout.minimumWidth: 40
|
||||
Layout.maximumWidth: 40
|
||||
Layout.preferredWidth: 40
|
||||
|
||||
Image {
|
||||
anchors.centerIn: parent
|
||||
source: "qrc:/images/controls/chevron-right.svg"
|
||||
sourceSize: Qt.size(24, 24)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
MouseArea {
|
||||
anchors.fill: parent
|
||||
|
||||
cursorShape: Qt.PointingHandCursor
|
||||
hoverEnabled: true
|
||||
enabled: root.enabled
|
||||
|
||||
onEntered: {
|
||||
backgroundRect.color = root.hoveredColor
|
||||
}
|
||||
|
||||
onExited: {
|
||||
backgroundRect.color = root.defaultColor
|
||||
}
|
||||
|
||||
onClicked: {
|
||||
root.clicked()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -48,30 +48,6 @@ PageType {
|
||||
}
|
||||
}
|
||||
|
||||
Connections {
|
||||
|
||||
target: ApiPremV1MigrationController
|
||||
|
||||
function onMigrationFinished() {
|
||||
apiPremV1MigrationDrawer.closeTriggered()
|
||||
|
||||
var headerText = qsTr("You've successfully switched to the new Amnezia Premium subscription!")
|
||||
var descriptionText = qsTr("Old keys will no longer work. Please use your new subscription key to connect. \nThank you for staying with us!")
|
||||
var yesButtonText = qsTr("Continue")
|
||||
var noButtonText = ""
|
||||
|
||||
var yesButtonFunction = function() {
|
||||
}
|
||||
var noButtonFunction = function() {
|
||||
}
|
||||
|
||||
showQuestionDrawer(headerText, descriptionText, yesButtonText, noButtonText, yesButtonFunction, noButtonFunction)
|
||||
}
|
||||
|
||||
function onShowMigrationDrawer() {
|
||||
apiPremV1MigrationDrawer.openTriggered()
|
||||
}
|
||||
}
|
||||
|
||||
Item {
|
||||
objectName: "homeColumnItem"
|
||||
@@ -204,84 +180,6 @@ PageType {
|
||||
Layout.rightMargin: 16
|
||||
Layout.topMargin: 22
|
||||
}
|
||||
|
||||
PremiumBannerType {
|
||||
id: premiumBannerHome
|
||||
|
||||
Layout.fillWidth: true
|
||||
Layout.leftMargin: 16
|
||||
Layout.rightMargin: 16
|
||||
Layout.topMargin: 16
|
||||
Layout.bottomMargin: 16
|
||||
|
||||
property bool isAmneziaFree: {
|
||||
if (ServersModel.getServersCount() > 0 && ServersModel.isDefaultServerFromApi) {
|
||||
var apiConfig = ServersModel.getDefaultServerData("apiConfig")
|
||||
if (apiConfig) {
|
||||
// Получаем serviceType из apiConfig (ключ "service_type")
|
||||
var serviceType = ""
|
||||
if (apiConfig.service_type !== undefined) {
|
||||
serviceType = apiConfig.service_type
|
||||
} else if (apiConfig.serviceType !== undefined) {
|
||||
serviceType = apiConfig.serviceType
|
||||
}
|
||||
|
||||
if (serviceType === "amnezia-free") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
// Альтернативная проверка через имя сервера
|
||||
var serverName = ServersModel.defaultServerName
|
||||
if (serverName) {
|
||||
var nameLower = serverName.toString().toLowerCase()
|
||||
if (nameLower.indexOf("free") >= 0) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
Connections {
|
||||
target: ServersModel
|
||||
function onDefaultServerIndexChanged() {
|
||||
// Пересчитываем isAmneziaFree при изменении сервера
|
||||
var apiConfig = ServersModel.getDefaultServerData("apiConfig")
|
||||
var newValue = false
|
||||
if (ServersModel.getServersCount() > 0 && ServersModel.isDefaultServerFromApi && apiConfig) {
|
||||
var serviceType = ""
|
||||
if (apiConfig.service_type !== undefined) {
|
||||
serviceType = apiConfig.service_type
|
||||
} else if (apiConfig.serviceType !== undefined) {
|
||||
serviceType = apiConfig.serviceType
|
||||
}
|
||||
|
||||
if (serviceType === "amnezia-free") {
|
||||
newValue = true
|
||||
} else {
|
||||
var serverName = ServersModel.defaultServerName
|
||||
if (serverName) {
|
||||
var nameLower = serverName.toString().toLowerCase()
|
||||
if (nameLower.indexOf("free") >= 0) {
|
||||
newValue = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
premiumBannerHome.isAmneziaFree = newValue
|
||||
}
|
||||
}
|
||||
|
||||
visible: isAmneziaFree
|
||||
enabled: visible
|
||||
|
||||
onClicked: {
|
||||
PageController.goToPage(PageEnum.PageSetupWizardPremiumWebView)
|
||||
}
|
||||
|
||||
Keys.onEnterPressed: clicked()
|
||||
Keys.onReturnPressed: clicked()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -578,9 +476,4 @@ PageType {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ApiPremV1MigrationDrawer {
|
||||
id: apiPremV1MigrationDrawer
|
||||
anchors.fill: parent
|
||||
}
|
||||
}
|
||||
|
||||
@@ -101,7 +101,6 @@ PageType {
|
||||
remove,
|
||||
clear,
|
||||
reset,
|
||||
switch_to_premium,
|
||||
]
|
||||
|
||||
QtObject {
|
||||
@@ -237,16 +236,4 @@ PageType {
|
||||
}
|
||||
}
|
||||
|
||||
QtObject {
|
||||
id: switch_to_premium
|
||||
|
||||
property bool isVisible: ServersModel.getProcessedServerData("isServerFromTelegramApi") && ServersModel.processedServerIsPremium
|
||||
readonly property string title: qsTr("Switch to the new Amnezia Premium subscription")
|
||||
readonly property string description: ""
|
||||
readonly property var tColor: AmneziaStyle.color.vibrantRed
|
||||
readonly property var clickedHandler: function() {
|
||||
PageController.goToPageHome()
|
||||
ApiPremV1MigrationController.showMigrationDrawer()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,8 +16,6 @@ import "../Config"
|
||||
PageType {
|
||||
id: root
|
||||
|
||||
property bool isAmneziaFreeSelected: false
|
||||
|
||||
BackButtonType {
|
||||
id: backButton
|
||||
|
||||
@@ -33,8 +31,8 @@ PageType {
|
||||
}
|
||||
}
|
||||
|
||||
ColumnLayout {
|
||||
id: mainLayout
|
||||
ListViewType {
|
||||
id: listView
|
||||
|
||||
anchors.top: backButton.bottom
|
||||
anchors.right: parent.right
|
||||
@@ -42,46 +40,23 @@ PageType {
|
||||
anchors.bottom: parent.bottom
|
||||
anchors.topMargin: 16
|
||||
|
||||
header: ColumnLayout {
|
||||
width: listView.width
|
||||
|
||||
BaseHeaderType {
|
||||
Layout.fillWidth: true
|
||||
Layout.rightMargin: 16
|
||||
Layout.leftMargin: 16
|
||||
Layout.bottomMargin: 24
|
||||
|
||||
headerText: qsTr("VPN by Amnezia")
|
||||
descriptionText: qsTr("Choose a VPN service that suits your needs.")
|
||||
}
|
||||
}
|
||||
|
||||
spacing: 0
|
||||
|
||||
BaseHeaderType {
|
||||
Layout.fillWidth: true
|
||||
Layout.rightMargin: 16
|
||||
Layout.leftMargin: 16
|
||||
Layout.bottomMargin: 24
|
||||
|
||||
headerText: qsTr("VPN by Amnezia")
|
||||
descriptionText: qsTr("Choose a VPN service that suits your needs.")
|
||||
}
|
||||
|
||||
PremiumBannerType {
|
||||
id: premiumBanner
|
||||
|
||||
Layout.fillWidth: true
|
||||
Layout.leftMargin: 16
|
||||
Layout.rightMargin: 16
|
||||
Layout.bottomMargin: 16
|
||||
|
||||
visible: root.isAmneziaFreeSelected
|
||||
enabled: visible
|
||||
|
||||
onClicked: {
|
||||
PageController.goToPage(PageEnum.PageSetupWizardPremiumWebView)
|
||||
}
|
||||
|
||||
Keys.onEnterPressed: clicked()
|
||||
Keys.onReturnPressed: clicked()
|
||||
}
|
||||
|
||||
ListViewType {
|
||||
id: listView
|
||||
|
||||
Layout.fillWidth: true
|
||||
Layout.fillHeight: true
|
||||
|
||||
spacing: 0
|
||||
|
||||
model: SortFilterProxyModel {
|
||||
model: SortFilterProxyModel {
|
||||
id: proxyApiServicesModel
|
||||
|
||||
sourceModel: ApiServicesModel
|
||||
@@ -113,29 +88,8 @@ PageType {
|
||||
|
||||
onClicked: {
|
||||
if (isServiceAvailable) {
|
||||
var sourceIndex = proxyApiServicesModel.mapToSource(index)
|
||||
|
||||
// Устанавливаем индекс ПЕРЕД проверкой типа
|
||||
ApiServicesModel.setServiceIndex(sourceIndex)
|
||||
|
||||
// Проверяем тип через метод
|
||||
var serviceType = ApiServicesModel.getSelectedServiceType()
|
||||
|
||||
// Также проверяем имя напрямую из делегата
|
||||
var nameLower = name ? name.toString().toLowerCase() : ""
|
||||
var nameHasFree = nameLower.indexOf("free") >= 0
|
||||
|
||||
// Комбинированная проверка
|
||||
var isAmneziaFree = (serviceType === "amnezia-free") || nameHasFree
|
||||
|
||||
if (isAmneziaFree) {
|
||||
// Показываем баннер
|
||||
root.isAmneziaFreeSelected = true
|
||||
} else {
|
||||
// Скрываем баннер и переходим на страницу сервиса
|
||||
root.isAmneziaFreeSelected = false
|
||||
PageController.goToPage(PageEnum.PageSetupWizardApiServiceInfo)
|
||||
}
|
||||
ApiServicesModel.setServiceIndex(proxyApiServicesModel.mapToSource(index))
|
||||
PageController.goToPage(PageEnum.PageSetupWizardApiServiceInfo)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -143,6 +97,5 @@ PageType {
|
||||
Keys.onReturnPressed: clicked()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,69 +0,0 @@
|
||||
import QtQuick
|
||||
import QtQuick.Controls
|
||||
import QtQuick.Layouts
|
||||
|
||||
import PageEnum 1.0
|
||||
import Style 1.0
|
||||
import AmneziaWebView 1.0
|
||||
|
||||
import "./"
|
||||
import "../Controls2"
|
||||
import "../Controls2/TextTypes"
|
||||
import "../Config"
|
||||
import "../Components"
|
||||
|
||||
PageType {
|
||||
id: root
|
||||
|
||||
property string premiumUrl: LanguageModel.getCurrentLanguageIndex() === 1 // 1 = Russian
|
||||
? "https://storage.googleapis.com/amnezia/amnezia.org?m-path=/ru/premium"
|
||||
: "https://storage.googleapis.com/amnezia/amnezia.org?m-path=/en/premium"
|
||||
|
||||
BackButtonType {
|
||||
id: backButton
|
||||
|
||||
anchors.top: parent.top
|
||||
anchors.left: parent.left
|
||||
anchors.right: parent.right
|
||||
anchors.topMargin: 20 + SettingsController.safeAreaTopMargin
|
||||
|
||||
z: 1000 // Ensure BackButton is above WebView
|
||||
|
||||
onActiveFocusChanged: {
|
||||
// Focus handling
|
||||
}
|
||||
}
|
||||
|
||||
ColumnLayout {
|
||||
id: webViewContainer
|
||||
|
||||
anchors.top: backButton.bottom
|
||||
anchors.right: parent.right
|
||||
anchors.left: parent.left
|
||||
anchors.bottom: parent.bottom
|
||||
anchors.topMargin: 16
|
||||
|
||||
spacing: 0
|
||||
|
||||
AmneziaWebView {
|
||||
id: webView
|
||||
|
||||
Layout.fillWidth: true
|
||||
Layout.fillHeight: true
|
||||
|
||||
preferredWidth: webViewContainer.width
|
||||
preferredHeight: webViewContainer.height
|
||||
|
||||
url: root.premiumUrl
|
||||
|
||||
onLoadFailed: {
|
||||
console.error("Failed to load Premium page:", root.premiumUrl)
|
||||
}
|
||||
|
||||
onLoadFinished: {
|
||||
console.log("Premium page loaded successfully")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user