mirror of
https://github.com/GopeedLab/gopeed.git
synced 2026-11-17 05:43:41 +00:00
feat: add WebView support for extension (#1359)
This commit is contained in:
92 files changed
+10248
-2676
No files matched your search
@@ -0,0 +1,90 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:dio/dio.dart';
|
||||
|
||||
import '../../api/model/create_task.dart';
|
||||
import '../../api/model/result.dart';
|
||||
import 'server.dart';
|
||||
|
||||
typedef HostCreateHandler = Future<void> Function(
|
||||
CreateTask createTask,
|
||||
bool silent,
|
||||
);
|
||||
|
||||
typedef HostForwardHandler = Future<dynamic> Function({
|
||||
required String path,
|
||||
required String method,
|
||||
dynamic data,
|
||||
Map<String, dynamic>? query,
|
||||
});
|
||||
|
||||
class HostRpcService {
|
||||
HostRpcService._();
|
||||
|
||||
static final HostRpcService instance = HostRpcService._();
|
||||
|
||||
RpcServerHandle? _server;
|
||||
|
||||
Future<void> start({
|
||||
required HostCreateHandler onCreate,
|
||||
required HostForwardHandler onForward,
|
||||
}) async {
|
||||
if (_server != null) {
|
||||
return;
|
||||
}
|
||||
_server = await startRpcServer(
|
||||
routes: {
|
||||
'/create': (ctx) async {
|
||||
final meta =
|
||||
ctx.request.headers['X-Gopeed-Host-Meta']?.firstOrNull ?? '{}';
|
||||
final jsonMeta = jsonDecode(meta);
|
||||
final silent = jsonMeta['silent'] as bool? ?? false;
|
||||
final params = await ctx.readText();
|
||||
final createTask = CreateTask.fromJson(_decodeParams(params));
|
||||
await onCreate(createTask, silent);
|
||||
},
|
||||
'/forward': (ctx) async {
|
||||
try {
|
||||
final body = await ctx.readJSON();
|
||||
final method = (body['method'] as String?)?.toUpperCase() ?? 'GET';
|
||||
final path = (body['path'] as String?) ?? '/';
|
||||
final data = body['data'];
|
||||
final query = body['query'] as Map<String, dynamic>?;
|
||||
final response = await onForward(
|
||||
path: path,
|
||||
method: method,
|
||||
data: data,
|
||||
query: query,
|
||||
);
|
||||
if (response is Map<String, dynamic>) {
|
||||
await ctx.writeJSON(response);
|
||||
} else {
|
||||
await ctx.writeJSON((response as dynamic).data);
|
||||
}
|
||||
} catch (e) {
|
||||
if (e is DioException && e.response != null) {
|
||||
await ctx.writeJSON(e.response!.data);
|
||||
} else {
|
||||
await ctx.writeJSON(Result(code: 1, msg: e.toString()).toJson());
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> stop() async {
|
||||
final server = _server;
|
||||
_server = null;
|
||||
if (server != null) {
|
||||
await server.close();
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, dynamic> _decodeParams(String params) {
|
||||
final safeParams = params.replaceAll('"', '').replaceAll(' ', '+');
|
||||
final paramsJson =
|
||||
String.fromCharCodes(base64Decode(base64.normalize(safeParams)));
|
||||
return jsonDecode(paramsJson);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:dart_ipc/dart_ipc.dart';
|
||||
|
||||
import '../../util/util.dart';
|
||||
|
||||
class RpcContext {
|
||||
final HttpRequest request;
|
||||
final HttpResponse response;
|
||||
String? _bodyCache;
|
||||
|
||||
RpcContext(this.request, this.response);
|
||||
|
||||
Future<Map<String, dynamic>> readJSON() async {
|
||||
if (_bodyCache == null) {
|
||||
final content = <int>[];
|
||||
await for (final data in request) {
|
||||
content.addAll(data);
|
||||
}
|
||||
_bodyCache = String.fromCharCodes(content);
|
||||
}
|
||||
|
||||
if (_bodyCache!.isEmpty) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return jsonDecode(_bodyCache!) as Map<String, dynamic>;
|
||||
}
|
||||
|
||||
Future<String> readText() async {
|
||||
if (_bodyCache == null) {
|
||||
final content = <int>[];
|
||||
await for (final data in request) {
|
||||
content.addAll(data);
|
||||
}
|
||||
_bodyCache = String.fromCharCodes(content);
|
||||
}
|
||||
|
||||
return _bodyCache ?? '';
|
||||
}
|
||||
|
||||
Future<void> writeJSON(Map<String, dynamic> data) async {
|
||||
response.headers.contentType = ContentType.json;
|
||||
response.write(jsonEncode(data));
|
||||
}
|
||||
|
||||
Future<void> writeError(String message, [int statusCode = 500]) async {
|
||||
response.statusCode = statusCode;
|
||||
await writeJSON({'error': message});
|
||||
}
|
||||
}
|
||||
|
||||
typedef RouteHandler = Future<void> Function(RpcContext ctx);
|
||||
|
||||
class RouteRegistry {
|
||||
final Map<String, RouteHandler> _routes = {};
|
||||
|
||||
void register(String path, RouteHandler handler) {
|
||||
_routes[path] = handler;
|
||||
}
|
||||
|
||||
RouteHandler? getHandler(String path) {
|
||||
return _routes[path];
|
||||
}
|
||||
}
|
||||
|
||||
class RpcBinding {
|
||||
final String network;
|
||||
final String address;
|
||||
|
||||
const RpcBinding({
|
||||
required this.network,
|
||||
required this.address,
|
||||
});
|
||||
}
|
||||
|
||||
class RpcServerHandle {
|
||||
final RpcBinding binding;
|
||||
final HttpServer server;
|
||||
final Future<void> Function()? _cleanup;
|
||||
|
||||
RpcServerHandle({
|
||||
required this.binding,
|
||||
required this.server,
|
||||
Future<void> Function()? cleanup,
|
||||
}) : _cleanup = cleanup;
|
||||
|
||||
Future<void> close({bool force = true}) async {
|
||||
await server.close(force: force);
|
||||
if (_cleanup != null) {
|
||||
await _cleanup!();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<RpcBinding> defaultHostRpcBinding() async {
|
||||
if (Util.isWindows()) {
|
||||
return const RpcBinding(
|
||||
network: 'pipe',
|
||||
address: r'\\.\pipe\gopeed_host',
|
||||
);
|
||||
}
|
||||
return RpcBinding(
|
||||
network: 'unix',
|
||||
address: await Util.homePathJoin('gopeed_host.sock'),
|
||||
);
|
||||
}
|
||||
|
||||
Future<RpcBinding> defaultWebViewRpcBinding() async {
|
||||
if (Util.supportUnixSocket()) {
|
||||
return RpcBinding(
|
||||
network: 'unix',
|
||||
address: await Util.homePathJoin('gopeed_webview.sock'),
|
||||
);
|
||||
}
|
||||
return const RpcBinding(
|
||||
network: 'tcp',
|
||||
address: '127.0.0.1:0',
|
||||
);
|
||||
}
|
||||
|
||||
Future<RpcServerHandle> startRpcServer({
|
||||
RpcBinding? binding,
|
||||
Map<String, RouteHandler>? routes,
|
||||
}) async {
|
||||
final rpcBinding = binding ?? await defaultHostRpcBinding();
|
||||
Future<void> Function()? cleanup;
|
||||
late final HttpServer httpServer;
|
||||
|
||||
switch (rpcBinding.network) {
|
||||
case 'pipe':
|
||||
final serverSocket = await bind(rpcBinding.address);
|
||||
httpServer = HttpServer.listenOn(serverSocket);
|
||||
break;
|
||||
case 'unix':
|
||||
final socketFile = File(rpcBinding.address);
|
||||
if (await socketFile.exists()) {
|
||||
try {
|
||||
await socketFile.delete();
|
||||
} catch (_) {}
|
||||
}
|
||||
final serverSocket = await bind(rpcBinding.address);
|
||||
httpServer = HttpServer.listenOn(serverSocket);
|
||||
cleanup = () async {
|
||||
if (await socketFile.exists()) {
|
||||
try {
|
||||
await socketFile.delete();
|
||||
} catch (_) {}
|
||||
}
|
||||
};
|
||||
break;
|
||||
case 'tcp':
|
||||
final separator = rpcBinding.address.lastIndexOf(':');
|
||||
if (separator <= 0 || separator == rpcBinding.address.length - 1) {
|
||||
throw ArgumentError('invalid tcp rpc address: ${rpcBinding.address}');
|
||||
}
|
||||
final host = rpcBinding.address.substring(0, separator);
|
||||
final port = int.parse(rpcBinding.address.substring(separator + 1));
|
||||
httpServer = await HttpServer.bind(host, port);
|
||||
break;
|
||||
default:
|
||||
throw ArgumentError('unsupported rpc network: ${rpcBinding.network}');
|
||||
}
|
||||
|
||||
final registry = RouteRegistry();
|
||||
routes?.forEach(registry.register);
|
||||
|
||||
httpServer.forEach((request) async {
|
||||
final ctx = RpcContext(request, request.response);
|
||||
try {
|
||||
final handler = registry.getHandler(request.uri.path);
|
||||
if (handler != null) {
|
||||
await handler(ctx);
|
||||
} else {
|
||||
await ctx.writeError('Route not found: ${request.uri.path}', 404);
|
||||
}
|
||||
} catch (e) {
|
||||
await ctx.writeError('Internal server error: $e', 500);
|
||||
} finally {
|
||||
await request.response.close();
|
||||
}
|
||||
});
|
||||
|
||||
var resolvedBinding = rpcBinding;
|
||||
if (rpcBinding.network == 'tcp') {
|
||||
resolvedBinding = RpcBinding(
|
||||
network: rpcBinding.network,
|
||||
address: '${httpServer.address.address}:${httpServer.port}',
|
||||
);
|
||||
}
|
||||
|
||||
return RpcServerHandle(
|
||||
binding: resolvedBinding,
|
||||
server: httpServer,
|
||||
cleanup: cleanup,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'webview_rpc_service.dart';
|
||||
|
||||
class WebViewRpcOverlay extends StatefulWidget {
|
||||
const WebViewRpcOverlay({super.key});
|
||||
|
||||
@override
|
||||
State<WebViewRpcOverlay> createState() => _WebViewRpcOverlayState();
|
||||
}
|
||||
|
||||
class _WebViewRpcOverlayState extends State<WebViewRpcOverlay> {
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
WebViewRpcService.instance.markOverlayReady();
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ValueListenableBuilder<List<WebViewRpcPageSession>>(
|
||||
valueListenable: WebViewRpcService.instance.pages,
|
||||
builder: (context, pages, _) {
|
||||
if (pages.isEmpty) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
return IgnorePointer(
|
||||
ignoring: false,
|
||||
child: Stack(
|
||||
children: pages
|
||||
.map((page) => _WebViewRpcPageView(page: page))
|
||||
.toList(growable: false),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _WebViewRpcPageView extends StatefulWidget {
|
||||
const _WebViewRpcPageView({required this.page});
|
||||
|
||||
final WebViewRpcPageSession page;
|
||||
|
||||
@override
|
||||
State<_WebViewRpcPageView> createState() => _WebViewRpcPageViewState();
|
||||
}
|
||||
|
||||
class _WebViewRpcPageViewState extends State<_WebViewRpcPageView> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final page = widget.page;
|
||||
final content = page.buildWebView();
|
||||
|
||||
return Positioned.fill(
|
||||
child: Material(
|
||||
color: Colors.black54,
|
||||
child: Center(
|
||||
child: Container(
|
||||
width: page.width > 0 ? page.width.toDouble() : 960,
|
||||
height: page.height > 0 ? page.height.toDouble() : 720,
|
||||
clipBehavior: Clip.antiAlias,
|
||||
decoration: BoxDecoration(
|
||||
color: Theme.of(context).colorScheme.surface,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
boxShadow: const [
|
||||
BoxShadow(
|
||||
blurRadius: 24,
|
||||
color: Colors.black26,
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Column(
|
||||
children: [
|
||||
Container(
|
||||
height: 44,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
alignment: Alignment.centerLeft,
|
||||
color: Theme.of(context).colorScheme.surfaceContainerHighest,
|
||||
child: Text(
|
||||
page.title.isNotEmpty ? page.title : 'WebView',
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: Theme.of(context).textTheme.titleSmall,
|
||||
),
|
||||
),
|
||||
Expanded(child: content),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user