Refactor H5 line management and cache handling in WebView app

- Introduced shared_preferences for initial H5 cache management.
- Added methods to clear H5 caches and probe line availability.
- Enhanced error handling for line loading and switching.
- Removed openim_common package and its configurations.
- Updated widget tests to reflect changes in H5 line handling and URL management.
This commit is contained in:
Booker
2026-05-29 17:56:55 +07:00
parent 131df57dfe
commit a1e7b3e52c
11 changed files with 881 additions and 288 deletions

View File

@@ -1,9 +1,11 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:webview_flutter_android/webview_flutter_android.dart';
@@ -19,7 +21,11 @@ const _shellBrandingChannel =
MethodChannel('io.openim.flutter.im_webview_app/shell_branding');
const _androidFilePickerChannel =
MethodChannel('io.openim.flutter.openim/file_picker');
const _h5CacheChannel =
MethodChannel('io.openim.flutter.im_webview_app/h5_cache');
const _keyboardAnimationDuration = Duration(milliseconds: 250);
const _initialH5CacheClearedKey = 'initial_h5_cache_cleared_v1';
const _lineProbeTimeout = Duration(seconds: 5);
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
@@ -67,6 +73,12 @@ class ShellBranding {
static String _trim(String? value) => value?.trim() ?? '';
}
enum _LineAvailability {
checking,
available,
unavailable,
}
class ImWebViewApp extends StatelessWidget {
const ImWebViewApp({
super.key,
@@ -100,15 +112,19 @@ class H5ShellPage extends StatefulWidget {
}
class _H5ShellPageState extends State<H5ShellPage> {
late final List<H5Line> _h5Lines;
late final List<_H5LineWebViewSlot> _lineSlots;
late List<H5Line> _h5Lines;
late List<_H5LineWebViewSlot> _lineSlots;
bool _shellBrandingLoaded = false;
bool _isPreparingInitialLine = true;
bool _isAutoSwitchingLine = false;
int _currentLineIndex = 0;
double _lastKeyboardInset = 0;
bool _lastKeyboardVisible = false;
int _keyboardSyncToken = 0;
int _lineProbeGeneration = 0;
late ShellBranding _shellBranding;
Future<void>? _cacheClearTask;
H5Line get _currentLine => _h5Lines[_currentLineIndex];
_H5LineWebViewSlot get _currentSlot => _lineSlots[_currentLineIndex];
@@ -118,14 +134,18 @@ class _H5ShellPageState extends State<H5ShellPage> {
super.initState();
_h5Lines = AppConfig.h5Lines;
_shellBranding = widget.initialShellBranding;
_lineSlots = [
for (var index = 0; index < _h5Lines.length; index += 1)
_lineSlots = _createLineSlots(_h5Lines);
unawaited(_initializeLines());
}
List<_H5LineWebViewSlot> _createLineSlots(List<H5Line> lines) {
return [
for (var index = 0; index < lines.length; index += 1)
_H5LineWebViewSlot(
line: _h5Lines[index],
line: lines[index],
controller: _buildController(index),
),
];
unawaited(_ensureLineLoaded(_currentLineIndex));
}
WebViewController _buildController(int lineIndex) {
@@ -181,13 +201,7 @@ class _H5ShellPageState extends State<H5ShellPage> {
},
onWebResourceError: (error) {
if (error.isForMainFrame ?? true) {
final slot = _lineSlots[lineIndex];
slot.shellCoverFallbackTimer?.cancel();
slot.loadError = error.description;
slot.showShellCover = false;
if (mounted && lineIndex == _currentLineIndex) {
setState(() {});
}
_handleMainFrameLoadError(lineIndex, error.description);
}
},
onNavigationRequest: _handleNavigationRequest,
@@ -238,6 +252,413 @@ class _H5ShellPageState extends State<H5ShellPage> {
super.dispose();
}
Future<void> _initializeLines() async {
await _clearInitialH5CachesIfNeeded();
final runtimeLines = await _fetchRuntimeH5Lines();
if (!mounted) {
return;
}
if (runtimeLines.isNotEmpty && !_hasSameLineUrls(_h5Lines, runtimeLines)) {
setState(() {
_replaceLineSlots(runtimeLines);
});
}
final firstAvailableIndex = await _probeLinesUntilFirstAvailable();
if (!mounted) {
return;
}
if (firstAvailableIndex == null) {
setState(() {
_isPreparingInitialLine = false;
_currentLineIndex = 0;
_currentSlot.loadError = '所有线路暂不可用,请稍后重试';
_currentSlot.showShellCover = false;
});
return;
}
setState(() {
_isPreparingInitialLine = false;
});
await _loadLine(firstAvailableIndex);
}
Future<void> _clearInitialH5CachesIfNeeded() async {
try {
final preferences = await SharedPreferences.getInstance();
if (preferences.getBool(_initialH5CacheClearedKey) == true) {
return;
}
await _clearAllH5Caches();
await preferences.setBool(_initialH5CacheClearedKey, true);
} catch (_) {
await _clearAllH5Caches();
}
}
Future<void> _clearAllH5Caches() {
final runningTask = _cacheClearTask;
if (runningTask != null) {
return runningTask;
}
final task = _clearAllH5CachesInternal();
_cacheClearTask = task;
return task.whenComplete(() {
if (identical(_cacheClearTask, task)) {
_cacheClearTask = null;
}
});
}
Future<void> _clearAllH5CachesInternal() async {
await _clearNativeH5WebsiteData();
await _clearCookiesSafely();
if (_lineSlots.isEmpty) {
final controller = WebViewController();
await _clearControllerStorage(controller);
return;
}
for (final slot in _lineSlots) {
await _clearPageStorage(slot.controller);
await _clearControllerStorage(slot.controller);
}
}
Future<void> _clearNativeH5WebsiteData() async {
try {
await _h5CacheChannel.invokeMethod<void>('clearAllWebsiteData');
} catch (_) {
// Older native shells may not expose the cache channel yet.
}
}
Future<void> _clearCookiesSafely() async {
try {
await WebViewCookieManager().clearCookies();
} catch (_) {
// Cookie clearing is best-effort across platform WebView implementations.
}
}
Future<void> _clearControllerStorage(WebViewController controller) async {
try {
await controller.clearCache();
} catch (_) {}
try {
await controller.clearLocalStorage();
} catch (_) {}
}
Future<void> _clearPageStorage(WebViewController controller) async {
const script = '''
(() => {
try {
if ('caches' in window) {
caches.keys().then((keys) => Promise.all(keys.map((key) => caches.delete(key))));
}
} catch (_) {}
try {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.getRegistrations()
.then((items) => Promise.all(items.map((item) => item.unregister())));
}
} catch (_) {}
try {
if (typeof indexedDB !== 'undefined' && indexedDB.databases) {
indexedDB.databases().then((databases) => {
databases.forEach((database) => {
if (database && database.name) {
indexedDB.deleteDatabase(database.name);
}
});
});
}
} catch (_) {}
try { window.localStorage.clear(); } catch (_) {}
try { window.sessionStorage.clear(); } catch (_) {}
})();
''';
try {
await controller.runJavaScript(script);
} catch (_) {}
}
Future<List<H5Line>> _fetchRuntimeH5Lines() async {
_logH5Lines('启动兜底线路', _h5Lines);
for (final uri in AppConfig.clientConfigQueryUris) {
try {
_logH5LineDebug(
'请求线路配置: $uri payload=${jsonEncode(AppConfig.clientConfigQueryPayload)}',
);
final lines = await _fetchRuntimeH5LinesFrom(uri);
if (lines.isNotEmpty) {
_logH5Lines('接口换算后的线路', lines);
return lines;
}
_logH5LineDebug('线路配置接口没有返回可用 resourceUrl: $uri');
} catch (error) {
_logH5LineDebug('线路配置请求失败: $uri error=$error');
// Try the next compatible endpoint shape.
}
}
_logH5LineDebug('没有获取到远程线路配置,将继续使用启动兜底线路');
return const [];
}
Future<List<H5Line>> _fetchRuntimeH5LinesFrom(Uri uri) async {
final client = HttpClient()..connectionTimeout = _lineProbeTimeout;
try {
final request = await client.postUrl(uri).timeout(_lineProbeTimeout);
request.headers.contentType = ContentType.json;
request.headers.set(HttpHeaders.acceptHeader, 'application/json');
request.headers.set('operationID', _createOperationID());
request.write(jsonEncode(AppConfig.clientConfigQueryPayload));
final response = await request.close().timeout(_lineProbeTimeout);
final body = await utf8.decoder.bind(response).join();
_logH5LineDebug(
'线路配置响应: $uri status=${response.statusCode} body=${_previewForLog(body)}',
);
if (response.statusCode < 200 || response.statusCode >= 300) {
return const [];
}
final decoded = jsonDecode(body);
final resourceUrl = _firstResourceUrlFromClientConfig(decoded);
if (resourceUrl == null || resourceUrl.trim().isEmpty) {
_logH5LineDebug('线路配置未找到 resourceUrl: $uri');
return const [];
}
_logH5LineDebug(
'resourceUrl 原始值: ${_escapeForLog(resourceUrl)}',
);
final resourceLines = AppConfig.splitResourceUrlLines(resourceUrl);
_logStringList('resourceUrl 拆分结果', resourceLines);
return AppConfig.h5LinesFromResourceUrl(resourceUrl);
} finally {
client.close(force: true);
}
}
String _createOperationID() =>
'flutter-h5-line-${DateTime.now().microsecondsSinceEpoch}';
String? _firstResourceUrlFromClientConfig(Object? decoded) {
if (decoded is! Map) {
return null;
}
final data = decoded['data'];
final entries = decoded['entries'] ??
(data is Map ? data['entries'] : null) ??
(data is List ? data : null);
if (entries is! List) {
return null;
}
for (final entry in entries) {
if (entry is! Map) {
continue;
}
final resourceType = entry['resourceType']?.toString().trim() ?? '';
final resourceUrl = entry['resourceUrl']?.toString();
if (resourceUrl == null || resourceUrl.trim().isEmpty) {
continue;
}
if (resourceType.isNotEmpty && resourceType != 'text') {
continue;
}
return resourceUrl;
}
return null;
}
Future<int?> _probeLinesUntilFirstAvailable() async {
final generation = ++_lineProbeGeneration;
for (var index = 0; index < _lineSlots.length; index += 1) {
if (!mounted || generation != _lineProbeGeneration) {
return null;
}
if (await _probeLineAndUpdate(index, generation: generation)) {
unawaited(_probeRemainingLines(index + 1, generation));
return index;
}
}
return null;
}
Future<void> _probeRemainingLines(int startIndex, int generation) async {
for (var index = startIndex; index < _lineSlots.length; index += 1) {
if (!mounted || generation != _lineProbeGeneration) {
return;
}
await _probeLineAndUpdate(index, generation: generation);
}
}
Future<void> _refreshAllLineAvailability() async {
final generation = ++_lineProbeGeneration;
if (mounted) {
setState(() {
for (final slot in _lineSlots) {
slot.availability = _LineAvailability.checking;
}
});
}
await Future.wait([
for (var index = 0; index < _lineSlots.length; index += 1)
_probeLineAndUpdate(index, generation: generation),
]);
}
Future<bool> _probeLineAndUpdate(
int index, {
required int generation,
}) async {
if (index < 0 || index >= _lineSlots.length) {
return false;
}
final line = _lineSlots[index].line;
_setLineAvailability(
index,
_LineAvailability.checking,
generation: generation,
line: line,
);
final available = await _isLineReachable(line);
if (!mounted ||
generation != _lineProbeGeneration ||
index < 0 ||
index >= _lineSlots.length ||
_lineSlots[index].line.url != line.url) {
return false;
}
_setLineAvailability(
index,
available ? _LineAvailability.available : _LineAvailability.unavailable,
generation: generation,
line: line,
);
_logH5LineDebug(
'线路探测: ${line.label} ${line.url} => ${available ? '可用' : '不可用'}',
);
return available;
}
Future<bool> _isLineReachable(H5Line line) async {
final client = HttpClient()..connectionTimeout = _lineProbeTimeout;
try {
final request = await client.getUrl(line.uri).timeout(_lineProbeTimeout);
request.followRedirects = true;
request.maxRedirects = 5;
final response = await request.close().timeout(_lineProbeTimeout);
final available = response.statusCode >= 200 && response.statusCode < 400;
unawaited(response.drain<void>().catchError((_) {}));
return available;
} catch (_) {
return false;
} finally {
client.close(force: true);
}
}
void _setLineAvailability(
int index,
_LineAvailability availability, {
required int generation,
required H5Line line,
}) {
if (!mounted ||
generation != _lineProbeGeneration ||
index < 0 ||
index >= _lineSlots.length ||
_lineSlots[index].line.url != line.url ||
_lineSlots[index].availability == availability) {
return;
}
setState(() {
_lineSlots[index].availability = availability;
});
}
void _replaceLineSlots(List<H5Line> lines) {
for (final slot in _lineSlots) {
slot.dispose();
}
_lineProbeGeneration += 1;
_h5Lines = lines;
_lineSlots = _createLineSlots(lines);
_currentLineIndex = 0;
_isAutoSwitchingLine = false;
_logH5Lines('WebView 使用的线路', _h5Lines);
}
void _logH5Lines(String title, List<H5Line> lines) {
_logH5LineDebug('$title count=${lines.length}');
for (var index = 0; index < lines.length; index += 1) {
_logH5LineDebug(
'$title[${index + 1}] ${lines[index].label} => ${lines[index].url}',
);
}
}
void _logStringList(String title, List<String> values) {
_logH5LineDebug('$title count=${values.length}');
for (var index = 0; index < values.length; index += 1) {
_logH5LineDebug('$title[${index + 1}] ${_escapeForLog(values[index])}');
}
}
void _logH5LineDebug(String message) {
debugPrint('[H5LineDebug] $message');
}
String _previewForLog(String value, {int maxLength = 1200}) {
final escaped = _escapeForLog(value);
if (escaped.length <= maxLength) {
return escaped;
}
return '${escaped.substring(0, maxLength)}...<${escaped.length} chars>';
}
String _escapeForLog(String value) {
return value
.replaceAll('\r', r'\r')
.replaceAll('\n', r'\n')
.replaceAll('\t', r'\t');
}
bool _hasSameLineUrls(List<H5Line> left, List<H5Line> right) {
if (left.length != right.length) {
return false;
}
for (var index = 0; index < left.length; index += 1) {
if (left[index].url != right[index].url) {
return false;
}
}
return true;
}
Future<void> _runJavaScriptSafely(int lineIndex, String source) async {
try {
await _lineSlots[lineIndex].controller.runJavaScript(source);
@@ -252,6 +673,7 @@ class _H5ShellPageState extends State<H5ShellPage> {
await _installRouteObserver(lineIndex);
await _syncKeyboardState(lineIndex);
final slot = _lineSlots[lineIndex];
slot.availability = _LineAvailability.available;
slot.progress = 100;
if (mounted &&
lineIndex == _currentLineIndex &&
@@ -548,6 +970,64 @@ class _H5ShellPageState extends State<H5ShellPage> {
);
}
void _handleMainFrameLoadError(int lineIndex, String description) {
if (lineIndex < 0 || lineIndex >= _lineSlots.length) {
return;
}
final slot = _lineSlots[lineIndex];
slot.shellCoverFallbackTimer?.cancel();
slot.availability = _LineAvailability.unavailable;
slot.loadError = description;
slot.showShellCover = false;
if (mounted && lineIndex == _currentLineIndex) {
setState(() {});
unawaited(_switchToNextUsableLine(lineIndex));
}
}
Future<void> _switchToNextUsableLine(int failedIndex) async {
if (_isAutoSwitchingLine || _lineSlots.length <= 1) {
return;
}
_isAutoSwitchingLine = true;
try {
for (final index in _fallbackLineIndexes(failedIndex)) {
if (!mounted || failedIndex != _currentLineIndex) {
return;
}
final slot = _lineSlots[index];
if (slot.availability == _LineAvailability.unavailable) {
continue;
}
var available = slot.availability == _LineAvailability.available;
if (!available) {
final generation = _lineProbeGeneration;
available = await _probeLineAndUpdate(index, generation: generation);
}
if (available && mounted && failedIndex == _currentLineIndex) {
await _loadLine(index);
return;
}
}
} finally {
_isAutoSwitchingLine = false;
}
}
Iterable<int> _fallbackLineIndexes(int failedIndex) sync* {
for (var index = failedIndex + 1; index < _lineSlots.length; index += 1) {
yield index;
}
for (var index = 0; index < failedIndex; index += 1) {
yield index;
}
}
void _updateSlotUrl(int lineIndex, String? url) {
if (url == null || lineIndex < 0 || lineIndex >= _lineSlots.length) {
return;
@@ -560,9 +1040,12 @@ class _H5ShellPageState extends State<H5ShellPage> {
}
}
Future<void> _ensureLineLoaded(int lineIndex) async {
Future<void> _loadLineHomeRequest(
int lineIndex, {
bool force = false,
}) async {
final slot = _lineSlots[lineIndex];
if (slot.hasLoadedInitialRequest) {
if (slot.hasLoadedInitialRequest && !force) {
return;
}
@@ -596,19 +1079,23 @@ class _H5ShellPageState extends State<H5ShellPage> {
if (slot.hasLoadedInitialRequest) {
await slot.controller.reload();
} else {
await _ensureLineLoaded(_currentLineIndex);
await _loadLineHomeRequest(_currentLineIndex);
}
}
Future<void> _loadLine(int index) async {
Future<void> _loadLine(int index, {bool forceReload = false}) async {
final safeIndex = index < 0 || index >= _h5Lines.length ? 0 : index;
if (_lineSlots[safeIndex].availability == _LineAvailability.unavailable) {
return;
}
if (mounted) {
setState(() {
_currentLineIndex = safeIndex;
});
}
await _ensureLineLoaded(safeIndex);
await _loadLineHomeRequest(safeIndex, force: forceReload);
await _syncKeyboardState(safeIndex);
}
@@ -634,7 +1121,13 @@ class _H5ShellPageState extends State<H5ShellPage> {
);
}
void _showLineSwitcher() {
Future<void> _showLineSwitcher() async {
await _clearAllH5Caches();
await _refreshAllLineAvailability();
if (!mounted) {
return;
}
showModalBottomSheet<void>(
context: context,
useSafeArea: true,
@@ -646,12 +1139,14 @@ class _H5ShellPageState extends State<H5ShellPage> {
builder: (sheetContext) {
return _LineSwitcherSheet(
lines: _h5Lines,
slots: _lineSlots,
currentIndex: _currentLineIndex,
onSelect: (index) {
Navigator.of(sheetContext).pop();
if (index != _currentLineIndex) {
unawaited(_loadLine(index));
if (_lineSlots[index].availability != _LineAvailability.available) {
return;
}
Navigator.of(sheetContext).pop();
unawaited(_loadLine(index, forceReload: true));
},
);
},
@@ -695,12 +1190,14 @@ class _H5ShellPageState extends State<H5ShellPage> {
final topInset = MediaQuery.paddingOf(context).top;
final bottomInset = MediaQuery.viewInsetsOf(context).bottom;
_scheduleKeyboardStateSync(bottomInset);
final showLineSwitch = !currentSlot.showShellCover &&
final showLineSwitch = !_isPreparingInitialLine &&
!currentSlot.showShellCover &&
currentSlot.loadError == null &&
currentSlot.isLoginPage &&
bottomInset == 0;
final shouldPaintShellFallback =
currentSlot.isAwaitingFirstScreen && currentSlot.loadError == null;
(_isPreparingInitialLine || currentSlot.isAwaitingFirstScreen) &&
currentSlot.loadError == null;
return PopScope(
canPop: false,
@@ -760,7 +1257,7 @@ class _H5ShellPageState extends State<H5ShellPage> {
bottom: MediaQuery.paddingOf(context).bottom + 14,
child: _LineSwitchBar(
currentLine: _currentLine,
onSwitch: _showLineSwitcher,
onSwitch: () => unawaited(_showLineSwitcher()),
),
),
],
@@ -806,6 +1303,7 @@ class _H5LineWebViewSlot {
int progress = 0;
String? loadError;
_LineAvailability availability = _LineAvailability.checking;
bool showShellCover = true;
bool hasPresentedFirstScreen = false;
bool hasLoadedInitialRequest = false;
@@ -960,11 +1458,13 @@ class _LineSwitchBar extends StatelessWidget {
class _LineSwitcherSheet extends StatelessWidget {
const _LineSwitcherSheet({
required this.lines,
required this.slots,
required this.currentIndex,
required this.onSelect,
});
final List<H5Line> lines;
final List<_H5LineWebViewSlot> slots;
final int currentIndex;
final ValueChanged<int> onSelect;
@@ -998,10 +1498,12 @@ class _LineSwitcherSheet extends StatelessWidget {
separatorBuilder: (context, index) => const SizedBox(height: 10),
itemBuilder: (context, index) {
final line = lines[index];
final availability = slots[index].availability;
final selected = index == currentIndex;
return _LineOptionTile(
line: line,
availability: availability,
selected: selected,
onTap: () => onSelect(index),
);
@@ -1017,29 +1519,43 @@ class _LineSwitcherSheet extends StatelessWidget {
class _LineOptionTile extends StatelessWidget {
const _LineOptionTile({
required this.line,
required this.availability,
required this.selected,
required this.onTap,
});
final H5Line line;
final _LineAvailability availability;
final bool selected;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
final enabled = availability == _LineAvailability.available;
final foregroundColor = enabled ? const Color(0xFF17233D) : _shellSubText;
final borderColor = selected && enabled
? _shellAccent
: enabled
? const Color(0xFFE1EAF5)
: const Color(0xFFE4E8EE);
return Material(
color: selected ? const Color(0xFFEFF7FF) : Colors.white,
color: selected && enabled
? const Color(0xFFEFF7FF)
: enabled
? Colors.white
: const Color(0xFFF4F6F9),
borderRadius: BorderRadius.circular(8),
child: InkWell(
onTap: onTap,
onTap: enabled ? onTap : null,
borderRadius: BorderRadius.circular(8),
child: Container(
constraints: const BoxConstraints(minHeight: 64),
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
constraints: const BoxConstraints(minHeight: 58),
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
border: Border.all(
color: selected ? _shellAccent : const Color(0xFFE1EAF5),
color: borderColor,
),
),
child: Row(
@@ -1048,7 +1564,7 @@ class _LineOptionTile extends StatelessWidget {
selected
? Icons.radio_button_checked_rounded
: Icons.radio_button_unchecked_rounded,
color: selected ? _shellAccent : _shellSubText,
color: selected && enabled ? _shellAccent : _shellSubText,
size: 22,
),
const SizedBox(width: 12),
@@ -1061,34 +1577,21 @@ class _LineOptionTile extends StatelessWidget {
line.label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
color: Color(0xFF17233D),
style: TextStyle(
color: foregroundColor,
fontSize: 16,
height: 1.2,
fontWeight: FontWeight.w700,
letterSpacing: 0,
),
),
const SizedBox(height: 4),
Text(
line.displayAddress,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
color: _shellSubText,
fontSize: 12,
height: 1.2,
fontWeight: FontWeight.w500,
letterSpacing: 0,
),
),
],
),
),
const SizedBox(width: 8),
const Icon(
Icon(
Icons.chevron_right_rounded,
color: _shellSubText,
color: enabled ? _shellSubText : const Color(0xFFC1CBD8),
size: 22,
),
],