基于自定义规则的番剧采集APP,支持流媒体在线观看,支持弹幕,支持实时超分辨率。
feat: migrate from webview_flutter to flutter_inappwebview for Android platform (#1165)
KotaHvc6d74f7f5f1f
diff --git a/lib/pages/webview/webview_controller.dart b/lib/pages/webview/webview_controller.dartindex 654a470d..88de54c2 100644--- a/lib/pages/webview/webview_controller.dart+++ b/lib/pages/webview/webview_controller.dart@@ -1,6 +1,7 @@import 'dart:io';import 'dart:async';+import 'package:kazumi/pages/webview/webview_controller_impel/webview_android_controller_impel.dart';import 'package:kazumi/pages/webview/webview_controller_impel/webview_controller_impel.dart';import 'package:kazumi/pages/webview/webview_controller_impel/webview_windows_controller_impel.dart';import 'package:kazumi/pages/webview/webview_controller_impel/webview_linux_controller_impel.dart';@@ -67,6 +68,9 @@ class WebviewItemControllerFactory {if (Platform.isMacOS || Platform.isIOS) {return WebviewAppleItemControllerImpel();}+ if (Platform.isAndroid) {+ return WebviewAndroidItemControllerImpel();+ }return WebviewItemControllerImpel();}}diff --git a/lib/pages/webview/webview_controller_impel/webview_android_controller_impel.dart b/lib/pages/webview/webview_controller_impel/webview_android_controller_impel.dartnew file mode 100644index 00000000..4c267479--- /dev/null+++ b/lib/pages/webview/webview_controller_impel/webview_android_controller_impel.dart@@ -0,0 +1,331 @@+import 'dart:async';+import 'package:flutter/material.dart';+import 'package:kazumi/utils/utils.dart';+import 'package:kazumi/pages/webview/webview_controller.dart';+import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';++class WebviewAndroidItemControllerImpel+ extends WebviewItemController<PlatformInAppWebViewController> {+ Timer? loadingMonitorTimer;+ bool hasInjectedScripts = false;+ bool shouldInjectIframeRedirect = false;+ bool useNativePlayer = false;++ @override+ Future<void> init() async {+ initEventController.add(true);+ }++ @override+ Future<void> loadUrl(String url, bool useNativePlayer, bool useLegacyParser,+ {int offset = 0}) async {+ await unloadPage();+ if (!hasInjectedScripts) {+ addJavaScriptHandlers(useNativePlayer, useLegacyParser);+ await addUserScripts(useNativePlayer, useLegacyParser);+ hasInjectedScripts = true;+ }+ count = 0;+ this.offset = offset;+ isIframeLoaded = false;+ isVideoSourceLoaded = false;+ shouldInjectIframeRedirect = true;+ this.useNativePlayer = useNativePlayer;+ videoLoadingEventController.add(true);++ await webviewController?.loadUrl(urlRequest: URLRequest(url: WebUri(url)));+ loadingMonitorTimer = Timer.periodic(const Duration(seconds: 1), (timer) {+ if (isVideoSourceLoaded || isIframeLoaded) {+ timer.cancel();+ } else {+ count++;+ if (count >= 15) {+ timer.cancel();++ logEventController.add('clear');+ logEventController.add('解析视频资源超时');+ logEventController.add('请切换到其他播放列表或视频源');+ logEventController.add('showDebug');+ }+ }+ });+ }++ void addJavaScriptHandlers(bool useNativePlayer, bool useLegacyParser) {+ if (!useNativePlayer) {+ debugPrint('[WebView] Adding IframeRedirectBridge handler');+ webviewController?.addJavaScriptHandler(+ handlerName: 'IframeRedirectBridge',+ callback: (args) {+ String message = args[0].toString();+ logEventController.add('Redirect to: $message');+ Future.delayed(const Duration(seconds: 2), () {+ isIframeLoaded = true;+ videoLoadingEventController.add(false);+ });+ });+ } else if (useLegacyParser) {+ debugPrint('[WebView] Adding JSBridgeDebug handler');+ webviewController?.addJavaScriptHandler(+ handlerName: 'JSBridgeDebug',+ callback: (args) {+ String message = args[0].toString();+ logEventController.add('Callback received: $message');+ logEventController.add(+ 'If there is audio but no video, please report it to the rule developer.');+ if ((message.contains('http') || message.startsWith('//')) &&+ !message.contains('googleads') &&+ !message.contains('googlesyndication.com') &&+ !message.contains('prestrain.html') &&+ !message.contains('prestrain%2Ehtml') &&+ !message.contains('adtrafficquality')) {+ logEventController.add('Parsing video source $message');+ String encodedUrl = Uri.encodeFull(message);+ if (Utils.decodeVideoSource(encodedUrl) != encodedUrl) {+ isIframeLoaded = true;+ isVideoSourceLoaded = true;+ videoLoadingEventController.add(false);+ logEventController.add(+ 'Loading video source ${Utils.decodeVideoSource(encodedUrl)}');+ unloadPage();+ videoParserEventController+ .add((Utils.decodeVideoSource(encodedUrl), offset));+ }+ }+ });+ } else {+ debugPrint('[WebView] Adding VideoBridgeDebug handler');+ webviewController?.addJavaScriptHandler(+ handlerName: 'VideoBridgeDebug',+ callback: (args) {+ String message = args[0].toString();+ logEventController.add('Callback received: $message');+ if (message.contains('http') && !isVideoSourceLoaded) {+ logEventController.add('Loading video source: $message');+ isIframeLoaded = true;+ isVideoSourceLoaded = true;+ videoLoadingEventController.add(false);+ unloadPage();+ videoParserEventController.add((message, offset));+ }+ });+ }+ }++ Future<void> addUserScripts(+ bool useNativePlayer, bool useLegacyParser) async {+ if (!useNativePlayer) {+ return;+ }+ final List<UserScript> scripts = [];++ if (useLegacyParser) {+ debugPrint('[WebView] Adding JSBridgeDebug user script');+ const String jsBridgeDebugScript = """+ function processIframeElement(iframe) {+ window.flutter_inappwebview.callHandler('JSBridgeDebug', 'Processing iframe element');+ let src = iframe.getAttribute('src');+ if (src) {+ window.flutter_inappwebview.callHandler('JSBridgeDebug', src);+ }+ }++ const _observer = new MutationObserver((mutations) => {+ window.flutter_inappwebview.callHandler('JSBridgeDebug', 'Scanning for iframes');+ mutations.forEach(mutation => {+ if (mutation.type === 'attributes' && mutation.target.nodeName === 'IFRAME') {+ processIframeElement(mutation.target);+ } else {+ mutation.addedNodes.forEach(node => {+ if (node.nodeName === 'IFRAME') processIframeElement(node);+ if (node.querySelectorAll) {+ node.querySelectorAll('iframe').forEach(processIframeElement);+ }+ });+ }+ });+ });++ _observer.observe(document.documentElement, {+ childList: true,+ subtree: true,+ attributes: true,+ attributeFilter: ['src']+ });+ """;+ scripts.add(UserScript(+ source: jsBridgeDebugScript,+ injectionTime: UserScriptInjectionTime.AT_DOCUMENT_START,+ ));+ } else {+ debugPrint('[WebView] Adding VideoBridgeDebug user script');+ const String blobParserScript = """+ const _r_text = window.Response.prototype.text;+ window.Response.prototype.text = function () {+ return new Promise((resolve, reject) => {+ _r_text.call(this).then((text) => {+ resolve(text);+ if (text.trim().startsWith("#EXTM3U")) {+ console.log('M3U8 source found:', this.url);+ window.flutter_inappwebview.callHandler('VideoBridgeDebug', this.url);+ }+ }).catch(reject);+ });+ }++ const _open = window.XMLHttpRequest.prototype.open;+ window.XMLHttpRequest.prototype.open = function (...args) {+ this.addEventListener("load", () => {+ try {+ let content = this.responseText;+ if (content.trim().startsWith("#EXTM3U")) {+ console.log('M3U8 source found:', args[1]);+ window.flutter_inappwebview.callHandler('VideoBridgeDebug', args[1]);+ };+ } catch {}+ });+ return _open.apply(this, args);+ };+ """;++ const String videoTagParserScript = """+ const _observer = new MutationObserver((mutations) => {+ window.flutter_inappwebview.callHandler('VideoBridgeDebug', 'Scanning for video elements');+ for (const mutation of mutations) {+ if (mutation.type === "attributes" && mutation.target.nodeName === "VIDEO") {+ if (processVideoElement(mutation.target)) return;+ continue;+ }+ for (const node of mutation.addedNodes) {+ if (node.nodeName === "VIDEO") {+ if (processVideoElement(node)) return;+ }+ if (node.querySelectorAll) {+ for (const video of node.querySelectorAll("video")) {+ if (processVideoElement(video)) return;+ }+ }+ }+ }+ });+ function processVideoElement(video) {+ window.flutter_inappwebview.callHandler('VideoBridgeDebug', 'Scanning video element for source URL');+ let src = video.getAttribute('src');+ if (src && src.trim() !== '' && !src.startsWith('blob:') && !src.includes('googleads')) {+ _observer.disconnect();+ console.log('VIDEO source found:', src);+ window.flutter_inappwebview.callHandler('VideoBridgeDebug', src);+ return true;+ }+ const sources = video.getElementsByTagName('source');+ for (let source of sources) {+ src = source.getAttribute('src');+ if (src && src.trim() !== '' && !src.startsWith('blob:') && !src.includes('googleads')) {+ _observer.disconnect();+ console.log('VIDEO source found (source tag):', src);+ window.flutter_inappwebview.callHandler('VideoBridgeDebug', src);+ return true;+ }+ }+ }++ function setupVideoProcessing() {+ for (const video of document.querySelectorAll("video")) {+ if (processVideoElement(video)) return;+ }+ _observer.observe(document.body, {+ childList: true,+ subtree: true,+ attributes: true,+ attributeFilter: ['src']+ });+ }+ if (document.readyState === 'loading') {+ document.addEventListener('DOMContentLoaded', setupVideoProcessing);+ } else {+ setupVideoProcessing();+ }+ """;+ scripts.add(UserScript(+ source: blobParserScript,+ injectionTime: UserScriptInjectionTime.AT_DOCUMENT_START,+ ));+ scripts.add(UserScript(+ source: videoTagParserScript,+ injectionTime: UserScriptInjectionTime.AT_DOCUMENT_START,+ ));+ }++ await webviewController?.addUserScripts(+ userScripts: scripts,+ );+ }++ Future<void> onLoadStart() async {+ if (!useNativePlayer && shouldInjectIframeRedirect) {+ debugPrint('[WebView] Adding IframeRedirectBridge user script');+ shouldInjectIframeRedirect = false;+ await webviewController?.evaluateJavascript(source: """+ const _observer = new MutationObserver((mutations) => {+ for (const mutation of mutations) {+ if (mutation.type === "attributes" && mutation.target.nodeName === "IFRAME") {+ if (processIframeElement(mutation.target)) return;+ continue;+ }+ for (const node of mutation.addedNodes) {+ if (node.nodeName === "IFRAME") {+ if (processIframeElement(node)) return;+ }+ if (node.querySelectorAll) {+ for (const iframe of node.querySelectorAll("iframe")) {+ if (processIframeElement(iframe)) return;+ }+ }+ }+ }+ });++ function processIframeElement(iframe) {+ let src = iframe.getAttribute("src");+ if (src && src.trim() !== '' && (src.startsWith('http') || src.startsWith('//')) && !src.includes('googleads') && !src.includes('adtrafficquality') && !src.includes('googlesyndication.com') && !src.includes('google.com') && !src.includes('prestrain.html') && !src.includes('prestrain%2Ehtml')) {+ _observer.disconnect();+ window.flutter_inappwebview.callHandler("IframeRedirectBridge", src);+ window.location.href = src;+ return true;+ }+ }++ function setupIframeProcessing() {+ for (const iframe of document.querySelectorAll("iframe")) {+ if (processIframeElement(iframe)) return;+ }+ _observer.observe(document.body, {+ childList: true,+ subtree: true,+ attributes: true,+ attributeFilter: ["src"],+ });+ }++ if (document.readyState === 'loading') {+ document.addEventListener('DOMContentLoaded', setupIframeProcessing);+ } else {+ setupIframeProcessing();+ }+ """);+ }+ }++ @override+ Future<void> unloadPage() async {+ loadingMonitorTimer?.cancel();+ await webviewController!.clearAllCache();+ await webviewController!+ .loadUrl(urlRequest: URLRequest(url: WebUri("about:blank")));+ }++ @override+ void dispose() {+ loadingMonitorTimer?.cancel();+ }+}diff --git a/lib/pages/webview/webview_item.dart b/lib/pages/webview/webview_item.dartindex a4718ed4..e368a5e1 100644--- a/lib/pages/webview/webview_item.dart+++ b/lib/pages/webview/webview_item.dart@@ -1,5 +1,6 @@import 'dart:io';import 'package:flutter/material.dart';+import 'package:kazumi/pages/webview/webview_item_impel/webview_android_item_impel.dart';import 'package:kazumi/pages/webview/webview_item_impel/webview_item_impel.dart';import 'package:kazumi/pages/webview/webview_item_impel/webview_windows_item_impel.dart';import 'package:kazumi/pages/webview/webview_item_impel/webview_linux_item_impel.dart';@@ -29,5 +30,8 @@ Widget get webviewUniversal {if (Platform.isMacOS || Platform.isIOS) {return const WebviewAppleItemImpel();}+ if (Platform.isAndroid) {+ return const WebviewAndroidItemImpel();+ }return const WebviewItemImpel();}diff --git a/lib/pages/webview/webview_item_impel/webview_android_item_impel.dart b/lib/pages/webview/webview_item_impel/webview_android_item_impel.dartnew file mode 100644index 00000000..7c910862--- /dev/null+++ b/lib/pages/webview/webview_item_impel/webview_android_item_impel.dart@@ -0,0 +1,61 @@+import 'package:flutter/material.dart';+import 'package:kazumi/pages/webview/webview_controller.dart';+import 'package:flutter_modular/flutter_modular.dart';+import 'package:kazumi/pages/webview/webview_controller_impel/webview_android_controller_impel.dart';+import 'package:kazumi/utils/utils.dart';+import 'package:flutter_inappwebview_platform_interface/flutter_inappwebview_platform_interface.dart';++class WebviewAndroidItemImpel extends StatefulWidget {+ const WebviewAndroidItemImpel({super.key});++ @override+ State<WebviewAndroidItemImpel> createState() =>+ _WebviewAndroidItemImpelState();+}++class _WebviewAndroidItemImpelState extends State<WebviewAndroidItemImpel> {+ final webviewAndroidItemController =+ Modular.get<WebviewItemController>() as WebviewAndroidItemControllerImpel;++ @override+ void initState() {+ super.initState();+ }++ @override+ void dispose() {+ webviewAndroidItemController.dispose();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) {+ return PlatformInAppWebViewWidget(PlatformInAppWebViewWidgetCreationParams(+ initialSettings: InAppWebViewSettings(+ userAgent: Utils.getRandomUA(),+ mediaPlaybackRequiresUserGesture: true,+ cacheEnabled: false,+ blockNetworkImage: true,+ loadsImagesAutomatically: false,+ upgradeKnownHostsToHTTPS: false,+ safeBrowsingEnabled: false,+ mixedContentMode: MixedContentMode.MIXED_CONTENT_COMPATIBILITY_MODE,+ geolocationEnabled: false,+ ),+ onWebViewCreated: (controller) {+ debugPrint('[WebView] Created');+ webviewAndroidItemController.webviewController = controller;+ webviewAndroidItemController.init();+ },+ onLoadStart: (controller, url) async {+ debugPrint('[WebView] Started loading: $url');+ if (url.toString() != 'about:blank') {+ await webviewAndroidItemController.onLoadStart();+ }+ },+ onLoadStop: (controller, url) {+ debugPrint('[WebView] Loading completed: $url');+ },+ )).build(context);+ }+}diff --git a/pubspec.lock b/pubspec.lockindex 3972385c..c3c59ab2 100644--- a/pubspec.lock+++ b/pubspec.lock@@ -460,6 +460,14 @@ packages:url: "https://pub.dev"source: hostedversion: "0.6.0"+ flutter_inappwebview_android:+ dependency: "direct main"+ description:+ name: flutter_inappwebview_android+ sha256: "62557c15a5c2db5d195cb3892aab74fcaec266d7b86d59a6f0027abd672cddba"+ url: "https://pub.dev"+ source: hosted+ version: "1.1.3"flutter_inappwebview_internal_annotations:dependency: transitivedescription:@@ -1604,26 +1612,26 @@ packages:dependency: transitivedescription:name: webview_flutter_android- sha256: "9573ad97890d199ac3ab32399aa33a5412163b37feb573eb5b0a76b35e9ffe41"+ sha256: "414174cacd339046a1a6dbf93cac62422194c676fed11119ccf228b81640e887"url: "https://pub.dev"source: hosted- version: "4.8.2"+ version: "4.9.1"webview_flutter_platform_interface:dependency: transitivedescription:name: webview_flutter_platform_interface- sha256: f0dc2dc3a2b1e3a6abdd6801b9355ebfeb3b8f6cde6b9dc7c9235909c4a1f147+ sha256: "63d26ee3aca7256a83ccb576a50272edd7cfc80573a4305caa98985feb493ee0"url: "https://pub.dev"source: hosted- version: "2.13.1"+ version: "2.14.0"webview_flutter_wkwebview:dependency: transitivedescription:name: webview_flutter_wkwebview- sha256: "71523b9048cf510cfa1fd4e0a3fa5e476a66e0884d5df51d59d5023dba237107"+ sha256: fb46db8216131a3e55bcf44040ca808423539bc6732e7ed34fb6d8044e3d512furl: "https://pub.dev"source: hosted- version: "3.22.1"+ version: "3.23.0"webview_windows:dependency: "direct main"description:diff --git a/pubspec.yaml b/pubspec.yamlindex 183bb720..9f316b32 100644--- a/pubspec.yaml+++ b/pubspec.yaml@@ -2,7 +2,7 @@ name: kazumidescription: "A new Flutter project."# The following line prevents the package from being accidentally published to# pub.dev using `flutter pub publish`. This is preferred for private packages.-publish_to: 'none' # Remove this line if you wish to publish to pub.dev+publish_to: "none" # Remove this line if you wish to publish to pub.dev# The following defines the version and build number for your application.# A version number is three numbers separated by dots, like 1.2.43@@ -19,7 +19,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.devversion: 1.7.5+10705environment:- sdk: '>=3.3.4 <4.0.0'+ sdk: ">=3.3.4 <4.0.0"flutter: 3.32.8# Dependencies specify other packages that your package needs in order to work.@@ -34,7 +34,6 @@ dependencies:flutter_localizations:sdk: flutter-# The following adds the Cupertino Icons font to your application.# Use with the CupertinoIcons class for iOS style icons.cupertino_icons: ^1.0.6@@ -111,6 +110,7 @@ dependencies:flutter_inappwebview_platform_interface: ^1.3.0+1flutter_inappwebview_ios: ^1.1.2flutter_inappwebview_macos: ^1.1.2+ flutter_inappwebview_android: ^1.1.3dependency_overrides:media_kit_libs_linux:@@ -155,7 +155,6 @@ dev_dependencies:flutter_launcher_icons: ^0.14.3flutter_native_splash: ^2.4.3msix: ^3.16.8-# For information on the generic Dart part of this file, see the# following page: https://dart.dev/tools/pub/pubspec@@ -197,7 +196,6 @@ msix_config:# The following section is specific to Flutter packages.flutter:-# The following line ensures that the Material Icons font is# included with your application, so that you can use the icons in# the material Icons class.@@ -208,7 +206,7 @@ flutter:# - images/a_dot_burr.jpeg# - images/a_dot_ham.jpegassets:- - assets/images/+ - assets/images/- assets/plugins/- assets/shaders/- assets/images/logo/