import 'package:flutter/material.dart'; import 'dart:async'; import 'dart:collection'; import 'package:flutter/foundation.dart'; import 'package:flutter_inappwebview/flutter_inappwebview.dart'; import 'package:pwa_ios/utils/constants.dart'; import 'package:pwa_ios/views/login.dart'; import 'package:pwa_ios/utils/util.dart'; import 'package:pwa_ios/widgets/webview_popup.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:url_launcher/url_launcher.dart'; import 'package:internet_connection_checker/internet_connection_checker.dart'; class MyApp extends StatefulWidget { const MyApp({Key? key}) : super(key: key); @override State createState() => _MyAppState(); } // Use WidgetsBindingObserver to listen when the app goes in background // to stop, on Android, JavaScript execution and any processing that can be paused safely, // such as videos, audio, and animations. class _MyAppState extends State with WidgetsBindingObserver { final GlobalKey webViewKey = GlobalKey(); ValueNotifier isLoading = ValueNotifier(true); InAppWebViewController? webViewController; late Future _username; late Future _useremail; late Future _domain; late Future _key; late Future _token; final Future _prefs = SharedPreferences.getInstance(); late final String name, email, key; late String token = ''; late bool logout = false; bool connectivity = true; InAppWebViewSettings sharedSettings = InAppWebViewSettings( // enable opening windows support supportMultipleWindows: true, javaScriptCanOpenWindowsAutomatically: true, // useful for identifying traffic, e.g. in Google Analytics. applicationNameForUserAgent: 'Konectar', // Override the User Agent, otherwise some external APIs, such as Google and Facebook logins, will not work // because they recognize and block the default WebView User Agent. userAgent: 'Mozilla/5.0 (Linux; Android 13) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.5304.105 Mobile Safari/537.36', disableDefaultErrorPage: true, // enable iOS service worker feature limited to defined App Bound Domains limitsNavigationsToAppBoundDomains: true); @override void initState() { WidgetsBinding.instance.addObserver(this); WidgetsBinding.instance.addPostFrameCallback((timeStamp) async { // connectivity = await InternetConnectionChecker().hasConnection; _username = _prefs.then((SharedPreferences prefs) { name = prefs.getString('username') ?? ""; return prefs.getString('username') ?? ""; }); _useremail = _prefs.then((SharedPreferences prefs) { email = prefs.getString('useremail') ?? ""; return prefs.getString('useremail') ?? ""; }); _domain = _prefs.then((SharedPreferences prefs) { return prefs.getString('domain') ?? ""; }); _key = _prefs.then((SharedPreferences prefs) { key = prefs.getString('secretkey') ?? ""; return prefs.getString('secretkey') ?? ""; }); _token = _prefs.then((SharedPreferences prefs) { token = prefs.getString('token') ?? ""; return prefs.getString('token') ?? ""; }); }); super.initState(); } @override void dispose() { webViewController = null; WidgetsBinding.instance.removeObserver(this); super.dispose(); } @override void didChangeAppLifecycleState(AppLifecycleState state) { if (!kIsWeb) { if (webViewController != null && defaultTargetPlatform == TargetPlatform.android) { if (state == AppLifecycleState.paused) { pauseAll(); } else { resumeAll(); } } } } void pauseAll() { if (defaultTargetPlatform == TargetPlatform.android) { webViewController?.pause(); } webViewController?.pauseTimers(); } void resumeAll() { if (defaultTargetPlatform == TargetPlatform.android) { webViewController?.resume(); } webViewController?.resumeTimers(); } @override Widget build(BuildContext context) { return WillPopScope( onWillPop: () async { // detect Android back button click final controller = webViewController; if (controller != null) { if (await controller.canGoBack()) { controller.goBack(); return false; } } return true; }, child: SafeArea( child: Scaffold( body: Column( // mainAxisAlignment: MainAxisAlignment.center, // children: [ Expanded( child: FutureBuilder( future: InternetConnectionChecker().hasConnection, builder: (context, snapshot) { if (!snapshot.hasData) { print("no data******"); return const Text("No internet connectivity!"); } final bool networkAvailable = snapshot.data ?? false; // Android-only final cacheMode = networkAvailable ? CacheMode.LOAD_DEFAULT : CacheMode.LOAD_CACHE_ELSE_NETWORK; // iOS-only final cachePolicy = networkAvailable ? URLRequestCachePolicy.USE_PROTOCOL_CACHE_POLICY : URLRequestCachePolicy.RETURN_CACHE_DATA_ELSE_LOAD; final webViewInitialSettings = sharedSettings.copy(); //webViewInitialSettings.cacheMode = cacheMode; webViewInitialSettings.useShouldOverrideUrlLoading = true; webViewInitialSettings.useShouldInterceptAjaxRequest = true; webViewInitialSettings .javaScriptCanOpenWindowsAutomatically = true; webViewInitialSettings.useShouldInterceptRequest = true; return networkAvailable ? Stack( alignment: AlignmentDirectional.center, children: [ ValueListenableBuilder( valueListenable: isLoading, builder: (context, value, child) { return isLoading.value ? const CircularProgressIndicator() : Center( child: Container( child: const Text( "No internet connectivity!"), ), ); }, ), InAppWebView( key: webViewKey, shouldInterceptRequest: (controller, request) async { print("something"); print(request); return null; }, initialUrlRequest: token.isNotEmpty ? URLRequest( url: WebUri( "https://cardio-staging.konectar.io/contacts")) : URLRequest( url: kPwaUri, headers: { "key": key, "email": email, "name": name, "key": "\$2a\$08\$XeBs/kLqAESRk/jWyNVsyeCjoOvxEmDT7/TK5xkLn23FJ/.5B5beK", // // "email": "scheepu@tikamobile.com", // // "name": "scheepu", }, method: "GET", cachePolicy: cachePolicy), onReceivedServerTrustAuthRequest: (controller, challenge) async { return ServerTrustAuthResponse( action: ServerTrustAuthResponseAction .PROCEED); }, initialUserScripts: UnmodifiableListView([ UserScript( source: """ document.getElementById('notifications').addEventListener('click', function(event) { var randomText = Math.random().toString(36).slice(2, 7); window.flutter_inappwebview.callHandler('requestDummyNotification', randomText); }); """, injectionTime: UserScriptInjectionTime .AT_DOCUMENT_END) ]), initialSettings: webViewInitialSettings, onWebViewCreated: (controller) { webViewController = controller; controller.addJavaScriptHandler( handlerName: 'readystatechange', callback: (arguments) { final String randomText = arguments.isNotEmpty ? arguments[0] : ''; print("responses"); print(arguments); ScaffoldMessenger.of(context) .showSnackBar(const SnackBar( content: Text("some notification"))); }, ); }, shouldOverrideUrlLoading: (controller, navigationAction) async { // restrict navigation to target host, open external links in 3rd party apps final uri = navigationAction.request.url; if (uri != null && navigationAction.isForMainFrame && uri.host != kPwaHost && await canLaunchUrl(uri)) { // launchUrl(uri); return NavigationActionPolicy.CANCEL; } return NavigationActionPolicy.ALLOW; }, onLoadStart: (controller, url) async { isLoading.value = true; print("check urls here ${url.toString()}"); if (url.toString() == 'https://cardio-staging.konectar.io/login/logout') { logout = true; } if (url.toString() == 'https://cardio-staging.konectar.io/login') { controller.loadUrl( urlRequest: URLRequest( url: kPwaUri, headers: { // "key": key, "email": email, "name": name, "key": "\$2a\$08\$XeBs/kLqAESRk/jWyNVsyeCjoOvxEmDT7/TK5xkLn23FJ/.5B5beK", }, method: "GET")); if (logout) { SharedPreferences preferences = await SharedPreferences.getInstance(); await preferences.clear().then((value) { Navigator.pushReplacement( context, MaterialPageRoute( builder: (BuildContext context) => const LoginScreen())); }); } } }, onLoadStop: (controller, url) async { final SharedPreferences prefs = await _prefs; String response = await controller.evaluateJavascript( source: 'document.body.innerText'); // setState(() { // isLoading.value = false; // isLoading.addListener(() {}); // }); if (response.contains('token')) { String token = response .split(',') .last .split(':')[1] .replaceAll('}', "") .replaceAll('"', ""); setState(() { _token = prefs .setString('token', token) .then((bool success) { return _token; }); }); print("response"); print(token); print( "https://cardio-staging.konectar.io/nested_logins/verify_url/$token/notifications/list_all_notifications"); // await ApiCall().listnotifications( // "https://cardio-staging.konectar.io/nested_logins/verify_url/$token/notifications/list_all_notifications"); controller.loadUrl( urlRequest: URLRequest( url: WebUri( "https://cardio-staging.konectar.io/nested_logins/verify_url/$token/contacts/", ), )); } if (await InternetConnectionChecker() .hasConnection && !(await isPWAInstalled())) { // if network is available and this is the first timeß setPWAInstalled(); } }, onReceivedError: (controller, request, error) async { final isForMainFrame = request.isForMainFrame ?? true; if (isForMainFrame && !(await InternetConnectionChecker() .hasConnection)) { if (!(await isPWAInstalled())) { await controller.loadData( data: kHTMLErrorPageNotInstalled); } } }, // shouldInterceptAjaxRequest: // (InAppWebViewController controller, // AjaxRequest ajaxRequest) async { // print("ajax urls"); // print(ajaxRequest.url); // // ajaxRequest.headers!.setRequestHeader( // // "Cookie", "list_all_notifications"); // return ajaxRequest; // }, // onAjaxReadyStateChange: // (InAppWebViewController controller, // AjaxRequest ajaxRequest) async { // print("ajax request"); // print(ajaxRequest.url); // print(ajaxRequest.status); // return AjaxRequestAction.PROCEED; // }, // onAjaxProgress: (InAppWebViewController controller, // AjaxRequest ajaxRequest) async { // print("ajax response"); // print(ajaxRequest.url); // print(ajaxRequest.status); // return AjaxRequestAction.PROCEED; // }, onCreateWindow: (controller, createWindowAction) async { print("CREATES WINDOW"); showDialog( context: context, builder: (context) { final popupWebViewSettings = sharedSettings.copy(); popupWebViewSettings .supportMultipleWindows = false; popupWebViewSettings .javaScriptCanOpenWindowsAutomatically = false; return WebViewPopup( createWindowAction: createWindowAction, popupWebViewSettings: popupWebViewSettings); }, ); return true; }, ), // backdropFilterExample(context), ], ) : Container( child: const Text("No internet"), ); }, ), ), ])), ), ); } // Widget backdropFilterExample(BuildContext context) { // return Positioned.fill( // child: BackdropFilter( // filter: ui.ImageFilter.blur( // sigmaX: 0.0, // sigmaY: 0.0, // ), // child: Container( // // width: MediaQuery.of(context).size.height, // // height: 100, // color: Colors.transparent, // child: isLoading.value // ? Transform.scale( // scale: 0.5, // child: const CircularProgressIndicator( // color: Colors.blue, // ), // ) // : SizedBox.shrink(), // )), // ); // } }