From 9e130f14c5d6a214636f6d52725bb091b07f77b3 Mon Sep 17 00:00:00 2001 From: jdz Date: Wed, 28 Oct 2026 22:56:19 +0800 Subject: [PATCH] =?UTF-8?q?feat(network):=20=E6=96=B0=E5=A2=9E=E5=BA=94?= =?UTF-8?q?=E7=94=A8=E4=BB=A3=E7=90=86=E4=B8=8E=20Linux=20=E5=8E=9F?= =?UTF-8?q?=E7=94=9F=E7=99=BB=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/main.dart | 14 ++- lib/pages/settings_page.dart | 62 ++++++++++++ lib/services/http_client.dart | 18 ++++ lib/services/storage_service.dart | 7 ++ lib/services/uni_auth_service.dart | 20 +++- linux/runner/CMakeLists.txt | 4 + linux/runner/my_application.cc | 7 ++ linux/runner/uni_auth_window.cc | 151 +++++++++++++++++++++++++++++ linux/runner/uni_auth_window.h | 24 +++++ 9 files changed, 303 insertions(+), 4 deletions(-) create mode 100644 linux/runner/uni_auth_window.cc create mode 100644 linux/runner/uni_auth_window.h diff --git a/lib/main.dart b/lib/main.dart index 41ffecb8..dcefffb9 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -61,11 +61,19 @@ void main(List args) async { Future _realMain(SharedPreferences prefs) async { final storageService = StorageService(prefs); + configureAppProxy(storageService.appProxyEnabled ? storageService.appProxyUrl : ''); final debugLogger = DebugLogger()..enabled = storageService.debugMode; final httpClient = LoggingHttpClient(debugLogger); - final uniAuthService = UniAuthService(logger: debugLogger); - final authService = AuthService(storageService, httpClient, uniAuthService, - logger: debugLogger,); + final uniAuthService = UniAuthService( + logger: debugLogger, + proxyUrl: storageService.appProxyEnabled ? storageService.appProxyUrl : '', + ); + final authService = AuthService( + storageService, + httpClient, + uniAuthService, + logger: debugLogger, + ); final themeService = ThemeService(storageService); final campusCardService = CampusCardService(debugLogger: debugLogger, storage: storageService); diff --git a/lib/pages/settings_page.dart b/lib/pages/settings_page.dart index 6de9c254..53e6594a 100644 --- a/lib/pages/settings_page.dart +++ b/lib/pages/settings_page.dart @@ -7,9 +7,12 @@ import 'package:package_info_plus/package_info_plus.dart'; import 'package:techpie/services/auth_service.dart'; import 'package:url_launcher/url_launcher.dart'; +import '../services/http_client.dart'; import '../services/service_provider.dart'; +import '../services/storage_service.dart'; import '../services/sync_service.dart'; import '../services/theme_service.dart'; +import '../services/uni_auth_service.dart'; import '../services/update_service.dart'; import '../utils/adaptive_layout.dart'; import '../utils/platform.dart'; @@ -422,6 +425,28 @@ class _SettingsPageState extends State { }); }, ), + ListTile( + leading: const Icon(Icons.lan_outlined), + title: const Text('Application proxy'), + subtitle: Text( + storage.appProxyEnabled && storage.appProxyUrl.isNotEmpty + ? storage.appProxyUrl + : 'Disabled', + ), + onTap: () => _showProxySettings(storage, sp.uniAuthService), + ), + SwitchListTile( + secondary: const Icon(Icons.power_settings_new), + title: const Text('Enable application proxy'), + value: storage.appProxyEnabled, + onChanged: (value) async { + await storage.setAppProxyEnabled(value); + final proxy = value ? storage.appProxyUrl : ''; + configureAppProxy(proxy); + sp.uniAuthService.setProxyUrl(proxy); + if (mounted) setState(() {}); + }, + ), ListTile( leading: const Icon(Icons.info_outline), title: const Text('About'), @@ -538,6 +563,43 @@ class _SettingsPageState extends State { } } + Future _showProxySettings(StorageService storage, UniAuthService uniAuth) async { + final controller = TextEditingController(text: storage.appProxyUrl); + final value = await showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('Application proxy'), + content: TextField( + controller: controller, + autofocus: true, + decoration: const InputDecoration(hintText: '127.0.0.1:7890'), + keyboardType: TextInputType.url, + ), + actions: [ + TextButton(onPressed: () => Navigator.pop(context), child: const Text('Cancel')), + FilledButton(onPressed: () => Navigator.pop(context, controller.text.trim()), child: const Text('Save')), + ], + ), + ); + controller.dispose(); + if (value == null || !mounted) return; + final proxy = value.trim(); + if (proxy.isNotEmpty && !RegExp(r'^[^\s:]+:\d{1,5}$').hasMatch(proxy)) { + await showAdaptiveAlertDialog( + context: context, + title: 'Invalid proxy', + message: 'Use host:port, for example 127.0.0.1:7890.', + actions: const [AdaptiveAlertAction(label: 'OK')], + ); + return; + } + await storage.setAppProxyUrl(proxy); + await storage.setAppProxyEnabled(proxy.isNotEmpty); + configureAppProxy(proxy); + uniAuth.setProxyUrl(proxy); + setState(() {}); + } + void _showThemePicker(BuildContext context, ThemeService themeService) { if (usesSidebarLayout(context)) { showDesktopPopover( diff --git a/lib/services/http_client.dart b/lib/services/http_client.dart index 72799b95..137f81db 100644 --- a/lib/services/http_client.dart +++ b/lib/services/http_client.dart @@ -1,9 +1,27 @@ import 'dart:convert'; +import 'dart:io'; import 'package:http/http.dart' as http; import 'debug_logger.dart'; +String _appProxy = ''; + +class TechPieHttpOverrides extends HttpOverrides { + @override + HttpClient createHttpClient(SecurityContext? context) { + final client = super.createHttpClient(context); + // Read the current choice on every request, including existing clients. + client.findProxy = (_) => _appProxy.isEmpty ? 'DIRECT' : 'PROXY $_appProxy'; + return client; + } +} + +void configureAppProxy(String value) { + _appProxy = value.trim(); + HttpOverrides.global = TechPieHttpOverrides(); +} + class LoggingHttpClient { final http.Client _inner; final DebugLogger _logger; diff --git a/lib/services/storage_service.dart b/lib/services/storage_service.dart index b42ed5c3..c4a5b8d1 100644 --- a/lib/services/storage_service.dart +++ b/lib/services/storage_service.dart @@ -33,6 +33,8 @@ class StorageService { static const _syncMasterKeyKey = 'sync_master_key'; // secure storage static const _deviceIdKey = 'device_id'; static const _maskPersonalInfoKey = 'mask_personal_info'; + static const _proxyUrlKey = 'app_proxy_url'; + static const _proxyEnabledKey = 'app_proxy_enabled'; final FlutterSecureStorage _secure; final SharedPreferences _prefs; @@ -203,6 +205,11 @@ class StorageService { Future setMaskPersonalInfo(bool value) => _prefs.setBool(_maskPersonalInfoKey, value); + String get appProxyUrl => _prefs.getString(_proxyUrlKey) ?? ''; + Future setAppProxyUrl(String value) => _prefs.setString(_proxyUrlKey, value); + bool get appProxyEnabled => _prefs.getBool(_proxyEnabledKey) ?? false; + Future setAppProxyEnabled(bool value) => _prefs.setBool(_proxyEnabledKey, value); + bool get useLocalhost => !kReleaseMode && (_prefs.getBool(_useLocalhostKey) ?? false); Future setUseLocalhost(bool value) => diff --git a/lib/services/uni_auth_service.dart b/lib/services/uni_auth_service.dart index b68ffbd9..ccd81263 100644 --- a/lib/services/uni_auth_service.dart +++ b/lib/services/uni_auth_service.dart @@ -3,6 +3,7 @@ import 'dart:convert'; import 'package:casdoor_flutter_sdk/casdoor_flutter_sdk.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:http/http.dart' as http; import '../pages/macos_casdoor_auth_page.dart'; @@ -69,7 +70,13 @@ class UniAuthService extends ChangeNotifier { bool get loading => _loading; - UniAuthService({DebugLogger? logger}) : _logger = logger; + UniAuthService({DebugLogger? logger, String proxyUrl = ''}) + : _logger = logger, + _proxyUrl = proxyUrl; + + String _proxyUrl; + String get proxyUrl => _proxyUrl; + void setProxyUrl(String value) => _proxyUrl = value.trim(); final DebugLogger? _logger; @@ -142,6 +149,17 @@ class UniAuthService extends ChangeNotifier { callbackUrl = await _showOhosLogin(navigator, casdoor); } else if (defaultTargetPlatform == TargetPlatform.macOS) { callbackUrl = await _showMacosLogin(navigator, casdoor); + } else if (!kIsWeb && defaultTargetPlatform == TargetPlatform.linux) { + try { + callbackUrl = await const MethodChannel('techpie/uni_auth') + .invokeMethod('authenticate', { + 'url': casdoor.getSigninUrl().toString(), + 'proxy': proxyUrl, + }) ?? ''; + } on PlatformException catch (error) { + if (error.code == 'CANCELLED') throw CasdoorAuthCancelledException(); + rethrow; + } } else { callbackUrl = await casdoor.showFullscreen(context); } diff --git a/linux/runner/CMakeLists.txt b/linux/runner/CMakeLists.txt index e97dabc7..79663fe0 100644 --- a/linux/runner/CMakeLists.txt +++ b/linux/runner/CMakeLists.txt @@ -9,6 +9,7 @@ project(runner LANGUAGES CXX) add_executable(${BINARY_NAME} "main.cc" "my_application.cc" + "uni_auth_window.cc" "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" ) @@ -23,4 +24,7 @@ add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") target_link_libraries(${BINARY_NAME} PRIVATE flutter) target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) +pkg_check_modules(WEBKIT REQUIRED IMPORTED_TARGET webkit2gtk-4.1) +target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::WEBKIT) + target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") diff --git a/linux/runner/my_application.cc b/linux/runner/my_application.cc index 60d12536..7ca46dd3 100644 --- a/linux/runner/my_application.cc +++ b/linux/runner/my_application.cc @@ -1,4 +1,5 @@ #include "my_application.h" +#include "uni_auth_window.h" #include #ifdef GDK_WINDOWING_X11 @@ -10,6 +11,7 @@ struct _MyApplication { GtkApplication parent_instance; char** dart_entrypoint_arguments; + UniAuthWindow* uni_auth_window; }; G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) @@ -74,6 +76,9 @@ static void my_application_activate(GApplication* application) { gtk_widget_realize(GTK_WIDGET(view)); fl_register_plugins(FL_PLUGIN_REGISTRY(view)); + delete self->uni_auth_window; + self->uni_auth_window = new UniAuthWindow( + fl_engine_get_binary_messenger(fl_view_get_engine(view)), window); gtk_widget_grab_focus(GTK_WIDGET(view)); } @@ -120,6 +125,8 @@ static void my_application_shutdown(GApplication* application) { // Implements GObject::dispose. static void my_application_dispose(GObject* object) { MyApplication* self = MY_APPLICATION(object); + delete self->uni_auth_window; + self->uni_auth_window = nullptr; g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); G_OBJECT_CLASS(my_application_parent_class)->dispose(object); } diff --git a/linux/runner/uni_auth_window.cc b/linux/runner/uni_auth_window.cc new file mode 100644 index 00000000..273771d2 --- /dev/null +++ b/linux/runner/uni_auth_window.cc @@ -0,0 +1,151 @@ +#include "uni_auth_window.h" + +UniAuthWindow::UniAuthWindow(FlBinaryMessenger* messenger, GtkWindow* parent) + : parent_(parent) { + g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); + channel_ = fl_method_channel_new(messenger, "techpie/uni_auth", FL_METHOD_CODEC(codec)); + fl_method_channel_set_method_call_handler(channel_, + [](FlMethodChannel*, FlMethodCall* call, gpointer data) { + auto* self = static_cast(data); + if (g_str_equal(fl_method_call_get_name(call), "authenticate")) { + self->Authenticate(call); + } else { + g_autoptr(FlMethodResponse) response = FL_METHOD_RESPONSE(fl_method_not_implemented_response_new()); + fl_method_call_respond(call, response, nullptr); + } + }, this, nullptr); +} + +UniAuthWindow::~UniAuthWindow() { + if (window_) gtk_widget_destroy(window_); + fl_method_channel_set_method_call_handler(channel_, nullptr, nullptr, nullptr); + g_clear_object(&channel_); +} + +void UniAuthWindow::Complete(const gchar* callback) { + if (!pending_) return; + g_autoptr(FlMethodResponse) response = nullptr; + if (callback) { + g_autoptr(FlValue) value = fl_value_new_string(callback); + response = FL_METHOD_RESPONSE(fl_method_success_response_new(value)); + } else { + response = FL_METHOD_RESPONSE(fl_method_error_response_new("CANCELLED", "Login cancelled", nullptr)); + } + fl_method_call_respond(pending_, response, nullptr); + g_clear_object(&pending_); +} + +void UniAuthWindow::Authenticate(FlMethodCall* call) { + FlValue* args = fl_method_call_get_args(call); + const gchar* url = nullptr; + const gchar* proxy = nullptr; + if (args && fl_value_get_type(args) == FL_VALUE_TYPE_MAP) { + FlValue* url_value = fl_value_lookup_string(args, "url"); + FlValue* proxy_value = fl_value_lookup_string(args, "proxy"); + if (url_value && fl_value_get_type(url_value) == FL_VALUE_TYPE_STRING) url = fl_value_get_string(url_value); + if (proxy_value && fl_value_get_type(proxy_value) == FL_VALUE_TYPE_STRING) proxy = fl_value_get_string(proxy_value); + } + g_autoptr(GUri) uri = url ? g_uri_parse(url, G_URI_FLAGS_NONE, nullptr) : nullptr; + if (!uri || g_strcmp0(g_uri_get_scheme(uri), "https") || + g_strcmp0(g_uri_get_host(uri), "auth.geekpie.club")) { + fl_method_call_respond_error(call, "INVALID_URL", "Invalid authorization URL", nullptr, nullptr); + return; + } + if (pending_) { + gtk_window_present(GTK_WINDOW(window_)); + fl_method_call_respond_error(call, "IN_PROGRESS", "Login already open", nullptr, nullptr); + return; + } + pending_ = FL_METHOD_CALL(g_object_ref(call)); + window_ = gtk_window_new(GTK_WINDOW_TOPLEVEL); + gtk_window_set_title(GTK_WINDOW(window_), "GeekPie UniAuth"); + gtk_window_set_default_size(GTK_WINDOW(window_), 520, 720); + gtk_window_set_transient_for(GTK_WINDOW(window_), parent_); + gtk_window_set_destroy_with_parent(GTK_WINDOW(window_), TRUE); + gtk_window_set_modal(GTK_WINDOW(window_), TRUE); + g_signal_connect(window_, "destroy", G_CALLBACK(+[](GtkWidget*, gpointer data) { + auto* self = static_cast(data); + self->window_ = self->status_ = nullptr; + self->webview_ = nullptr; + self->Complete(nullptr); + }), this); + + GtkWidget* box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 8); + gtk_container_add(GTK_CONTAINER(window_), box); + GtkWidget* header = gtk_header_bar_new(); + gtk_header_bar_set_title(GTK_HEADER_BAR(header), "GeekPie UniAuth"); + gtk_header_bar_set_show_close_button(GTK_HEADER_BAR(header), TRUE); + gtk_window_set_titlebar(GTK_WINDOW(window_), header); + GtkWidget* retry = gtk_button_new_with_label("重新加载"); + gtk_header_bar_pack_start(GTK_HEADER_BAR(header), retry); + g_signal_connect(retry, "clicked", G_CALLBACK(+[](GtkButton*, gpointer data) { + auto* self = static_cast(data); + if (self->webview_) webkit_web_view_reload(self->webview_); + }), this); + status_ = gtk_label_new("正在加载登录页…"); + gtk_label_set_line_wrap(GTK_LABEL(status_), TRUE); + gtk_box_pack_start(GTK_BOX(box), status_, FALSE, FALSE, 4); + g_autoptr(WebKitWebContext) context = webkit_web_context_new_ephemeral(); + if (proxy && *proxy) { + g_autoptr(WebKitNetworkProxySettings) settings = webkit_network_proxy_settings_new(nullptr, nullptr); + webkit_network_proxy_settings_add_proxy_for_scheme(settings, "http", proxy); + webkit_network_proxy_settings_add_proxy_for_scheme(settings, "https", proxy); + webkit_website_data_manager_set_network_proxy_settings( + webkit_web_context_get_website_data_manager(context), WEBKIT_NETWORK_PROXY_MODE_CUSTOM, settings); + } else { + webkit_website_data_manager_set_network_proxy_settings( + webkit_web_context_get_website_data_manager(context), WEBKIT_NETWORK_PROXY_MODE_NO_PROXY, nullptr); + } + webview_ = WEBKIT_WEB_VIEW(webkit_web_view_new_with_context(context)); + // Avoid the WebKit/NVIDIA EGL rendering path in this small login window. + webkit_settings_set_hardware_acceleration_policy(webkit_web_view_get_settings(webview_), + WEBKIT_HARDWARE_ACCELERATION_POLICY_NEVER); + gtk_box_pack_start(GTK_BOX(box), GTK_WIDGET(webview_), TRUE, TRUE, 0); + g_signal_connect(webview_, "load-changed", G_CALLBACK(+[](WebKitWebView*, WebKitLoadEvent event, gpointer data) { + auto* self = static_cast(data); + if (!self->status_) return; + if (event == WEBKIT_LOAD_STARTED) { + gtk_label_set_text(GTK_LABEL(self->status_), "正在加载登录页…"); + gtk_widget_show(self->status_); + } else if (event == WEBKIT_LOAD_COMMITTED) { + gtk_widget_hide(self->status_); + } + }), this); + g_signal_connect(webview_, "load-failed", G_CALLBACK(+[](WebKitWebView*, WebKitLoadEvent, + const gchar*, GError* error, gpointer data) -> gboolean { + auto* self = static_cast(data); + if (!self->status_ || g_error_matches(error, WEBKIT_NETWORK_ERROR, WEBKIT_NETWORK_ERROR_CANCELLED)) return FALSE; + gtk_label_set_text(GTK_LABEL(self->status_), "登录页加载失败,请检查网络后点击“重新加载”。"); + gtk_widget_show(self->status_); + return TRUE; + }), this); + g_signal_connect(webview_, "decide-policy", G_CALLBACK(+[](WebKitWebView* view, + WebKitPolicyDecision* decision, WebKitPolicyDecisionType type, gpointer data) -> gboolean { + if (type != WEBKIT_POLICY_DECISION_TYPE_NAVIGATION_ACTION && + type != WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION) return FALSE; + auto* self = static_cast(data); + auto* navigation = WEBKIT_NAVIGATION_POLICY_DECISION(decision); + auto* action = webkit_navigation_policy_decision_get_navigation_action(navigation); + const gchar* url = webkit_uri_request_get_uri(webkit_navigation_action_get_request(action)); + g_autoptr(GUri) uri = g_uri_parse(url, G_URI_FLAGS_NONE, nullptr); + if (uri && g_strcmp0(g_uri_get_scheme(uri), "techpie") == 0) { + webkit_policy_decision_ignore(decision); + if (g_strcmp0(g_uri_get_host(uri), "auth-callback") == 0) { + self->Complete(url); + // GTK queues the close request instead of destroying inside WebKit. + gtk_window_close(GTK_WINDOW(self->window_)); + } + return TRUE; + } + if (type == WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION) { + webkit_policy_decision_ignore(decision); + if (uri && (g_strcmp0(g_uri_get_scheme(uri), "https") == 0 || + g_strcmp0(g_uri_get_scheme(uri), "http") == 0)) + webkit_web_view_load_uri(view, url); + return TRUE; + } + return FALSE; + }), this); + gtk_widget_show_all(window_); + webkit_web_view_load_uri(webview_, url); +} diff --git a/linux/runner/uni_auth_window.h b/linux/runner/uni_auth_window.h new file mode 100644 index 00000000..a86a5e85 --- /dev/null +++ b/linux/runner/uni_auth_window.h @@ -0,0 +1,24 @@ +#ifndef RUNNER_UNI_AUTH_WINDOW_H_ +#define RUNNER_UNI_AUTH_WINDOW_H_ + +#include +#include + +// A GTK authentication window with no secondary Flutter engine. +class UniAuthWindow { + public: + UniAuthWindow(FlBinaryMessenger* messenger, GtkWindow* parent); + ~UniAuthWindow(); + + private: + void Authenticate(FlMethodCall* call); + void Complete(const gchar* callback); + GtkWindow* parent_; + GtkWidget* window_ = nullptr; + GtkWidget* status_ = nullptr; + WebKitWebView* webview_ = nullptr; + FlMethodChannel* channel_; + FlMethodCall* pending_ = nullptr; +}; + +#endif // RUNNER_UNI_AUTH_WINDOW_H_