fix: 兼容 Web 同源部署地址

This commit is contained in:
2026-06-24 21:10:21 +08:00
parent 7cb51e70a3
commit 2281c98b1b
2 changed files with 40 additions and 10 deletions

View File

@@ -3,11 +3,16 @@ import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
class SettingsProvider with ChangeNotifier {
// Use 10.0.2.2 for Android emulator to access host's localhost
static String get _defaultUrl =>
(defaultTargetPlatform == TargetPlatform.android && !kIsWeb)
? "http://10.0.2.2:8080"
: "http://localhost:8080";
// On web: use empty string so API calls use same origin (works behind any proxy)
// On Android emulator: 10.0.2.2 maps to host localhost
// On other platforms: localhost
static String get _defaultUrl {
if (kIsWeb) return "";
if (defaultTargetPlatform == TargetPlatform.android) {
return "http://10.0.2.2:8080";
}
return "http://localhost:8080";
}
String _baseUrl = _defaultUrl;
Color _themeColor = Colors.blue;
@@ -38,7 +43,7 @@ class SettingsProvider with ChangeNotifier {
}
_livePreviewThumbnailsEnabled =
prefs.getBool('livePreviewThumbnailsEnabled') ?? false;
final languageCode = prefs.getString('languageCode');
final scriptCode = prefs.getString('scriptCode');
final countryCode = prefs.getString('countryCode');
@@ -49,7 +54,7 @@ class SettingsProvider with ChangeNotifier {
countryCode: countryCode,
);
}
notifyListeners();
}
@@ -106,8 +111,18 @@ class SettingsProvider with ChangeNotifier {
// Also provide the RTMP URL based on the same hostname
String get rtmpUrl {
final uri = Uri.parse(_baseUrl);
return "rtmp://${uri.host}:1935/live";
final host = _baseUrl.isEmpty ? _effectiveHost : Uri.parse(_baseUrl).host;
return "rtmp://$host:1935/live";
}
// Fallback hostname when baseUrl is empty (web same-origin mode)
String get _effectiveHost {
if (kIsWeb) {
final host = Uri.base.host;
if (host.isNotEmpty) return host;
return 'localhost';
}
return 'localhost';
}
String playbackUrl(String roomId, {String? quality}) {

View File

@@ -45,7 +45,7 @@ class ChatService {
Stream<ChatMessage> get messages => _messageController.stream;
void connect(String baseUrl, String roomId, String username) {
final wsUri = Uri.parse(baseUrl).replace(
final wsUri = _webSocketUri(baseUrl).replace(
scheme: 'ws',
path: '/api/ws/room/$roomId',
queryParameters: {'username': username},
@@ -83,6 +83,21 @@ class ChatService {
}
}
Uri _webSocketUri(String baseUrl) {
if (baseUrl.isEmpty) {
if (kIsWeb) {
return Uri.base.replace(
scheme: Uri.base.scheme == 'https' ? 'wss' : 'ws',
);
}
return Uri.parse('http://localhost:8080');
}
final uri = Uri.parse(baseUrl);
final scheme = uri.scheme == 'https' ? 'wss' : 'ws';
return uri.replace(scheme: scheme);
}
void dispose() {
_channel?.sink.close();
_messageController.close();