diff --git a/assets/audio/ring_30Sec.caf b/assets/audio/ring_30Sec.caf new file mode 100644 index 0000000..b5bb4b8 Binary files /dev/null and b/assets/audio/ring_30Sec.caf differ diff --git a/assets/audio/ring_60Sec.mp3 b/assets/audio/ring_60Sec.mp3 new file mode 100644 index 0000000..ac32394 Binary files /dev/null and b/assets/audio/ring_60Sec.mp3 differ diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swift index b4ad5b3..5b1bfee 100644 --- a/ios/Runner/AppDelegate.swift +++ b/ios/Runner/AppDelegate.swift @@ -1,11 +1,13 @@ import UIKit +import PushKit import Flutter import Firebase +import flutter_callkit_incoming import flutter_local_notifications - +// PKPushRegistryDelegate @UIApplicationMain -@objc class AppDelegate: FlutterAppDelegate { +@objc class AppDelegate: FlutterAppDelegate, PKPushRegistryDelegate { override func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? @@ -18,6 +20,51 @@ import flutter_local_notifications UNUserNotificationCenter.current().delegate = self as UNUserNotificationCenterDelegate } GeneratedPluginRegistrant.register(with: self) - return super.application(application, didFinishLaunchingWithOptions: launchOptions) - } + + //Setup VOIP + let mainQueue = DispatchQueue.main + let voipRegistry: PKPushRegistry = PKPushRegistry(queue: mainQueue) + voipRegistry.delegate = self + voipRegistry.desiredPushTypes = [PKPushType.voIP] + + return super.application(application, didFinishLaunchingWithOptions: launchOptions) + } + + // Handle updated push credentials + func pushRegistry(_ registry: PKPushRegistry, didUpdate credentials: PKPushCredentials, for type: PKPushType) { + print(credentials.token) + let deviceToken = credentials.token.map { String(format: "%02x", $0) }.joined() + print(deviceToken) + print("deviceToken From Swift") + //Save deviceToken to your server + SwiftFlutterCallkitIncomingPlugin.sharedInstance?.setDevicePushTokenVoIP(deviceToken) + } + + func pushRegistry(_ registry: PKPushRegistry, didInvalidatePushTokenFor type: PKPushType) { + print("didInvalidatePushTokenFor") + SwiftFlutterCallkitIncomingPlugin.sharedInstance?.setDevicePushTokenVoIP("") + } + + // Handle incoming pushes + func pushRegistry(_ registry: PKPushRegistry, didReceiveIncomingPushWith payload: PKPushPayload, for type: PKPushType, completion: @escaping () -> Void) { + print("didReceiveIncomingPushWith") + guard type == .voIP else { return } + print(payload.dictionaryPayload) +// let id = payload.dictionaryPayload["id"] as? String ?? "" +// let nameCaller = payload.dictionaryPayload["nameCaller"] as? String ?? "" +// let handle = payload.dictionaryPayload["handle"] as? String ?? "" + let isVideo = payload.dictionaryPayload["isVideo"] as? Bool ?? false +// +// + let data = flutter_callkit_incoming.Data(id: "1", nameCaller: "Mohemm", handle: "handle", type: isVideo ? 1 : 0) +// //set more data +// data.extra = ["user": "abc@123", "platform": "ios"] +// //data.iconName = ... +// //data..... +// data.appName = "Mohemm" +// data.iconName = "Mohemm" + SwiftFlutterCallkitIncomingPlugin.sharedInstance?.showCallkitIncoming(data, fromPushKit: true) + } + + } diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist index 75c680b..50ff832 100644 --- a/ios/Runner/Info.plist +++ b/ios/Runner/Info.plist @@ -57,8 +57,11 @@ This app requires microphone access to for call. UIBackgroundModes + processing fetch remote-notification + voip + FirebaseAppDelegateProxyEnabled @@ -91,5 +94,7 @@ TAG + UIApplicationSupportsIndirectInputEvents + diff --git a/lib/api/chat/chat_api_client.dart b/lib/api/chat/chat_api_client.dart index f727c7d..275f10b 100644 --- a/lib/api/chat/chat_api_client.dart +++ b/lib/api/chat/chat_api_client.dart @@ -71,9 +71,7 @@ class ChatApiClient { if (!kReleaseMode) { logger.i("res: " + response.body); } - return ChatUserModel.fromJson( - json.decode(response.body), - ); + return ChatUserModel.fromJson(json.decode(response.body)); } catch (e) { throw e; } diff --git a/lib/classes/chat_call_kit.dart b/lib/classes/chat_call_kit.dart new file mode 100644 index 0000000..2059eec --- /dev/null +++ b/lib/classes/chat_call_kit.dart @@ -0,0 +1,203 @@ +import 'dart:convert'; +import 'package:firebase_messaging/firebase_messaging.dart'; +import 'package:flutter/cupertino.dart'; +import 'package:flutter_callkit_incoming/entities/entities.dart'; +import 'package:flutter_callkit_incoming/flutter_callkit_incoming.dart'; +import 'package:mohem_flutter_app/app_state/app_state.dart'; +import 'package:mohem_flutter_app/classes/navigationService.dart'; +import 'package:mohem_flutter_app/classes/notifications.dart'; +import 'package:mohem_flutter_app/classes/utils.dart'; +import 'package:mohem_flutter_app/config/routes.dart'; +import 'package:mohem_flutter_app/main.dart'; +import 'package:mohem_flutter_app/models/chat/call.dart'; +import 'package:mohem_flutter_app/models/chat/get_single_user_chat_list_model.dart'; +import 'package:mohem_flutter_app/models/chat/get_user_login_token_model.dart' as ALM; +import 'package:mohem_flutter_app/models/chat/get_user_login_token_model.dart'; +import 'package:mohem_flutter_app/provider/chat_call_provider.dart'; +import 'package:mohem_flutter_app/provider/chat_provider_model.dart'; +import 'package:provider/provider.dart'; + +class ChatVoipCall { + static final ChatVoipCall _instance = ChatVoipCall._internal(); + + ChatVoipCall._internal(); + + factory ChatVoipCall() => _instance; + + late ChatProviderModel prov; + late ChatCallProvider cProv; + dynamic inCallData; + bool isUserOnline = false; + dynamic callData; + + Future showCallkitIncoming({required String uuid, RemoteMessage? data, CallDataModel? incomingCallData, bool background = false}) async { + await ChatVoipCall().listenerEvent(); + await FlutterCallkitIncoming.endAllCalls(); + ALM.Response autoLoginData; + SingleUserChatModel callerData; + if (data!.data["user_token_response"] == null || data.data["user_token_response"].isEmpty) { + // Online & App Logged In + ALM.Response sharedDetails = ALM.Response.fromJson(jsonDecode(await Utils.getStringFromPrefs("userLoginChatDetails"))); + + autoLoginData = ALM.Response.fromJson(AppState().getchatUserDetails == null ? sharedDetails.toJson() : AppState().getchatUserDetails!.response!.toJson()); + dynamic items = jsonDecode(data!.data["user_chat_history_response"]); + callerData = SingleUserChatModel( + targetUserId: items["CurrentUserId"], + targetUserEmail: items["CurrentUserEmail"], + targetUserName: items["CurrentUserName"].split("@").first, + currentUserId: autoLoginData.id, + currentUserEmail: autoLoginData.email, + currentUserName: autoLoginData.userName, + chatEventId: 3); + isUserOnline = true; + } else { + // Offline or App in Background or App is At Verify Screen + autoLoginData = ALM.Response.fromJson(jsonDecode(data.data["user_token_response"])); + callerData = SingleUserChatModel.fromJson(json.decode(data!.data["user_chat_history_response"])); + } + CallKitParams params = CallKitParams( + id: uuid, + nameCaller: callerData.targetUserName, + appName: 'Mohemm', + handle: '', + type: 0, + duration: 25000, + textAccept: 'Accept', + textDecline: 'Decline', + textMissedCall: 'Missed call', + textCallback: 'Call back', + extra: { + "loginDetails": autoLoginData.toJson(), + "callerDetails": callerData.toJson(), + 'isIncomingCall': true, + }, + android: const AndroidParams( + isCustomNotification: true, + isShowLogo: false, + isShowCallback: false, + isShowMissedCallNotification: true, + ringtonePath: 'system_ringtone_default', + backgroundColor: '#0955fa', + backgroundUrl: 'assets/test.png', + actionColor: '#4CAF50', + ), + ios: IOSParams( + iconName: 'Mohemm', + handleType: '', + supportsVideo: true, + maximumCallGroups: 2, + maximumCallsPerCallGroup: 1, + audioSessionMode: 'default', + audioSessionActive: true, + audioSessionPreferredSampleRate: 38000.0, + audioSessionPreferredIOBufferDuration: 0.005, + supportsDTMF: true, + supportsHolding: true, + supportsGrouping: false, + supportsUngrouping: false, + ringtonePath: 'system_ringtone_default', + ), + ); + if (callerData.chatEventId == 3) { + await Utils.saveStringFromPrefs("isIncomingCall", "true"); + await FlutterCallkitIncoming.showCallkitIncoming(params); + } + } + Future getCurrentCall() async { + var calls = await FlutterCallkitIncoming.activeCalls(); + if (calls is List) { + if (calls.isNotEmpty) { + return calls[0]; + } else { + return null; + } + } + } + + void checkAndNavigationCallingPage() async { + var currentCall = await getCurrentCall(); + if (currentCall != null) { + Future.delayed(const Duration(seconds: 2)).whenComplete(() { + Navigator.pushNamed(AppRoutes.navigatorKey.currentContext!, AppRoutes.chatStartCall); + }); + } + } + + Future isCall() async { + var calls = await FlutterCallkitIncoming.activeCalls(); + if (calls is List) { + if (calls.isNotEmpty) { + NavigationService.navigateTo(AppRoutes.chatStartCall); + } + } + } + +//Function(CallEvent) callback + Future listenerEvent() async { + try { + FlutterCallkitIncoming.onEvent.listen((CallEvent? event) async { + switch (event!.event) { + case Event.ACTION_CALL_INCOMING: + break; + case Event.ACTION_CALL_START: + break; + case Event.ACTION_CALL_ACCEPT: + if (isUserOnline) { + checkAndNavigationCallingPage(); + } else { + isCall(); + } + break; + case Event.ACTION_CALL_DECLINE: + // cProv.isIncomingCall = true; + Utils.saveStringFromPrefs("isIncomingCall", "false"); + Utils.saveStringFromPrefs("inComingCallData", "null"); + + // cProv.endCall(isUserOnline: true); + FlutterCallkitIncoming.endAllCalls(); + break; + case Event.ACTION_CALL_ENDED: + Utils.saveStringFromPrefs("isIncomingCall", "false"); + Utils.saveStringFromPrefs("inComingCallData", "null"); + FlutterCallkitIncoming.endAllCalls(); + break; + case Event.ACTION_CALL_TIMEOUT: + Utils.saveStringFromPrefs("isIncomingCall", "false"); + Utils.saveStringFromPrefs("inComingCallData", "null"); + break; + } + }); + } on Exception {} + } + + void nothing() { + // if (!background) { + // await initProviders(); + // if (data!.data["callType"] == "video") { + // cProv.isVideoCall = true; + // } else { + // cProv.isAudioCall = true; + // cProv.isVideoCall = false; + // } + // } + // + // // if(!background){} + // await initProviders(); + + // callData = jsonEncode([ + // { + // "loginDetails": autoLoginData.toJson(), + // "callerDetails": callerData.toJson(), + // } + // ]); + + // connection(data: callData, isUserOnline: isUserOnline).whenComplete(() => {}); + // if (isUserOnline) { + // cProv.init(); + // } + // if (!isUserOnline) { + // initProviders(); + // } + // Navigator.pushNamed(AppRoutes.navigatorKey.currentContext!, AppRoutes.chatStartCall); + } +} diff --git a/lib/classes/consts.dart b/lib/classes/consts.dart index 32b3fc7..422afea 100644 --- a/lib/classes/consts.dart +++ b/lib/classes/consts.dart @@ -3,8 +3,8 @@ import 'package:mohem_flutter_app/ui/marathon/widgets/question_card.dart'; class ApiConsts { //static String baseUrl = "http://10.200.204.20:2801/"; // Local server // static String baseUrl = "https://erptstapp.srca.org.sa"; // SRCA server - static String baseUrl = "https://uat.hmgwebservices.com"; // UAT server - // static String baseUrl = "https://hmgwebservices.com"; // Live server + // static String baseUrl = "https://uat.hmgwebservices.com"; // UAT server + static String baseUrl = "https://hmgwebservices.com"; // Live server static String baseUrlServices = baseUrl + "/Services/"; // server // static String baseUrlServices = "https://api.cssynapses.com/tangheem/"; // Live server static String utilitiesRest = baseUrlServices + "Utilities.svc/REST/"; diff --git a/lib/classes/navigationService.dart b/lib/classes/navigationService.dart new file mode 100644 index 0000000..d18a945 --- /dev/null +++ b/lib/classes/navigationService.dart @@ -0,0 +1,25 @@ +import 'package:flutter/material.dart'; +import 'package:get_it/get_it.dart'; +import 'package:mohem_flutter_app/app_state/app_state.dart'; +import 'package:mohem_flutter_app/config/routes.dart'; + +final locator = GetIt.instance; + +class NavigationService { + final GlobalKey navigatorKey = AppRoutes.navigatorKey; + + static Future navigateTo(String routeName) { + var key = locator().navigatorKey; + return key.currentState!.pushNamed(routeName); + } + + static Future navigateToPage(Widget page) { + var key = locator().navigatorKey; + var pageRoute = MaterialPageRoute(builder: (context) => page); + return Navigator.push(key.currentContext!, pageRoute); + } +} + +void setupLocator() { + locator.registerLazySingleton( ()=> NavigationService()); +} diff --git a/lib/classes/notifications.dart b/lib/classes/notifications.dart index 9528616..c573e4b 100644 --- a/lib/classes/notifications.dart +++ b/lib/classes/notifications.dart @@ -2,20 +2,22 @@ import 'dart:io'; import 'package:firebase_core/firebase_core.dart'; import 'package:firebase_messaging/firebase_messaging.dart'; +import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart'; -// import 'package:huawei_hmsavailability/huawei_hmsavailability.dart'; import 'package:huawei_push/huawei_push.dart' as huawei_push; import 'package:mohem_flutter_app/app_state/app_state.dart'; +import 'package:mohem_flutter_app/classes/chat_call_kit.dart'; import 'package:mohem_flutter_app/classes/utils.dart'; +import 'package:mohem_flutter_app/main.dart'; import 'package:permission_handler/permission_handler.dart'; +import 'package:uuid/uuid.dart'; final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); class AppNotifications { static final AppNotifications _instance = AppNotifications._internal(); - AppNotifications._internal(); factory AppNotifications() => _instance; @@ -57,7 +59,7 @@ class AppNotifications { if (initialMessage != null) _handleMessage(initialMessage); FirebaseMessaging.onMessage.listen((RemoteMessage message) { - if (message.notification != null) _handleMessage(message); + if (message != null) _handleMessage(message); }); FirebaseMessaging.onMessageOpenedApp.listen(_handleOpenApp); @@ -113,6 +115,12 @@ class AppNotifications { void _handleMessage(RemoteMessage message) { Utils.saveStringFromPrefs("isAppOpendByChat", "false"); + if (message.data.isNotEmpty && message.data["messageType"] == 'chat') { + Utils.saveStringFromPrefs("isAppOpendByChat", "true"); + Utils.saveStringFromPrefs("notificationData", message.data["user_chat_history_response"].toString()); + } else if (message.data.isNotEmpty && message.data["messageType"] == 'call') { + ChatVoipCall().showCallkitIncoming(uuid: const Uuid().v4(), data: message); + } } void _handleOpenApp(RemoteMessage message) { @@ -131,9 +139,10 @@ AndroidNotificationChannel channel = const AndroidNotificationChannel( Future backgroundMessageHandler(RemoteMessage message) async { await Firebase.initializeApp(); - Utils.saveStringFromPrefs("isAppOpendByChat", "false"); - Utils.saveStringFromPrefs("notificationData", message.data["user_chat_history_response"].toString()); - if (message.data.isNotEmpty && message.data["type"] == 'call') { - // ChatVoipCall().showCallkitIncoming(uuid: const Uuid().v4(), data: message); + if (message.data.isNotEmpty && message.data["messageType"] == 'chat') { + Utils.saveStringFromPrefs("isAppOpendByChat", "false"); + Utils.saveStringFromPrefs("notificationData", message.data["user_chat_history_response"].toString()); + } else if (message.data.isNotEmpty && message.data["messageType"] == 'call') { + ChatVoipCall().showCallkitIncoming(uuid: const Uuid().v4(), data: message, background: true); } } diff --git a/lib/config/routes.dart b/lib/config/routes.dart index 7ccb6ce..2667494 100644 --- a/lib/config/routes.dart +++ b/lib/config/routes.dart @@ -4,6 +4,7 @@ import 'package:mohem_flutter_app/ui/attendance/add_vacation_rule_screen.dart'; import 'package:mohem_flutter_app/ui/attendance/monthly_attendance_screen.dart'; import 'package:mohem_flutter_app/ui/attendance/vacation_rule_screen.dart'; import 'package:mohem_flutter_app/ui/bottom_sheets/attendence_details_bottom_sheet.dart'; +import 'package:mohem_flutter_app/ui/chat/call/chat_incoming_call_screen.dart'; import 'package:mohem_flutter_app/ui/chat/chat_detailed_screen.dart'; import 'package:mohem_flutter_app/ui/chat/chat_home.dart'; import 'package:mohem_flutter_app/ui/chat/favorite_users_screen.dart'; @@ -184,6 +185,7 @@ class AppRoutes { static const String chat = "/chat"; static const String chatDetailed = "/chatDetailed"; static const String chatFavoriteUsers = "/chatFavoriteUsers"; + static const String chatStartCall = "/chatStartCall"; //Marathon static const String marathonIntroScreen = "/marathonIntroScreen"; @@ -296,6 +298,8 @@ class AppRoutes { chat: (BuildContext context) => ChatHome(), chatDetailed: (BuildContext context) => ChatDetailScreen(), chatFavoriteUsers: (BuildContext context) => ChatFavoriteUsersScreen(), + chatStartCall: (BuildContext context) => StartCallPage(), + // Marathon marathonIntroScreen: (BuildContext context) => MarathonIntroScreen(), diff --git a/lib/generated_plugin_registrant.dart b/lib/generated_plugin_registrant.dart index 642c8ec..bcf8ba5 100644 --- a/lib/generated_plugin_registrant.dart +++ b/lib/generated_plugin_registrant.dart @@ -7,7 +7,6 @@ // ignore_for_file: depend_on_referenced_packages import 'package:audio_session/audio_session_web.dart'; -import 'package:camera_web/camera_web.dart'; import 'package:file_picker/_internal/file_picker_web.dart'; import 'package:firebase_core_web/firebase_core_web.dart'; import 'package:firebase_messaging_web/firebase_messaging_web.dart'; @@ -16,7 +15,6 @@ import 'package:geolocator_web/geolocator_web.dart'; import 'package:google_maps_flutter_web/google_maps_flutter_web.dart'; import 'package:image_picker_for_web/image_picker_for_web.dart'; import 'package:just_audio_web/just_audio_web.dart'; -import 'package:record_web/record_web.dart'; import 'package:shared_preferences_web/shared_preferences_web.dart'; import 'package:url_launcher_web/url_launcher_web.dart'; import 'package:video_player_web/video_player_web.dart'; @@ -26,7 +24,6 @@ import 'package:flutter_web_plugins/flutter_web_plugins.dart'; // ignore: public_member_api_docs void registerPlugins(Registrar registrar) { AudioSessionWeb.registerWith(registrar); - CameraPlugin.registerWith(registrar); FilePickerWeb.registerWith(registrar); FirebaseCoreWeb.registerWith(registrar); FirebaseMessagingWeb.registerWith(registrar); @@ -35,7 +32,6 @@ void registerPlugins(Registrar registrar) { GoogleMapsPlugin.registerWith(registrar); ImagePickerPlugin.registerWith(registrar); JustAudioPlugin.registerWith(registrar); - RecordPluginWeb.registerWith(registrar); SharedPreferencesPlugin.registerWith(registrar); UrlLauncherPlugin.registerWith(registrar); VideoPlayerPlugin.registerWith(registrar); diff --git a/lib/main.dart b/lib/main.dart index 07590f3..a4cdf94 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -6,6 +6,7 @@ import 'package:flutter/services.dart'; import 'package:logger/logger.dart'; import 'package:mohem_flutter_app/app_state/app_state.dart'; import 'package:mohem_flutter_app/classes/consts.dart'; +import 'package:mohem_flutter_app/classes/navigationService.dart'; import 'package:mohem_flutter_app/config/routes.dart'; import 'package:mohem_flutter_app/generated/codegen_loader.g.dart'; import 'package:mohem_flutter_app/models/post_params_model.dart'; @@ -28,6 +29,8 @@ Logger logger = Logger( // output: null, // U ); +late BuildContext callGlobalContext; + class MyHttpOverrides extends HttpOverrides { @override HttpClient createHttpClient(SecurityContext? context) { @@ -45,6 +48,7 @@ Future main() async { ]); await EasyLocalization.ensureInitialized(); AppState().setPostParamsInitConfig(); + setupLocator(); HttpOverrides.global = MyHttpOverrides(); isTablet = MediaQueryData.fromWindow(WidgetsBinding.instance.window).size.shortestSide >= ApiConsts.tabletMinLength; @@ -70,9 +74,9 @@ Future main() async { ChangeNotifierProvider( create: (_) => MarathonProvider(), ), - // ChangeNotifierProvider( - // create: (_) => ChatCallProvider(), - // ), + ChangeNotifierProvider( + create: (_) => ChatCallProvider(), + ), ], child: const MyApp(), ), @@ -91,6 +95,7 @@ class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { + callGlobalContext = context; return Sizer( builder: ( BuildContext context, @@ -122,6 +127,7 @@ class MyApp extends StatelessWidget { locale: context.locale, initialRoute: AppRoutes.initialRoute, routes: AppRoutes.routes, + ); }, ); diff --git a/lib/models/chat/call.dart b/lib/models/chat/call.dart index ce58ae3..0f0e5a6 100644 --- a/lib/models/chat/call.dart +++ b/lib/models/chat/call.dart @@ -7,19 +7,31 @@ import 'dart:convert'; class CallDataModel { CallDataModel({ this.callerId, - this.callerDetails, + this.callerName, + this.callerEmail, + this.callerTitle, + this.callerPhone, this.receiverId, - this.receiverDetails, + this.receiverName, + this.receiverEmail, + this.receiverTitle, + this.receiverPhone, this.title, - this.calltype, + this.callType, }); - String? callerId; - CallerDetails? callerDetails; - String? receiverId; - ReceiverDetails? receiverDetails; - dynamic title; - String? calltype; + int? callerId; + String? callerName; + String? callerEmail; + String? callerTitle; + dynamic callerPhone; + int? receiverId; + String? receiverName; + String? receiverEmail; + dynamic receiverTitle; + dynamic receiverPhone; + String? title; + String? callType; factory CallDataModel.fromRawJson(String str) => CallDataModel.fromJson(json.decode(str)); @@ -27,171 +39,92 @@ class CallDataModel { factory CallDataModel.fromJson(Map json) => CallDataModel( callerId: json["callerID"], - callerDetails: json["callerDetails"] == null ? null : CallerDetails.fromJson(json["callerDetails"]), + callerName: json["callerName"], + callerEmail: json["callerEmail"], + callerTitle: json["callerTitle"], + callerPhone: json["callerPhone"], receiverId: json["receiverID"], - receiverDetails: json["receiverDetails"] == null ? null : ReceiverDetails.fromJson(json["receiverDetails"]), + receiverName: json["receiverName"], + receiverEmail: json["receiverEmail"], + receiverTitle: json["receiverTitle"], + receiverPhone: json["receiverPhone"], title: json["title"], - calltype: json["calltype"], + callType: json["callType"], ); Map toJson() => { "callerID": callerId, - "callerDetails": callerDetails?.toJson(), + "callerName": callerName, + "callerEmail": callerEmail, + "callerTitle": callerTitle, + "callerPhone": callerPhone, "receiverID": receiverId, - "receiverDetails": receiverDetails?.toJson(), + "receiverName": receiverName, + "receiverEmail": receiverEmail, + "receiverTitle": receiverTitle, + "receiverPhone": receiverPhone, "title": title, - "calltype": calltype, + "callType": callType, }; } -class CallerDetails { - CallerDetails({ - this.response, - this.errorResponses, - }); - Response? response; - dynamic errorResponses; - factory CallerDetails.fromRawJson(String str) => CallerDetails.fromJson(json.decode(str)); - String toRawJson() => json.encode(toJson()); - factory CallerDetails.fromJson(Map json) => CallerDetails( - response: json["response"] == null ? null : Response.fromJson(json["response"]), - errorResponses: json["errorResponses"], - ); +// To parse this JSON data, do +// +// final callSessionPayLoad = callSessionPayLoadFromJson(jsonString); - Map toJson() => { - "response": response?.toJson(), - "errorResponses": errorResponses, - }; -} -class Response { - Response({ - this.id, - this.userName, - this.email, - this.phone, - this.title, - this.token, - this.isDomainUser, - this.isActiveCode, - this.encryptedUserId, - this.encryptedUserName, +class CallSessionPayLoad { + CallSessionPayLoad({ + this.target, + this.caller, + this.sdp, }); - int? id; - String? userName; - String? email; - dynamic phone; - String? title; - String? token; - bool? isDomainUser; - bool? isActiveCode; - String? encryptedUserId; - String? encryptedUserName; + int? target; + int? caller; + Sdp? sdp; - factory Response.fromRawJson(String str) => Response.fromJson(json.decode(str)); + factory CallSessionPayLoad.fromRawJson(String str) => CallSessionPayLoad.fromJson(json.decode(str)); String toRawJson() => json.encode(toJson()); - factory Response.fromJson(Map json) => Response( - id: json["id"], - userName: json["userName"], - email: json["email"], - phone: json["phone"], - title: json["title"], - token: json["token"], - isDomainUser: json["isDomainUser"], - isActiveCode: json["isActiveCode"], - encryptedUserId: json["encryptedUserId"], - encryptedUserName: json["encryptedUserName"], + factory CallSessionPayLoad.fromJson(Map json) => CallSessionPayLoad( + target: json["target"], + caller: json["caller"], + sdp: json["sdp"] == null ? null : Sdp.fromJson(json["sdp"]), ); Map toJson() => { - "id": id, - "userName": userName, - "email": email, - "phone": phone, - "title": title, - "token": token, - "isDomainUser": isDomainUser, - "isActiveCode": isActiveCode, - "encryptedUserId": encryptedUserId, - "encryptedUserName": encryptedUserName, + "target": target, + "caller": caller, + "sdp": sdp?.toJson(), }; } -class ReceiverDetails { - ReceiverDetails({ - this.id, - this.userName, - this.email, - this.phone, - this.title, - this.userStatus, - this.image, - this.unreadMessageCount, - this.userAction, - this.isPin, - this.isFav, - this.isAdmin, - this.rKey, - this.totalCount, +class Sdp { + Sdp({ + this.type, + this.sdp, }); - int? id; - String? userName; - String? email; - dynamic phone; - dynamic title; - int? userStatus; - String? image; - int? unreadMessageCount; - dynamic userAction; - bool? isPin; - bool? isFav; - bool? isAdmin; - String? rKey; - int? totalCount; - - factory ReceiverDetails.fromRawJson(String str) => ReceiverDetails.fromJson(json.decode(str)); + String? type; + String? sdp; + + factory Sdp.fromRawJson(String str) => Sdp.fromJson(json.decode(str)); String toRawJson() => json.encode(toJson()); - factory ReceiverDetails.fromJson(Map json) => ReceiverDetails( - id: json["id"], - userName: json["userName"], - email: json["email"], - phone: json["phone"], - title: json["title"], - userStatus: json["userStatus"], - image: json["image"], - unreadMessageCount: json["unreadMessageCount"], - userAction: json["userAction"], - isPin: json["isPin"], - isFav: json["isFav"], - isAdmin: json["isAdmin"], - rKey: json["rKey"], - totalCount: json["totalCount"], + factory Sdp.fromJson(Map json) => Sdp( + type: json["type"], + sdp: json["sdp"], ); Map toJson() => { - "id": id, - "userName": userName, - "email": email, - "phone": phone, - "title": title, - "userStatus": userStatus, - "image": image, - "unreadMessageCount": unreadMessageCount, - "userAction": userAction, - "isPin": isPin, - "isFav": isFav, - "isAdmin": isAdmin, - "rKey": rKey, - "totalCount": totalCount, + "type": type, + "sdp": sdp, }; } diff --git a/lib/models/chat/incoming_call_model.dart b/lib/models/chat/incoming_call_model.dart new file mode 100644 index 0000000..f49144f --- /dev/null +++ b/lib/models/chat/incoming_call_model.dart @@ -0,0 +1,329 @@ +// To parse this JSON data, do +// +// final incomingCallModel = incomingCallModelFromJson(jsonString); + +import 'dart:convert'; + +class IncomingCallModel { + String? actionColor; + String? appName; + Args? args; + String? avatar; + String? backgroundColor; + String? backgroundUrl; + int? duration; + Extra? extra; + String? from; + String? handle; + Args? headers; + String? id; + bool? isAccepted; + bool? isCustomNotification; + bool? isCustomSmallExNotification; + bool? isShowCallback; + bool? isShowLogo; + bool? isShowMissedCallNotification; + String? nameCaller; + String? ringtonePath; + String? textAccept; + String? textCallback; + String? textDecline; + String? textMissedCall; + int? type; + String? uuid; + + IncomingCallModel({ + this.actionColor, + this.appName, + this.args, + this.avatar, + this.backgroundColor, + this.backgroundUrl, + this.duration, + this.extra, + this.from, + this.handle, + this.headers, + this.id, + this.isAccepted, + this.isCustomNotification, + this.isCustomSmallExNotification, + this.isShowCallback, + this.isShowLogo, + this.isShowMissedCallNotification, + this.nameCaller, + this.ringtonePath, + this.textAccept, + this.textCallback, + this.textDecline, + this.textMissedCall, + this.type, + this.uuid, + }); + + factory IncomingCallModel.fromRawJson(String str) => IncomingCallModel.fromJson(json.decode(str)); + + String toRawJson() => json.encode(toJson()); + + factory IncomingCallModel.fromJson(Map json) => IncomingCallModel( + actionColor: json["actionColor"], + appName: json["appName"], + args: json["args"] == null ? null : Args.fromJson(json["args"]), + avatar: json["avatar"], + backgroundColor: json["backgroundColor"], + backgroundUrl: json["backgroundUrl"], + duration: json["duration"] == null ? null : json["duration"].toInt(), + extra: json["extra"] == null ? null : Extra.fromJson(json["extra"]), + from: json["from"], + handle: json["handle"], + headers: json["headers"] == null ? null : Args.fromJson(json["headers"]), + id: json["id"], + isAccepted: json["isAccepted"], + isCustomNotification: json["isCustomNotification"], + isCustomSmallExNotification: json["isCustomSmallExNotification"], + isShowCallback: json["isShowCallback"], + isShowLogo: json["isShowLogo"], + isShowMissedCallNotification: json["isShowMissedCallNotification"], + nameCaller: json["nameCaller"], + ringtonePath: json["ringtonePath"], + textAccept: json["textAccept"], + textCallback: json["textCallback"], + textDecline: json["textDecline"], + textMissedCall: json["textMissedCall"], + type: json["type"] == null ? null : json["type"].toInt(), + uuid: json["uuid"], + ); + + Map toJson() => { + "actionColor": actionColor, + "appName": appName, + "args": args?.toJson(), + "avatar": avatar, + "backgroundColor": backgroundColor, + "backgroundUrl": backgroundUrl, + "duration": duration, + "extra": extra?.toJson(), + "from": from, + "handle": handle, + "headers": headers?.toJson(), + "id": id, + "isAccepted": isAccepted, + "isCustomNotification": isCustomNotification, + "isCustomSmallExNotification": isCustomSmallExNotification, + "isShowCallback": isShowCallback, + "isShowLogo": isShowLogo, + "isShowMissedCallNotification": isShowMissedCallNotification, + "nameCaller": nameCaller, + "ringtonePath": ringtonePath, + "textAccept": textAccept, + "textCallback": textCallback, + "textDecline": textDecline, + "textMissedCall": textMissedCall, + "type": type, + "uuid": uuid, + }; +} + +class Args { + Args(); + + factory Args.fromRawJson(String str) => Args.fromJson(json.decode(str)); + + String toRawJson() => json.encode(toJson()); + + factory Args.fromJson(Map json) => Args(); + + Map toJson() => {}; +} + +class Extra { + LoginDetails? loginDetails; + bool? isIncomingCall; + CallerDetails? callerDetails; + + Extra({ + this.loginDetails, + this.isIncomingCall, + this.callerDetails, + }); + + factory Extra.fromRawJson(String str) => Extra.fromJson(json.decode(str)); + + String toRawJson() => json.encode(toJson()); + + factory Extra.fromJson(Map json) => Extra( + loginDetails: json["loginDetails"] == null ? null : LoginDetails.fromJson(json["loginDetails"]), + isIncomingCall: json["isIncomingCall"], + callerDetails: json["callerDetails"] == null ? null : CallerDetails.fromJson(json["callerDetails"]), + ); + + Map toJson() => { + "loginDetails": loginDetails?.toJson(), + "isIncomingCall": isIncomingCall, + "callerDetails": callerDetails?.toJson(), + }; +} + +class CallerDetails { + int? userChatHistoryId; + String? contant; + FileTypeResponse? fileTypeResponse; + String? currentUserName; + String? targetUserEmail; + String? conversationId; + String? encryptedTargetUserId; + int? targetUserId; + bool? isSeen; + int? userChatHistoryLineId; + bool? isDelivered; + String? targetUserName; + int? currentUserId; + DateTime? createdDate; + String? currentUserEmail; + String? contantNo; + int? chatEventId; + String? encryptedTargetUserName; + int? chatSource; + + CallerDetails({ + this.userChatHistoryId, + this.contant, + this.fileTypeResponse, + this.currentUserName, + this.targetUserEmail, + this.conversationId, + this.encryptedTargetUserId, + this.targetUserId, + this.isSeen, + this.userChatHistoryLineId, + this.isDelivered, + this.targetUserName, + this.currentUserId, + this.createdDate, + this.currentUserEmail, + this.contantNo, + this.chatEventId, + this.encryptedTargetUserName, + this.chatSource, + }); + + factory CallerDetails.fromRawJson(String str) => CallerDetails.fromJson(json.decode(str)); + + String toRawJson() => json.encode(toJson()); + + factory CallerDetails.fromJson(Map json) => CallerDetails( + userChatHistoryId: json["userChatHistoryId"] == null ? null : json["userChatHistoryId"].toInt(), + contant: json["contant"], + fileTypeResponse: json["fileTypeResponse"] == null ? null : FileTypeResponse.fromJson(json["fileTypeResponse"]), + currentUserName: json["currentUserName"], + targetUserEmail: json["targetUserEmail"], + conversationId: json["conversationId"], + encryptedTargetUserId: json["encryptedTargetUserId"], + targetUserId: json["targetUserId"] == null ? null : json["targetUserId"].toInt(), + isSeen: json["isSeen"], + userChatHistoryLineId: json["userChatHistoryLineId"] == null ? null : json["userChatHistoryLineId"].toInt(), + isDelivered: json["isDelivered"], + targetUserName: json["targetUserName"], + currentUserId: json["currentUserId"] == null ? null : json["currentUserId"].toInt(), + createdDate: json["createdDate"] == null ? null : DateTime.parse(json["createdDate"]), + currentUserEmail: json["currentUserEmail"], + contantNo: json["contantNo"], + chatEventId: json["chatEventId"] == null ? null : json["chatEventId"].toInt(), + encryptedTargetUserName: json["encryptedTargetUserName"], + chatSource: json["chatSource"] == null ? null : json["chatSource"].toInt(), + ); + + Map toJson() => { + "userChatHistoryId": userChatHistoryId, + "contant": contant, + "fileTypeResponse": fileTypeResponse?.toJson(), + "currentUserName": currentUserName, + "targetUserEmail": targetUserEmail, + "conversationId": conversationId, + "encryptedTargetUserId": encryptedTargetUserId, + "targetUserId": targetUserId, + "isSeen": isSeen, + "userChatHistoryLineId": userChatHistoryLineId, + "isDelivered": isDelivered, + "targetUserName": targetUserName, + "currentUserId": currentUserId, + "createdDate": createdDate?.toIso8601String(), + "currentUserEmail": currentUserEmail, + "contantNo": contantNo, + "chatEventId": chatEventId, + "encryptedTargetUserName": encryptedTargetUserName, + "chatSource": chatSource, + }; +} + +class FileTypeResponse { + int? fileTypeId; + + FileTypeResponse({ + this.fileTypeId, + }); + + factory FileTypeResponse.fromRawJson(String str) => FileTypeResponse.fromJson(json.decode(str)); + + String toRawJson() => json.encode(toJson()); + + factory FileTypeResponse.fromJson(Map json) => FileTypeResponse( + fileTypeId: json["fileTypeId"].toInt(), + ); + + Map toJson() => { + "fileTypeId": fileTypeId, + }; +} + +class LoginDetails { + bool? isActiveCode; + int? id; + String? encryptedUserName; + String? userName; + String? title; + String? encryptedUserId; + String? email; + bool? isDomainUser; + String? token; + + LoginDetails({ + this.isActiveCode, + this.id, + this.encryptedUserName, + this.userName, + this.title, + this.encryptedUserId, + this.email, + this.isDomainUser, + this.token, + }); + + factory LoginDetails.fromRawJson(String str) => LoginDetails.fromJson(json.decode(str)); + + String toRawJson() => json.encode(toJson()); + + factory LoginDetails.fromJson(Map json) => LoginDetails( + isActiveCode: json["isActiveCode"], + id: json["id"] == null ? null : json["id"].toInt(), + encryptedUserName: json["encryptedUserName"], + userName: json["userName"], + title: json["title"], + encryptedUserId: json["encryptedUserId"], + email: json["email"], + isDomainUser: json["isDomainUser"], + token: json["token"], + ); + + Map toJson() => { + "isActiveCode": isActiveCode, + "id": id, + "encryptedUserName": encryptedUserName, + "userName": userName, + "title": title, + "encryptedUserId": encryptedUserId, + "email": email, + "isDomainUser": isDomainUser, + "token": token, + }; +} diff --git a/lib/models/chat/webrtc_payloads.dart b/lib/models/chat/webrtc_payloads.dart new file mode 100644 index 0000000..1a3463f --- /dev/null +++ b/lib/models/chat/webrtc_payloads.dart @@ -0,0 +1,61 @@ +// To parse this JSON data, do +// +// final remoteIceCandidatePayLoad = remoteIceCandidatePayLoadFromJson(jsonString); + +import 'dart:convert'; + +class RemoteIceCandidatePayLoad { + RemoteIceCandidatePayLoad({ + this.target, + this.candidate, + }); + + int? target; + Candidate? candidate; + + factory RemoteIceCandidatePayLoad.fromRawJson(String str) => RemoteIceCandidatePayLoad.fromJson(json.decode(str)); + + String toRawJson() => json.encode(toJson()); + + factory RemoteIceCandidatePayLoad.fromJson(Map json) => RemoteIceCandidatePayLoad( + target: json["target"], + candidate: json["candidate"] == null ? null : Candidate.fromJson(json["candidate"]), + ); + + Map toJson() => { + "target": target, + "candidate": candidate?.toJson(), + }; +} + +class Candidate { + Candidate({ + this.candidate, + this.sdpMid, + this.sdpMLineIndex, + this.usernameFragment, + }); + + String? candidate; + String? sdpMid; + int? sdpMLineIndex; + String? usernameFragment; + + factory Candidate.fromRawJson(String str) => Candidate.fromJson(json.decode(str)); + + String toRawJson() => json.encode(toJson()); + + factory Candidate.fromJson(Map json) => Candidate( + candidate: json["candidate"], + sdpMid: json["sdpMid"], + sdpMLineIndex: json["sdpMLineIndex"], + usernameFragment: json["usernameFragment"], + ); + + Map toJson() => { + "candidate": candidate, + "sdpMid": sdpMid, + "sdpMLineIndex": sdpMLineIndex, + "usernameFragment": usernameFragment, + }; +} diff --git a/lib/provider/chat_call_provider.dart b/lib/provider/chat_call_provider.dart index 45205df..3660668 100644 --- a/lib/provider/chat_call_provider.dart +++ b/lib/provider/chat_call_provider.dart @@ -1,52 +1,87 @@ import 'dart:convert'; -import 'dart:ui'; - -import 'package:flutter/cupertino.dart'; +import 'dart:io'; import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_callkit_incoming/flutter_callkit_incoming.dart'; import 'package:flutter_webrtc/flutter_webrtc.dart'; +import 'package:just_audio/just_audio.dart'; +import 'package:mohem_flutter_app/app_state/app_state.dart'; +import 'package:mohem_flutter_app/classes/utils.dart'; +import 'package:mohem_flutter_app/config/routes.dart'; +import 'package:mohem_flutter_app/main.dart'; +import 'package:mohem_flutter_app/models/chat/call.dart'; +import 'package:mohem_flutter_app/models/chat/get_single_user_chat_list_model.dart'; +import 'package:mohem_flutter_app/models/chat/webrtc_payloads.dart'; +import 'package:mohem_flutter_app/provider/chat_provider_model.dart'; +import 'package:mohem_flutter_app/ui/chat/call/chat_incoming_call_screen.dart'; import 'package:mohem_flutter_app/ui/landing/dashboard_screen.dart'; +import 'package:signalr_netcore/hub_connection.dart'; class ChatCallProvider with ChangeNotifier, DiagnosticableTreeMixin { ///////////////////// Web RTC Video Calling ////////////////////// // Video Call - late RTCPeerConnection _peerConnection; - RTCVideoRenderer _localVideoRenderer = RTCVideoRenderer(); - final RTCVideoRenderer _remoteRenderer = RTCVideoRenderer(); + late RTCPeerConnection _pc; + late ChatProviderModel chatProvModel; + RTCVideoRenderer? localVideoRenderer; + RTCVideoRenderer? remoteRenderer; + final AudioPlayer player = AudioPlayer(); MediaStream? _localStream; - MediaStream? _remoteStream; + late CallDataModel outGoingCallData; + bool isMicOff = false; + bool isLoudSpeaker = false; + bool isCamOff = false; + bool isCallEnded = false; + bool isVideoCall = false; + bool isAudioCall = false; + bool isCallStarted = false; + bool isFrontCamera = true; + late SingleUserChatModel incomingCallData; + + /// WebRTC Connection Variables + bool isIncomingCallLoader = true; + bool isIncomingCall = false; + bool isOutGoingCall = false; - void initCallListeners() { + late BuildContext providerContext; + + void initCallListeners({required BuildContext context}) { + providerContext = context; + if (kDebugMode) { + print("=================== Call Listeners Registered ======================="); + } chatHubConnection.on("OnCallAcceptedAsync", onCallAcceptedAsync); chatHubConnection.on("OnIceCandidateAsync", onIceCandidateAsync); chatHubConnection.on("OnOfferAsync", onOfferAsync); chatHubConnection.on("OnAnswerOffer", onAnswerOffer); chatHubConnection.on("OnHangUpAsync", onHangUpAsync); chatHubConnection.on("OnCallDeclinedAsync", onCallDeclinedAsync); + // chatHubConnection.on("OnIncomingCallAsync", OnIncomingCallAsync); } //Video Constraints - var videoConstraints = { + Map videoConstraints = { "video": { "mandatory": { - "width": {"min": 320}, - "height": {"min": 180} + "width": {"min": 1280}, + "height": {"min": 720} }, "optional": [ { "width": {"max": 1280} }, - {"frameRate": 25}, + {"frameRate": 60}, {"facingMode": "user"} ] }, - "frameRate": 25, - "width": 420, //420,//640,//1280, - "height": 240 //240//480//720 + "frameRate": 60, + "width": 1280, //420,//640,//1280, + "height": 720, //240//480//720 + "audio": true, }; // Audio Constraints - var audioConstraints = { + Map audioConstraints = { "sampleRate": 8000, "sampleSize": 16, "channelCount": 2, @@ -54,128 +89,292 @@ class ChatCallProvider with ChangeNotifier, DiagnosticableTreeMixin { "audio": true, }; - Future _createPeerConnection() async { - // {"url": "stun:stun.l.google.com:19302"}, - Map configuration = { - "iceServers": [ - {"urls": 'stun:15.185.116.59:3478'}, - {"urls": "turn:15.185.116.59:3479", "username": "admin", "credential": "admin"} - ] - }; + Future init() async { + _pc = await creatOfferWithCon(); + Future.delayed(const Duration(seconds: 2), () { + connectIncomingCall(); + }); + } - Map offerSdpConstraints = { - "mandatory": { - "OfferToReceiveAudio": true, - "OfferToReceiveVideo": true, - }, - "optional": [], - }; + ///////////////////////////////////////////////OutGoing Call//////////////////////////////////////////////////// - RTCPeerConnection pc = await createPeerConnection(configuration, offerSdpConstraints); - // if (pc != null) print(pc); - //pc.addStream(widget.localStream); - - pc.onIceCandidate = (e) { - if (e.candidate != null) { - print(json.encode({ - 'candidate': e.candidate.toString(), - 'sdpMid': e.sdpMid.toString(), - 'sdpMlineIndex': e.sdpMLineIndex, - })); - } - }; - pc.onIceConnectionState = (e) { - print(e); - }; - pc.onAddStream = (stream) { - print('addStream: ' + stream.id); - _remoteRenderer.srcObject = stream; - }; - return pc; + Future initLocalCamera({required ChatProviderModel chatProvmodel, required callData, required BuildContext context, bool isIncomingCall = false}) async { + isCallEnded = false; + chatProvModel = chatProvmodel; + outGoingCallData = callData; + await initStreams(); + await startCall(callType: isVideoCall ? "Video" : "Audio", context: context); + _pc = await creatOfferWithCon(); + notifyListeners(); } - void init() { - initRenderers(); - _createPeerConnection().then((pc) { - _peerConnection = pc; - // _setRemoteDescription(widget.info); - }); + Future startCall({required String callType, required BuildContext context}) async { + chatProvModel.isTextMsg = true; + chatProvModel.isAttachmentMsg = false; + chatProvModel.isVoiceMsg = false; + chatProvModel.isReplyMsg = false; + chatProvModel.isCall = true; + chatProvModel.message.text = "Start $callType call ${outGoingCallData.receiverName.toString().replaceAll(".", " ")}"; + chatProvModel.sendChatMessage( + context, + targetUserId: outGoingCallData.receiverId!, + userStatus: 1, + userEmail: outGoingCallData.receiverEmail!, + targetUserName: outGoingCallData.receiverName!, + ); + await invoke( + invokeMethod: "CallUserAsync", + currentUserID: outGoingCallData.callerId!, + targetUserID: outGoingCallData.receiverId!, + ); + await invoke(invokeMethod: "UpdateUserStatusAsync", currentUserID: outGoingCallData.callerId!, targetUserID: outGoingCallData.receiverId!, userStatus: 4); } - void initRenderers() { - _localVideoRenderer.initialize(); - _remoteRenderer.initialize(); - initLocalCamera(); + // OutGoing Listeners + void onCallAcceptedAsync(List? params) async { + dynamic items = params!.toList(); + RTCSessionDescription description = await _createOffer(); + await _pc.setLocalDescription(description); + dynamic payload = {"target": items[0]["id"], "caller": outGoingCallData.callerId, "sdp": description.toMap()}; + invoke(invokeMethod: "OfferAsync", currentUserID: outGoingCallData.callerId!, targetUserID: items[0]["id"], data: jsonEncode(payload)); } - void initLocalCamera() async { - _localStream = await navigator.mediaDevices.getUserMedia({'video': true, 'audio': true}); - _localVideoRenderer.srcObject = _localStream; - // _localVideoRenderer.srcObject = await navigator.mediaDevices - // .getUserMedia({'video': true, 'audio': true}); - print('this source Object'); - print('this suarce ${_localVideoRenderer.srcObject != null}'); - notifyListeners(); + Future onIceCandidateAsync(List? params) async { + dynamic items = params!.toList(); + if (isIncomingCall) { + RemoteIceCandidatePayLoad data = RemoteIceCandidatePayLoad.fromJson(jsonDecode(items.first.toString())); + if (_pc != null) { + await _pc.addCandidate(RTCIceCandidate(data.candidate!.candidate, data.candidate!.sdpMid, data.candidate!.sdpMLineIndex)); + } + } else { + if (kDebugMode) { + logger.i("res: " + items.toString()); + } + RemoteIceCandidatePayLoad data = RemoteIceCandidatePayLoad.fromJson(jsonDecode(items.first.toString())); + if (_pc != null) { + await _pc.addCandidate(RTCIceCandidate(data.candidate!.candidate, data.candidate!.sdpMid, data.candidate!.sdpMLineIndex)); + if (!isCallStarted) { + isCallStarted = true; + notifyListeners(); + if (isCallStarted) { + isIncomingCallLoader = false; + isOutGoingCall = true; + Navigator.push( + providerContext, + MaterialPageRoute( + builder: (BuildContext context) => StartCallPage(), + allowSnapshotting: false, + )).then((value) { + Navigator.of(providerContext).pop(); + }); + } + } + } + notifyListeners(); + } } - void startCall({required String callType}) {} - - void endCall() {} - - void checkCall(Map message) { - switch (message["callStatus"]) { - case 'connected': - {} - break; - case 'offer': - {} - break; - case 'accept': - {} - break; - case 'candidate': - {} - break; - case 'bye': - {} - break; - case 'leave': - {} - break; + Future onOfferAsync(List? params) async { + dynamic items = params!.toList(); + var data = jsonDecode(items.toString()); + if (isIncomingCall) { + _pc.setRemoteDescription(RTCSessionDescription(data[0]["sdp"]["sdp"], data[0]["sdp"]["type"])); + RTCSessionDescription description = await _createAnswer(); + await _pc.setLocalDescription(description); + dynamic payload = {"target": data[0]["caller"], "caller": AppState().chatDetails!.response!.id, "sdp": description.toMap()}; + invoke(invokeMethod: "AnswerOfferAsync", currentUserID: AppState().chatDetails!.response!.id!, targetUserID: incomingCallData.targetUserId!, data: jsonEncode(payload)); } + // else { + // RTCSessionDescription description = await _createAnswer(); + // await _pc.setLocalDescription(description); + // var payload = {"target": items[0]["id"], "caller": outGoingCallData.callerId, "sdp": description.toMap()}; + // invoke(invokeMethod: "AnswerOffer", currentUserID: outGoingCallData.callerId!, targetUserID: items[0]["id"], data: jsonEncode(payload)); + // } + notifyListeners(); } - //// Listeners Methods //// + //////////////////////////// OutGoing Call End /////////////////////////////////////// - void onCallAcceptedAsync(List? params) {} + Future endCall({required bool isUserOnline}) async { + if (isIncomingCall) { + logger.i("-----------------------Endeddddd By Me---------------------------"); + if (chatHubConnection.state == HubConnectionState.Connected) { + await invoke(invokeMethod: "HangUpAsync", currentUserID: AppState().chatDetails!.response!.id!, targetUserID: incomingCallData.targetUserId!, userStatus: 0); + await invoke(invokeMethod: "UpdateUserStatusAsync", currentUserID: AppState().chatDetails!.response!.id!, targetUserID: incomingCallData.targetUserId!, userStatus: 1); + } + isCallStarted = false; + isVideoCall = false; + isCamOff = false; + isMicOff = false; + isLoudSpeaker = false; + isIncomingCall = false; + isOutGoingCall = false; + if (_pc.connectionState == RTCPeerConnectionState.RTCPeerConnectionStateConnected) { + print("------------------ PC Stopped ----------------------------"); + _pc.close(); + _pc.dispose(); + } + remoteRenderer!.dispose(); + localVideoRenderer!.dispose(); + localVideoRenderer = null; + remoteRenderer = null; + if (_localStream != null) { + _localStream!.dispose(); + _localStream = null; + } + if (chatHubConnection != null && !isUserOnline) { + chatHubConnection.stop(); + } + await FlutterCallkitIncoming.endAllCalls(); + return true; + } else { + if (isOutGoingCall) { + print("Endded Outgoing"); + await invoke(invokeMethod: "HangUpAsync", currentUserID: outGoingCallData.callerId!, targetUserID: outGoingCallData.receiverId!, userStatus: 1); + await invoke(invokeMethod: "UpdateUserStatusAsync", currentUserID: outGoingCallData.callerId!, targetUserID: outGoingCallData.receiverId!, userStatus: 1); + } else if (isIncomingCall) { + await invoke(invokeMethod: "UpdateUserStatusAsync", currentUserID: AppState().chatDetails!.response!.id!, targetUserID: incomingCallData.targetUserId!, userStatus: 1); + } - void onIceCandidateAsync(List? params) {} + isCallStarted = false; + isVideoCall = false; + isCamOff = false; + isMicOff = false; + isLoudSpeaker = false; - void onOfferAsync(List? params) {} + if (_pc.connectionState == RTCPeerConnectionState.RTCPeerConnectionStateConnected) { + _pc.close(); + _pc.dispose(); + } + remoteRenderer!.dispose(); + localVideoRenderer!.dispose(); + localVideoRenderer = null; + remoteRenderer = null; + if (_localStream != null) { + _localStream!.dispose(); + _localStream = null; + } + isOutGoingCall = false; + isIncomingCall = false; + // await initStreams().whenComplete(() => notifyListeners()); + return true; + } + } + + // Incoming Listeners + + void onAnswerOffer(List? payload) async { + // if (isIncomingCall) { + // // print("--------------------- On Answer Offer Async ---------------------------------------"); + // //await invoke(invokeMethod: "InvokeMobile", currentUserID: AppState().getchatUserDetails!.response!.id!, targetUserID: incomingCallData.targetUserId!, debugData: {"On Answer Offer Async"}); + // } else { + var items = payload!.toList(); + if (kDebugMode) { + logger.i("res: " + items.toString()); + } + CallSessionPayLoad data = CallSessionPayLoad.fromJson(jsonDecode(items.first.toString())); + RTCSessionDescription description = RTCSessionDescription(data.sdp!.sdp, 'answer'); + _pc.setRemoteDescription(description); + // } + } - void onAnswerOffer(List? params) {} + void onHangUpAsync(List? params) { + print("--------------------- onHangUp ---------------------------------------"); + isOutGoingCall = false; + endCall(isUserOnline: false).then((bool value) { + Navigator.of(AppRoutes.navigatorKey.currentContext!).pop(); + isCallEnded = true; + }); + } - void onHangUpAsync(List? params) {} + // Future OnIncomingCallAsync(List? params) async { + // print("--------------------- On Incoming Call ---------------------------------------"); + // dynamic items = params!.toList(); + // logger.d(items); + // // Map json = { + // // "callerID": items[0]["id"], + // // "callerName": items[0]["userName"], + // // "callerEmail": items[0]["email"], + // // "callerTitle": items[0]["title"], + // // "callerPhone": null, + // // "receiverID": AppState().chatDetails!.response!.id, + // // "receiverName": AppState().chatDetails!.response!.userName, + // // "receiverEmail": AppState().chatDetails!.response!.email, + // // "receiverTitle": AppState().chatDetails!.response!.title, + // // "receiverPhone": AppState().chatDetails!.response!.phone, + // // "title": AppState().chatDetails!.response!.userName!.replaceAll(".", " "), + // // "callType": items[1] ? "Video" : "Audio", + // // }; + // // CallDataModel callData = CallDataModel.fromJson(json); + // // ChatVoipCall().showCallkitIncoming(uuid: const Uuid().v4(), isOnline: true, incomingCallData: callData); + // // + // // if (!isOnIncomingCallPage) { + // // Map json = { + // // "callerID": items[0]["id"], + // // "callerName": items[0]["userName"], + // // "callerEmail": items[0]["email"], + // // "callerTitle": items[0]["title"], + // // "callerPhone": null, + // // "receiverID": AppState().chatDetails!.response!.id, + // // "receiverName": AppState().chatDetails!.response!.userName, + // // "receiverEmail": AppState().chatDetails!.response!.email, + // // "receiverTitle": AppState().chatDetails!.response!.title, + // // "receiverPhone": AppState().chatDetails!.response!.phone, + // // "title": AppState().chatDetails!.response!.userName!.replaceAll(".", " "), + // // "callType": items[1] ? "Video" : "Audio", + // // }; + // // CallDataModel callData = CallDataModel.fromJson(json); + // // await Navigator.push( + // // providerContext, + // // MaterialPageRoute( + // // builder: (BuildContext context) => IncomingCall( + // // isVideoCall: items[1] ? true : false, + // // outGoingCallData: callData, + // // ), + // // ), + // // ); + // // isOnIncomingCallPage = true; + // // } + // } - void onCallDeclinedAsync(List? params) {} + void onCallDeclinedAsync(List? params) { + print("================= On Declained ========================"); + // endCall().then((bool value) { + // if (value) { + // isCallEnded = true; + // notifyListeners(); + // } + // }); + } //// Invoke Methods - Future invoke({required String invokeMethod, required String currentUserID, required String targetUserID, bool isVideoCall = false, var data}) async { + Future invoke({required String invokeMethod, required int currentUserID, required int targetUserID, var data, int userStatus = 1, var debugData}) async { List args = []; - if (invokeMethod == "answerCallAsync") { - args = [currentUserID, targetUserID]; - } else if (invokeMethod == "CallUserAsync") { + // Utils.showToast(currentUserID.toString() + " -- " + targetUserID.toString() + " -- " + isVideoCall.toString()); + if (invokeMethod == "CallUserAsync") { args = [currentUserID, targetUserID, isVideoCall]; + } else if (invokeMethod == "answerCallAsync") { + args = [currentUserID, targetUserID]; } else if (invokeMethod == "IceCandidateAsync") { args = [targetUserID, data]; } else if (invokeMethod == "OfferAsync") { args = [targetUserID, data]; } else if (invokeMethod == "AnswerOfferAsync") { args = [targetUserID, data]; - //json In Data + // json In Data + } else if (invokeMethod == "UpdateUserStatusAsync") { + args = [currentUserID, userStatus]; + } else if (invokeMethod == "HangUpAsync") { + args = [currentUserID, targetUserID]; + } else if (invokeMethod == "InvokeMobile") { + args = [debugData]; + } + try { + await chatHubConnection.invoke("$invokeMethod", args: args); + } catch (e) { + logger.w(e); } - await chatHubConnection.invoke(invokeMethod, args: args); } void stopListeners() async { @@ -184,4 +383,203 @@ class ChatCallProvider with ChangeNotifier, DiagnosticableTreeMixin { chatHubConnection.off('OnIceCandidateAsync'); chatHubConnection.off('OnAnswerOffer'); } + + void playRingtone() async { + player.stop(); + await player.setVolume(1.0); + String audioAsset = ""; + if (Platform.isAndroid) { + audioAsset = "assets/audio/ring_60Sec.mp3"; + } else { + audioAsset = "assets/audio/ring_30Sec.caf"; + } + try { + await player.setAsset(audioAsset); + await player.load(); + player.play(); + } catch (e) { + print("Error: $e"); + } + } + + //////////////////// Web RTC Offers & Connections //////////////////////// + + Future creatOfferWithCon() async { + Map configuration = { + "sdpSemantics": "plan-b", + 'iceServers': [ + { + 'urls': 'stun:15.185.116.59:3478', + }, + { + 'urls': 'turn:15.185.116.59:3479', + 'username': 'admin', + 'credential': 'admin', + }, + ] + }; + Map offerSdpConstraints = { + 'mandatory': { + 'OfferToReceiveAudio': true, + 'OfferToReceiveVideo': true, + }, + 'optional': [] + }; + + RTCPeerConnection pc = await createPeerConnection(configuration, offerSdpConstraints); + await pc!.addStream(_localStream!); + pc?.onConnectionState = (RTCPeerConnectionState state) {}; + pc?.onAddStream = (MediaStream stream) { + remoteRenderer!.srcObject = stream; + notifyListeners(); + }; + pc!.onIceCandidate = (RTCIceCandidate e) async { + if (isIncomingCall) { + if (e.candidate != null) { + var payload = {"target": incomingCallData.targetUserId, "candidate": e.toMap()}; + invoke(invokeMethod: "IceCandidateAsync", currentUserID: AppState().chatDetails!.response!.id!, targetUserID: incomingCallData.targetUserId!, data: jsonEncode(payload)); + notifyListeners(); + } + } else { + if (e.candidate != null) { + var payload = {"target": outGoingCallData.callerId, "candidate": e.toMap()}; + invoke(invokeMethod: "IceCandidateAsync", currentUserID: outGoingCallData.callerId!, targetUserID: outGoingCallData.receiverId!, data: jsonEncode(payload)); + } + } + }; + // pc!.onTrack = (RTCTrackEvent event) async { + // + // String streamId = const Uuid().toString(); + // MediaStream remoteStream = await createLocalMediaStream(streamId); + // event.streams[0].getTracks().forEach((MediaStreamTrack element) { + // logger.i("Stream Track: " + element.id.toString()); + // // remoteRenderer.srcObject = element; + // remoteStream.addTrack(element); + // }); + // }; + pc!.onSignalingState = (RTCSignalingState state) { + logger.i("signaling state: " + state.name); + // invoke( + // invokeMethod: "InvokeMobile", + // currentUserID: AppState().getchatUserDetails!.response!.id!, + // targetUserID: incomingCallData.targetUserId!, + // debugData: {"location": "Signaling", "parms": state.name}); + }; + pc!.onIceGatheringState = (RTCIceGatheringState state) { + logger.i("rtc ice gathering state: " + state.name); + }; + pc!.onIceConnectionState = (RTCIceConnectionState state) { + if (RTCIceConnectionState.RTCIceConnectionStateFailed == state || + RTCIceConnectionState.RTCIceConnectionStateDisconnected == state || + RTCIceConnectionState.RTCIceConnectionStateClosed == state) { + logger.i("Ice Connection State:" + state.name); + // endCall().then((value) { + // notifyListeners(); + // }); + } + }; + // pc!.onRenegotiationNeeded = _onRenegotiate; + return pc; + } + + // void _onRenegotiate() async { + // try { + // print('onRenegotiationNeeded start'); + // // makingOffer = true; + // await _pc.setLocalDescription(await _pc.createOffer(videoConstraints)); + // print('onRenegotiationNeeded state after setLocalDescription: ' + _pc.signalingState.toString()); + // // send offer via callManager + // var localDesc = await _pc.getLocalDescription(); + // // callManager.sendCallMessage(MsgType.rtc_offer, RtcOfferAnswer(localDesc.sdp, localDesc.type)); + // print('onRenegotiationNeeded; offer sent'); + // } catch (e) { + // print("onRenegotiationNeeded error: " + e.toString()); + // } finally { + // // makingOffer = false; + // print('onRenegotiationNeeded done'); + // } + // } + + Future _createOffer() async { + RTCSessionDescription description = await _pc!.createOffer(); + // _offer = true; + return description; + } + + Future _createAnswer() async { + RTCSessionDescription description = await _pc!.createAnswer(); + // _offer = false; + return description; + } + + //////////////////// Web RTC End Offers //////////////////// + + //////////////////// CallPage Buttons ////////////////////// + + void micOff() { + isMicOff = !isMicOff; + _localStream!.getAudioTracks().forEach((track) { + track.enabled = !track.enabled; + }); + notifyListeners(); + } + + void camOff() { + isCamOff = !isCamOff; + _localStream!.getVideoTracks().forEach((track) { + track.enabled = !track.enabled; + }); + // if (isCamOff) { + // isVideoCall = false; + // } else { + // isVideoCall = true; + // } + notifyListeners(); + } + + void loudOn() { + isLoudSpeaker = !isLoudSpeaker; + remoteRenderer!.srcObject?.getAudioTracks().forEach((track) { + if (isLoudSpeaker) { + track.enableSpeakerphone(true); + } else { + track.enableSpeakerphone(false); + } + }); + notifyListeners(); + } + + void switchCamera() { + isFrontCamera = !isFrontCamera; + Helper.switchCamera(_localStream!.getVideoTracks()[0]); + notifyListeners(); + } + + ///////////////// Incoming Call /////////////////////////////// + + Future initStreams() async { + localVideoRenderer = RTCVideoRenderer(); + remoteRenderer = RTCVideoRenderer(); + await localVideoRenderer!.initialize(); + _localStream ??= await navigator.mediaDevices.getUserMedia(isVideoCall ? videoConstraints : audioConstraints); + localVideoRenderer!.srcObject = _localStream; + await remoteRenderer!.initialize(); + } + + Future startIncomingCallViaKit({bool isVCall = true, required var inCallData}) async { + Utils.saveStringFromPrefs("isIncomingCall", "false"); + isVideoCall = isVCall; + await initStreams(); + isIncomingCall = true; + incomingCallData = SingleUserChatModel.fromJson(inCallData); + loudOn(); + } + + void connectIncomingCall() { + invoke(invokeMethod: "answerCallAsync", currentUserID: AppState().getchatUserDetails!.response!.id!, targetUserID: incomingCallData.targetUserId!); + isIncomingCallLoader = false; + isIncomingCall = true; + isVideoCall = true; + notifyListeners(); + } } diff --git a/lib/provider/chat_provider_model.dart b/lib/provider/chat_provider_model.dart index d374114..bde5c42 100644 --- a/lib/provider/chat_provider_model.dart +++ b/lib/provider/chat_provider_model.dart @@ -24,12 +24,14 @@ import 'package:mohem_flutter_app/models/chat/get_single_user_chat_list_model.da import 'package:mohem_flutter_app/models/chat/get_user_login_token_model.dart' as userLoginToken; import 'package:mohem_flutter_app/models/chat/make_user_favotire_unfavorite_chat_model.dart' as fav; import 'package:mohem_flutter_app/models/my_team/get_employee_subordinates_list.dart'; +import 'package:mohem_flutter_app/provider/chat_call_provider.dart'; import 'package:mohem_flutter_app/ui/chat/chat_detailed_screen.dart'; import 'package:mohem_flutter_app/ui/landing/dashboard_screen.dart'; import 'package:mohem_flutter_app/widgets/image_picker.dart'; import 'package:open_file/open_file.dart'; import 'package:path_provider/path_provider.dart'; import 'package:permission_handler/permission_handler.dart'; +import 'package:provider/provider.dart'; import 'package:signalr_netcore/hub_connection.dart'; import 'package:signalr_netcore/signalr_client.dart'; import 'package:uuid/uuid.dart'; @@ -79,30 +81,50 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { List? chatUsersList = []; int pageNo = 1; - bool disbaleChatForThisUser = false; + bool disableChatForThisUser = false; + bool isUserOnline = false; + bool isCall = false; + + userLoginToken.UserAutoLoginModel userLoginData = userLoginToken.UserAutoLoginModel(); Future getUserAutoLoginToken() async { - userLoginToken.UserAutoLoginModel userLoginResponse = await ChatApiClient().getUserLoginToken(); - if (userLoginResponse.response != null) { - AppState().setchatUserDetails = userLoginResponse; - } else { - AppState().setchatUserDetails = userLoginResponse; - Utils.showToast( - userLoginResponse.errorResponses!.first.fieldName.toString() + " Erorr", - ); - disbaleChatForThisUser = true; + try { + userLoginToken.UserAutoLoginModel userLoginResponse = await ChatApiClient().getUserLoginToken(); + if (userLoginResponse.response != null) { + AppState().setchatUserDetails = userLoginResponse; + Utils.saveStringFromPrefs("userLoginChatDetails", jsonEncode(userLoginResponse.response)); + isUserOnline = true; + } else { + AppState().setchatUserDetails = userLoginResponse; + Utils.saveStringFromPrefs("userLoginChatDetails", "null"); + Utils.showToast( + userLoginResponse.errorResponses!.first.fieldName.toString() + " Erorr", + ); + disableChatForThisUser = true; + isUserOnline = false; + notifyListeners(); + } + } catch (e) { + disableChatForThisUser = true; + isUserOnline = false; + notifyListeners(); } } - Future buildHubConnection() async { - chatHubConnection = await getHubConnection(); + Future buildHubConnection({required BuildContext context, required ChatCallProvider ccProvider}) async { + try { + chatHubConnection = await getHubConnection(); + } catch (e) { + Utils.showToast(e.toString()); + } await chatHubConnection.start(); if (kDebugMode) { logger.i("Hub Conn: Startedddddddd"); } chatHubConnection.on("OnDeliveredChatUserAsync", onMsgReceived); chatHubConnection.on("OnGetChatConversationCount", onNewChatConversion); + ccProvider.initCallListeners(context: context); } Future getHubConnection() async { @@ -354,6 +376,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { Future onMsgReceived(List? parameters) async { List data = [], temp = []; + for (dynamic msg in parameters!) { data = getSingleUserChatModel(jsonEncode(msg)); temp = getSingleUserChatModel(jsonEncode(msg)); @@ -363,7 +386,6 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { data.first.currentUserId = temp.first.targetUserId; data.first.currentUserName = temp.first.targetUserName; data.first.currentUserEmail = temp.first.targetUserEmail; - if (data.first.fileTypeId == 12 || data.first.fileTypeId == 4 || data.first.fileTypeId == 3) { data.first.image = await ChatApiClient().downloadURL(fileName: data.first.contant!, fileTypeDescription: data.first.fileTypeResponse!.fileTypeDescription ?? "image/jpg"); } @@ -429,10 +451,6 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { } void OnSubmitChatAsync(List? parameters) { - print(isChatScreenActive); - print(receiverID); - print(isChatScreenActive); - logger.i(parameters); List data = [], temp = []; for (dynamic msg in parameters!) { data = getSingleUserChatModel(jsonEncode(msg)); @@ -446,7 +464,6 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { } if (isChatScreenActive && data.first.currentUserId == receiverID) { int index = userChatHistory.indexWhere((SingleUserChatModel element) => element.userChatHistoryId == 0); - logger.d(index); userChatHistory[index] = data.first; } @@ -570,7 +587,6 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { msg = voiceFile!.path.split("/").last; } else { msg = message.text; - logger.w(msg); } SingleUserChatModel data = SingleUserChatModel( userChatHistoryId: 0, @@ -632,7 +648,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { return; } sendChatToServer( - chatEventId: 1, + chatEventId: isCall ? 3 : 1, fileTypeId: null, targetUserId: targetUserId, targetUserName: targetUserName, @@ -1014,7 +1030,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { } void disposeData() { - if (!disbaleChatForThisUser) { + if (!disableChatForThisUser) { search.clear(); isChatScreenActive = false; receiverID = 0; @@ -1030,6 +1046,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { favUsersList.clear(); searchedChats?.clear(); pChatHistory?.clear(); + // callP.stopListeners(); chatHubConnection.stop(); AppState().chatDetails = null; } @@ -1457,21 +1474,4 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin { } return Material.TextDirection.ltr; } - - void openChatByNoti(BuildContext context) async { - SingleUserChatModel nUser = SingleUserChatModel(); - Utils.saveStringFromPrefs("isAppOpendByChat", "false"); - if (await Utils.getStringFromPrefs("notificationData") != "null") { - nUser = SingleUserChatModel.fromJson(jsonDecode(await Utils.getStringFromPrefs("notificationData"))); - Utils.saveStringFromPrefs("notificationData", "null"); - Future.delayed(const Duration(seconds: 2)); - for (ChatUser user in searchedChats!) { - if (user.id == nUser.targetUserId) { - Navigator.pushNamed(context, AppRoutes.chatDetailed, arguments: ChatDetailedScreenParams(user, false)); - return; - } - } - } - Utils.saveStringFromPrefs("notificationData", "null"); - } } diff --git a/lib/ui/chat/call/chat_incoming_call_screen.dart b/lib/ui/chat/call/chat_incoming_call_screen.dart index 1b6a5aa..f890696 100644 --- a/lib/ui/chat/call/chat_incoming_call_screen.dart +++ b/lib/ui/chat/call/chat_incoming_call_screen.dart @@ -1,381 +1,597 @@ +import 'dart:convert'; +import 'dart:core'; import 'dart:ui'; - -import 'package:camera/camera.dart'; +import 'package:draggable_widget/draggable_widget.dart'; +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; +import 'package:flutter_callkit_incoming/flutter_callkit_incoming.dart'; +import 'package:flutter_svg/flutter_svg.dart'; +import 'package:flutter_webrtc/flutter_webrtc.dart'; +import 'package:mohem_flutter_app/app_state/app_state.dart'; import 'package:mohem_flutter_app/classes/colors.dart'; -import 'package:mohem_flutter_app/classes/utils.dart'; +import 'package:mohem_flutter_app/extensions/int_extensions.dart'; +import 'package:mohem_flutter_app/main.dart'; import 'package:mohem_flutter_app/models/chat/call.dart'; +import 'package:mohem_flutter_app/models/chat/get_user_login_token_model.dart'; +import 'package:mohem_flutter_app/models/chat/incoming_call_model.dart'; +import 'package:mohem_flutter_app/provider/chat_call_provider.dart'; +import 'package:mohem_flutter_app/provider/chat_provider_model.dart'; +import 'package:provider/provider.dart'; -class IncomingCall extends StatefulWidget { - CallDataModel incomingCallData; - bool? isVideoCall; - - IncomingCall({Key? key, required this.incomingCallData, this.isVideoCall}) : super(key: key); - +class StartCallPage extends StatefulWidget { @override - _IncomingCallState createState() => _IncomingCallState(); + _StartCallPageState createState() => _StartCallPageState(); } -class _IncomingCallState extends State with SingleTickerProviderStateMixin { - AnimationController? _animationController; - CameraController? _controller; - Future? _initializeControllerFuture; - bool isCameraReady = false; +class _StartCallPageState extends State { + DragController dragController = DragController(); + bool isOutGoingCall = false; + bool isIncomingCall = false; + late ChatCallProvider cProv; + late ChatProviderModel provider; @override void initState() { - _animationController = AnimationController( - vsync: this, - duration: const Duration( - milliseconds: 500, - ), - ); - //_runAnimation(); - // connectSignaling(); - WidgetsBinding.instance.addPostFrameCallback( - (_) => _runAnimation(), - ); - super.initState(); } + @override + void dispose() { + super.dispose(); + } + + + @override + void didChangeDependencies() { + // TODO: implement didChangeDependencies + super.didChangeDependencies(); + } + + + void startCall() async { + IncomingCallModel? sessionData; + dynamic calls = await FlutterCallkitIncoming.activeCalls(); + if (calls.isNotEmpty) { + sessionData = IncomingCallModel.fromRawJson(jsonEncode(calls[0])); + isIncomingCall = sessionData.extra!.isIncomingCall!; + } + if (isIncomingCall) { + if (provider.isUserOnline) { + if (kDebugMode) { + print("====== Processing Incoming Call in Online State ========="); + } + await cProv.startIncomingCallViaKit(inCallData: sessionData!.extra!.callerDetails!.toJson()); + cProv.init(); + } else { + if (kDebugMode) { + print("====== Processing Incoming Call ========="); + } + await cProv.startIncomingCallViaKit(inCallData: sessionData!.extra!.callerDetails!.toJson()); + try { + AppState().setchatUserDetails = UserAutoLoginModel(response: Response.fromJson(sessionData.extra!.loginDetails!.toJson()), errorResponses: null); + await provider.buildHubConnection(context: context, ccProvider: cProv).whenComplete(() { + cProv.init(); + }); + } catch (e) { + logger.w(e); + } + if (kDebugMode) { + print('========== END =============='); + } + } + } + // else if (isOutGoingCall) { + // if (kDebugMode) { + // print("====== Processing Outgoing Call ========="); + // } + // + // } + else { + if (kDebugMode) { + print("====== Something Wrong With Call ========="); + } + } + } + + // void connection({required data, required bool isUserOnline}) async { + // if (isUserOnline) { + // cProv.isUserOnline = isUserOnline; + // cProv.startIncomingCallViaKit(inCallData: data); + // } else { + // dynamic callData = await jsonDecode(data); + // AppState().setchatUserDetails = UserAutoLoginModel( + // response: Response.fromJson(callData[0]["loginDetails"]), + // errorResponses: null, + // ); + // Utils.saveStringFromPrefs( + // "userLoginChatDetails", + // UserAutoLoginModel( + // response: Response.fromJson(callData[0]["loginDetails"]), + // errorResponses: null, + // ).toJson().toString()); + // cProv.startIncomingCallViaKit(inCallData: data); + // try { + // await prov.buildHubConnection(context: AppRoutes.navigatorKey.currentContext!, ccProvider: cProv).whenComplete(() { + // cProv.init(); + // }); + // } catch (e) { + // logger.w(e); + // } + // } + // } + @override Widget build(BuildContext context) { + cProv=context.read(); + provider=context.read(); + startCall(); return Scaffold( - body: FutureBuilder( - future: _initializeControllerFuture, - builder: (BuildContext context, AsyncSnapshot snapshot) { - if (snapshot.connectionState == ConnectionState.done) { - return Stack( - alignment: FractionalOffset.center, - children: [ - if (widget.isVideoCall!) - Positioned.fill( - child: AspectRatio( - aspectRatio: _controller!.value.aspectRatio, - child: CameraPreview( - _controller!, - ), - ), - ), - Positioned.fill( - child: ClipRect( - child: BackdropFilter( - filter: ImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0), - child: Container( - decoration: BoxDecoration( - color: MyColors.grey57Color.withOpacity( - 0.7, - ), - ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisSize: MainAxisSize.max, - children: [ - Container( - margin: const EdgeInsets.all(21.0), - child: Row( - children: [ - Image.asset( - "assets/images/logos/main_mohemm_logo.png", - height: 70, - width: 70, - ), - Container( - margin: const EdgeInsets.only( - left: 10.0, - right: 10.0, + extendBody: true, + body: Consumer2( + builder: (BuildContext context, ChatCallProvider provider, ChatProviderModel cpm, Widget? child) { + return provider.isIncomingCallLoader + ? const SizedBox( + width: double.infinity, + height: double.infinity, + child: Center(child: CircularProgressIndicator()), + ) + : provider.isIncomingCall + ? SizedBox( + width: double.infinity, + height: double.infinity, + child: Stack( + alignment: FractionalOffset.center, + children: [ + if (!provider.isAudioCall && provider.isVideoCall) + Positioned.fill( + child: RTCVideoView( + provider.remoteRenderer!, + objectFit: RTCVideoViewObjectFit.RTCVideoViewObjectFitCover, + key: const Key('remote'), + ), + ), + if (provider.isVideoCall) + DraggableWidget( + bottomMargin: 20, + topMargin: 40, + intialVisibility: true, + horizontalSpace: 20, + shadowBorderRadius: 50, + initialPosition: AnchoringPosition.topLeft, + dragController: dragController, + normalShadow: const BoxShadow(spreadRadius: 0.0, blurRadius: 0.0), + draggingShadow: const BoxShadow(spreadRadius: 0.0, blurRadius: 0.0), + child: SizedBox( + height: 200, + width: 140, + child: RTCVideoView( + provider.localVideoRenderer!, + mirror: true, + objectFit: RTCVideoViewObjectFit.RTCVideoViewObjectFitCover, + ), + ), + ), + if (!provider.isVideoCall) + Positioned.fill( + child: ClipRect( + child: BackdropFilter( + filter: ImageFilter.blur(sigmaX: 5.0, sigmaY: 5.0), + child: Container( + decoration: BoxDecoration( + color: MyColors.grey57Color.withOpacity( + 0.3, + ), ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - mainAxisAlignment: MainAxisAlignment.spaceAround, - children: const [ - - // todo @aamir, need to use extension mehtods - Text( - "Aamir Saleem Ahmad", - style: TextStyle( - fontSize: 21, - fontWeight: FontWeight.bold, - color: MyColors.white, - letterSpacing: -1.26, - height: 23 / 12, - ), - ), - Text( - "Calling...", - style: TextStyle( - fontSize: 16, - fontWeight: FontWeight.w600, - color: Color( - 0xffC6C6C6, + mainAxisSize: MainAxisSize.max, + children: [ + 40.height, + Row( + crossAxisAlignment: CrossAxisAlignment.center, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Container( + margin: const EdgeInsets.all(21.0), + child: Container( + margin: const EdgeInsets.only( + left: 10.0, + right: 10.0, + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.center, + mainAxisSize: MainAxisSize.min, + mainAxisAlignment: MainAxisAlignment.spaceAround, + children: [ + SvgPicture.asset( + "assets/images/user.svg", + height: 70, + width: 70, + fit: BoxFit.cover, + ), + 10.height, + Text( + provider.outGoingCallData.receiverName!, + style: const TextStyle( + fontSize: 21, + decoration: TextDecoration.none, + fontWeight: FontWeight.bold, + color: MyColors.white, + letterSpacing: -1.26, + height: 23 / 12, + ), + ), + const Text( + "On Call", + style: TextStyle( + fontSize: 16, + decoration: TextDecoration.none, + fontWeight: FontWeight.w600, + color: Color( + 0xffC6C6C6, + ), + letterSpacing: -0.48, + height: 23 / 24, + ), + ), + const SizedBox( + height: 2, + ), + ], + ), + ), ), - letterSpacing: -0.48, - height: 23 / 24, - ), - ), - SizedBox( - height: 2, + ], ), ], ), ), - ], + ), ), ), - // Container( - // margin: const EdgeInsets.all(21.0), - // width: MediaQuery.of(context).size.width, - // decoration: cardRadius(15.0, color: MyColors.black, elevation: null), - // child: Column( - // crossAxisAlignment: CrossAxisAlignment.start, - // mainAxisSize: MainAxisSize.min, - // children: [ - // Container( - // padding: const EdgeInsets.fromLTRB(16.0, 16.0, 16.0, 6.0), - // child: Text( - // "TranslationBase.of(context).appoInfo", - // style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: MyColors.white, letterSpacing: -0.64, height: 23 / 12), - // ), - // ), - // Container( - // padding: const EdgeInsets.only(left: 16.0, right: 16.0), - // child: Text( - // "widget.incomingCallData.appointmentdate + widget.incomingCallData.appointmenttime", - // style: TextStyle(fontSize: 12.0, letterSpacing: -0.48, color: Color(0xff8E8E8E), fontWeight: FontWeight.w600), - // ), - // ), - // Container( - // padding: const EdgeInsets.only(left: 16.0, right: 16.0, bottom: 21.0), - // child: Text( - // "widget.incomingCallData.clinicname", - // style: TextStyle(fontSize: 12.0, letterSpacing: -0.48, color: Color(0xff8E8E8E), fontWeight: FontWeight.w600), - // ), - // ), - // ], - // ), - // ), - const Spacer(), - Container( - margin: const EdgeInsets.only( - bottom: 70.0, - left: 49, - right: 49, + Align( + alignment: Alignment.bottomCenter, + child: Container( + padding: const EdgeInsets.only( + bottom: 20, + left: 40, + right: 40, ), child: Row( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - RotationTransition( - turns: Tween( - begin: 0.0, - end: -.1, - ) - .chain( - CurveTween( - curve: Curves.elasticIn, - ), - ) - .animate( - _animationController!, - ), - child: RawMaterialButton( - onPressed: () { - _submit(); - }, - elevation: 2.0, - fillColor: MyColors.green2DColor, - padding: const EdgeInsets.all( - 15.0, - ), - shape: const CircleBorder(), - child: const Icon( - Icons.call, - color: MyColors.white, - size: 35.0, - ), + // if (provider.isVideoCall) + RawMaterialButton( + constraints: const BoxConstraints(), + onPressed: () { + provider.loudOn(); + }, + elevation: 2.0, + fillColor: provider.isLoudSpeaker ? MyColors.textMixColor : Colors.grey, + padding: const EdgeInsets.all( + 10.0, + ), + shape: const CircleBorder(), + child: const Icon( + Icons.volume_up, + color: MyColors.white, + size: 30.0, + ), + ), + RawMaterialButton( + constraints: const BoxConstraints(), + onPressed: () { + provider.camOff(); + }, + elevation: 2.0, + fillColor: provider.isCamOff ? MyColors.textMixColor : Colors.grey, + padding: const EdgeInsets.all( + 10.0, + ), + shape: const CircleBorder(), + child: Icon( + provider.isCamOff ? Icons.videocam_off : Icons.videocam, + color: MyColors.white, + size: 30.0, + ), + ), + RawMaterialButton( + constraints: const BoxConstraints(), + onPressed: () { + provider.switchCamera(); + }, + elevation: 2.0, + fillColor: provider.isFrontCamera ? Colors.grey : MyColors.textMixColor, + padding: const EdgeInsets.all( + 10.0, + ), + shape: const CircleBorder(), + child: Icon( + provider.isFrontCamera ? Icons.switch_camera_outlined : Icons.switch_camera, + color: MyColors.white, + size: 30.0, ), ), RawMaterialButton( + constraints: const BoxConstraints(), onPressed: () { - backToHome(); + provider.micOff(); + }, + elevation: 2.0, + fillColor: provider.isMicOff ? MyColors.textMixColor : Colors.grey, + padding: const EdgeInsets.all( + 10.0, + ), + shape: const CircleBorder(), + child: Icon( + provider.isMicOff ? Icons.mic_off : Icons.mic, + color: MyColors.white, + size: 30.0, + ), + ), + RawMaterialButton( + constraints: const BoxConstraints(), + onPressed: () { + provider.endCall(isUserOnline: cpm.isUserOnline).then((bool value) { + if (value) { + Navigator.of(context).pop(); + // print("Reintiiiiiiitttiiiiiiii"); + // provider.initStreams(); + } + }); }, elevation: 2.0, fillColor: MyColors.redA3Color, padding: const EdgeInsets.all( - 15.0, + 10.0, ), shape: const CircleBorder(), child: const Icon( Icons.call_end, color: MyColors.white, - size: 35.0, + size: 30.0, ), ), ], ), ), - ], - ), + ), + ], ), - ), - ), - ), - ], - ); - } else { - return const Center( - child: CircularProgressIndicator(), - ); - } + ) + : provider.isOutGoingCall + ? SizedBox( + width: double.infinity, + height: double.infinity, + child: Stack( + alignment: FractionalOffset.center, + children: [ + if (!provider.isAudioCall && provider.isVideoCall) + Positioned.fill( + child: RTCVideoView( + provider.remoteRenderer!, + objectFit: RTCVideoViewObjectFit.RTCVideoViewObjectFitCover, + key: const Key('remote'), + ), + ), + if (provider.isVideoCall) + DraggableWidget( + bottomMargin: 20, + topMargin: 40, + intialVisibility: true, + horizontalSpace: 20, + shadowBorderRadius: 50, + initialPosition: AnchoringPosition.topLeft, + dragController: dragController, + normalShadow: const BoxShadow(spreadRadius: 0.0, blurRadius: 0.0), + draggingShadow: const BoxShadow(spreadRadius: 0.0, blurRadius: 0.0), + child: SizedBox( + height: 200, + width: 140, + child: RTCVideoView( + provider.localVideoRenderer!, + mirror: true, + objectFit: RTCVideoViewObjectFit.RTCVideoViewObjectFitCover, + ), + ), + ), + if (!provider.isVideoCall) + Positioned.fill( + child: ClipRect( + child: BackdropFilter( + filter: ImageFilter.blur(sigmaX: 5.0, sigmaY: 5.0), + child: Container( + decoration: BoxDecoration( + color: MyColors.grey57Color.withOpacity( + 0.3, + ), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.max, + children: [ + 40.height, + Row( + crossAxisAlignment: CrossAxisAlignment.center, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Container( + margin: const EdgeInsets.all(21.0), + child: Container( + margin: const EdgeInsets.only( + left: 10.0, + right: 10.0, + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.center, + mainAxisSize: MainAxisSize.min, + mainAxisAlignment: MainAxisAlignment.spaceAround, + children: [ + SvgPicture.asset( + "assets/images/user.svg", + height: 70, + width: 70, + fit: BoxFit.cover, + ), + 10.height, + Text( + provider.outGoingCallData.receiverName!, + style: const TextStyle( + fontSize: 21, + decoration: TextDecoration.none, + fontWeight: FontWeight.bold, + color: MyColors.white, + letterSpacing: -1.26, + height: 23 / 12, + ), + ), + const Text( + "On Call", + style: TextStyle( + fontSize: 16, + decoration: TextDecoration.none, + fontWeight: FontWeight.w600, + color: Color( + 0xffC6C6C6, + ), + letterSpacing: -0.48, + height: 23 / 24, + ), + ), + const SizedBox( + height: 2, + ), + ], + ), + ), + ), + ], + ), + ], + ), + ), + ), + ), + ), + Align( + alignment: Alignment.bottomCenter, + child: Container( + padding: const EdgeInsets.only( + bottom: 20, + left: 40, + right: 40, + ), + child: Row( + mainAxisSize: MainAxisSize.max, + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + // if (provider.isVideoCall) + RawMaterialButton( + constraints: const BoxConstraints(), + onPressed: () { + provider.loudOn(); + }, + elevation: 2.0, + fillColor: provider.isLoudSpeaker ? MyColors.textMixColor : Colors.grey, + padding: const EdgeInsets.all( + 10.0, + ), + shape: const CircleBorder(), + child: const Icon( + Icons.volume_up, + color: MyColors.white, + size: 30.0, + ), + ), + RawMaterialButton( + constraints: const BoxConstraints(), + onPressed: () { + provider.camOff(); + }, + elevation: 2.0, + fillColor: provider.isCamOff ? MyColors.textMixColor : Colors.grey, + padding: const EdgeInsets.all( + 10.0, + ), + shape: const CircleBorder(), + child: Icon( + provider.isCamOff ? Icons.videocam_off : Icons.videocam, + color: MyColors.white, + size: 30.0, + ), + ), + RawMaterialButton( + constraints: const BoxConstraints(), + onPressed: () { + provider.switchCamera(); + }, + elevation: 2.0, + fillColor: provider.isFrontCamera ? Colors.grey : MyColors.textMixColor, + padding: const EdgeInsets.all( + 10.0, + ), + shape: const CircleBorder(), + child: Icon( + provider.isFrontCamera ? Icons.switch_camera_outlined : Icons.switch_camera, + color: MyColors.white, + size: 30.0, + ), + ), + RawMaterialButton( + constraints: const BoxConstraints(), + onPressed: () { + provider.micOff(); + }, + elevation: 2.0, + fillColor: provider.isMicOff ? MyColors.textMixColor : Colors.grey, + padding: const EdgeInsets.all( + 10.0, + ), + shape: const CircleBorder(), + child: Icon( + provider.isMicOff ? Icons.mic_off : Icons.mic, + color: MyColors.white, + size: 30.0, + ), + ), + RawMaterialButton( + constraints: const BoxConstraints(), + onPressed: () { + provider.endCall(isUserOnline: cpm.isUserOnline).then((bool value) { + if (value) { + Navigator.of(context).pop(); + } + }); + }, + elevation: 2.0, + fillColor: MyColors.redA3Color, + padding: const EdgeInsets.all( + 10.0, + ), + shape: const CircleBorder(), + child: const Icon( + Icons.call_end, + color: MyColors.white, + size: 30.0, + ), + ), + ], + ), + ), + ), + ], + ), + ) + : const SizedBox(); }, ), ); } - - void _runAnimation() async { - List cameras = await availableCameras(); - CameraDescription firstCamera = cameras[1]; - _controller = CameraController( - firstCamera, - ResolutionPreset.medium, - ); - _initializeControllerFuture = _controller!.initialize(); - setState(() {}); - // setAudioFile(); - for (int i = 0; i < 100; i++) { - await _animationController!.forward(); - await _animationController!.reverse(); - } - } - - Future _submit() async { - try { - // backToHome(); - // final roomModel = RoomModel(name: widget.incomingCallData.name, token: widget.incomingCallData.sessionId, identity: widget.incomingCallData.identity); - await _controller?.dispose(); - - // changeCallStatusAPI(4); - - // if (_session != null && _signaling != null) { - // await Navigator.of(context).pushReplacement( - // MaterialPageRoute( - // // fullscreenDialog: true, - // builder: (BuildContext context) { - // // if (widget.incomingCallData.isWebRTC == "true") { - // return StartVideoCall(signaling: _signaling, session: _session); - // - // // else { - // // return OpenTokConnectCallPage(apiKey: OPENTOK_API_KEY, sessionId: widget.incomingCallData.sessionId, token: widget.incomingCallData.token); - // // } - // - // // return VideoCallWebPage(receiverId: widget.incomingCallData.receiverID, callerId: widget.incomingCallData.callerID); // Web WebRTC VideoCall - // - // // return CallHomePage(receiverId: widget.incomingCallData.receiverID, callerId: widget.incomingCallData.callerID); // App WebRTC VideoCall - // }, - // ), - // ); - // } else { - // // Invalid Params/Data - // Utils.showToast("Failed to establish connection with server"); - // } - } catch (err) { - print(err); - // await PlatformExceptionAlertDialog( - // exception: err, - // ).show(context); - - Utils.showToast(err.toString()); - } - } - - // void changeCallStatusAPI(int sessionStatus) { - // LiveCareService service = new LiveCareService(); - // service.endCallAPI(widget.incomingCallData.sessionId, sessionStatus, context).then((res) {}).catchError((err) { - // print(err); - // }); - // } - - void backToHome() async { - // final connected = await signaling.declineCall(widget.incomingCallData.callerID, widget.incomingCallData.receiverID); - // LandingPage.isOpenCallPage = false; - // _signaling - _animationController!.dispose(); - // player.stop(); - // changeCallStatusAPI(3); - // _signaling.bye(_session, callRejected: true); - // _signaling.callDisconnected(_session, callRejected: true); - Navigator.of(context).pop(); - } - - // - // void disposeAudioResources() async { - // await player.dispose(); - // } - // - // void setAudioFile() async { - // player.stop(); - // await player.setVolume(1.0); // full volume - // try { - // await player.setAsset('assets/sounds/ring_60Sec.mp3').then((value) { - // player.setLoopMode(LoopMode.one); // loop ring sound - // player.play(); - // }).catchError((err) { - // print("Error: $err"); - // }); - // } catch (e) { - // print("Error: $e"); - // } - // } - // - // void connectSignaling({@required bool iAmCaller = false}) async { - // print("----------------- + Signaling Connection Started ---------------------------"); - // var caller = widget.incomingCallData.callerID; - // var receiver = widget.incomingCallData.receiverID; - // var host = widget.incomingCallData.server; - // - // var selfRole = iAmCaller ? "Caller" : "Receiver"; - // var selfId = iAmCaller ? caller : receiver; - // var selfUser = SocketUser(id: selfId, name: "$selfRole-$selfId", userAgent: DeviceInfo.userAgent, moreInfo: {}); - // - // var remoteRole = !iAmCaller ? "Caller" : "Receiver"; - // var remoteId = !iAmCaller ? caller : receiver; - // var remoteUser = SocketUser(id: remoteId, name: "$remoteRole-$remoteId", userAgent: DeviceInfo.userAgent, moreInfo: {}); - // - // var sessionId = "$caller-$receiver"; - // _session = SessionOneToOne(id: sessionId, local_user: selfUser, remote_user: remoteUser); - // - // _signaling = Signaling(host, session: _session); - // await _signaling.connect(); - // - // if (_signaling.state == SignalingState.Open) { - // return; - // } - // } - - BoxDecoration cardRadius(double radius, {required Color color, double? elevation}) { - return BoxDecoration( - shape: BoxShape.rectangle, - color: color ?? Colors.white, - borderRadius: BorderRadius.all( - Radius.circular(radius), - ), - boxShadow: [ - BoxShadow( - color: const Color( - 0xff000000, - ).withOpacity( - .05, - ), - //spreadRadius: 5, - blurRadius: elevation ?? 27, - offset: const Offset( - -2, - 3, - ), - ), - ], - ); - } } + +/// if (Platform.isAndroid) { +// SystemNavigator.pop(); +// } else if (Platform.isIOS) { +// exit(0); +// } diff --git a/lib/ui/chat/call/chat_outgoing_call_screen.dart b/lib/ui/chat/call/chat_outgoing_call_screen.dart index 2356e10..6a1a3c7 100644 --- a/lib/ui/chat/call/chat_outgoing_call_screen.dart +++ b/lib/ui/chat/call/chat_outgoing_call_screen.dart @@ -1,16 +1,16 @@ import 'dart:convert'; import 'dart:ui'; -import 'package:camera/camera.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; +import 'package:flutter_webrtc/flutter_webrtc.dart'; import 'package:mohem_flutter_app/classes/colors.dart'; -import 'package:mohem_flutter_app/classes/utils.dart'; import 'package:mohem_flutter_app/extensions/int_extensions.dart'; -import 'package:mohem_flutter_app/main.dart'; import 'package:mohem_flutter_app/models/chat/call.dart'; import 'package:mohem_flutter_app/provider/chat_call_provider.dart'; +import 'package:mohem_flutter_app/provider/chat_provider_model.dart'; +import 'package:mohem_flutter_app/ui/chat/call/chat_incoming_call_screen.dart'; import 'package:provider/provider.dart'; class OutGoingCall extends StatefulWidget { @@ -23,407 +23,175 @@ class OutGoingCall extends StatefulWidget { _OutGoingCallState createState() => _OutGoingCallState(); } -class _OutGoingCallState extends State with SingleTickerProviderStateMixin { - AnimationController? _animationController; - late CameraController controller; - late List _cameras; - Future? _initializeControllerFuture; - bool isCameraReady = false; - bool isMicOff = false; - bool isLoudSpeaker = false; - bool isCamOff = false; - late ChatCallProvider callProviderd; +class _OutGoingCallState extends State { + late ChatCallProvider callProvider; + late ChatProviderModel chatProvider; @override void initState() { - callProviderd = Provider.of(context, listen: false); - _animationController = AnimationController( - vsync: this, - duration: const Duration( - milliseconds: 500, - ), - ); - // _runAnimation(); - // connectSignaling(); - WidgetsBinding.instance.addPostFrameCallback( - (_) => _runAnimation(), - ); - super.initState(); } + void init() { + widget.isVideoCall ? callProvider.isVideoCall = true : callProvider.isVideoCall = false; + callProvider.isOutGoingCall = true; + callProvider.initLocalCamera(chatProvmodel: chatProvider, callData: widget.outGoingCallData, context: context); + } + + @override + void dispose() { + super.dispose(); + } + + @override + void didChangeDependencies() { + // TODO: implement didChangeDependencies + super.didChangeDependencies(); + } + @override Widget build(BuildContext context) { + chatProvider = Provider.of(context, listen: true); + callProvider = Provider.of(context, listen: true); + init(); return Scaffold( - body: FutureBuilder( - future: _initializeControllerFuture, - builder: (BuildContext context, AsyncSnapshot snapshot) { - if (snapshot.connectionState == ConnectionState.done) { - return Stack( - alignment: FractionalOffset.center, - children: [ - if (widget.isVideoCall) - Positioned.fill( - child: CameraPreview( - controller, + body: Consumer(builder: (BuildContext context, ChatCallProvider chatcp, Widget? child) { + if (chatcp.isCallEnded) { + Navigator.pop(context); + } + return Stack( + alignment: FractionalOffset.center, + children: [ + if (chatcp.isVideoCall) + Positioned.fill( + child: RTCVideoView( + chatcp.localVideoRenderer!, + objectFit: RTCVideoViewObjectFit.RTCVideoViewObjectFitCover, + ), + ), + Positioned.fill( + child: ClipRect( + child: BackdropFilter( + filter: ImageFilter.blur(sigmaX: 5.0, sigmaY: 5.0), + child: Container( + decoration: BoxDecoration( + color: MyColors.grey57Color.withOpacity( + 0.3, + ), ), - ), - Positioned.fill( - child: ClipRect( - child: BackdropFilter( - filter: ImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0), - child: Container( - decoration: BoxDecoration( - color: MyColors.grey57Color.withOpacity( - 0.3, - ), - ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisSize: MainAxisSize.max, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.max, + children: [ + 40.height, + Row( + crossAxisAlignment: CrossAxisAlignment.center, + mainAxisAlignment: MainAxisAlignment.center, children: [ - 40.height, - Row( - crossAxisAlignment: CrossAxisAlignment.center, - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Container( - margin: const EdgeInsets.all(21.0), - child: Container( - margin: const EdgeInsets.only( - left: 10.0, - right: 10.0, - ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.center, - mainAxisSize: MainAxisSize.min, - mainAxisAlignment: MainAxisAlignment.spaceAround, - children: [ - SvgPicture.asset( - "assets/images/user.svg", - height: 70, - width: 70, - fit: BoxFit.cover, - ), - 10.height, - Text( - widget.outGoingCallData.title, - style: const TextStyle( - fontSize: 21, - fontWeight: FontWeight.bold, - color: MyColors.white, - letterSpacing: -1.26, - height: 23 / 12, - ), - ), - const Text( - "Ringing...", - style: TextStyle( - fontSize: 16, - fontWeight: FontWeight.w600, - color: Color( - 0xffC6C6C6, - ), - letterSpacing: -0.48, - height: 23 / 24, - ), - ), - const SizedBox( - height: 2, - ), - ], - ), - ), - ), - ], - ), - // Container( - // margin: const EdgeInsets.all(21.0), - // width: MediaQuery.of(context).size.width, - // decoration: cardRadius(15.0, color: MyColors.black, elevation: null), - // child: Column( - // crossAxisAlignment: CrossAxisAlignment.start, - // mainAxisSize: MainAxisSize.min, - // children: [ - // Container( - // padding: const EdgeInsets.fromLTRB(16.0, 16.0, 16.0, 6.0), - // child: Text( - // "TranslationBase.of(context).appoInfo", - // style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: MyColors.white, letterSpacing: -0.64, height: 23 / 12), - // ), - // ), - // Container( - // padding: const EdgeInsets.only(left: 16.0, right: 16.0), - // child: Text( - // "widget.OutGoingCallData.appointmentdate + widget.OutGoingCallData.appointmenttime", - // style: TextStyle(fontSize: 12.0, letterSpacing: -0.48, color: Color(0xff8E8E8E), fontWeight: FontWeight.w600), - // ), - // ), - // Container( - // padding: const EdgeInsets.only(left: 16.0, right: 16.0, bottom: 21.0), - // child: Text( - // "widget.OutGoingCallData.clinicname", - // style: TextStyle(fontSize: 12.0, letterSpacing: -0.48, color: Color(0xff8E8E8E), fontWeight: FontWeight.w600), - // ), - // ), - // ], - // ), - // ), - const Spacer(), Container( - margin: const EdgeInsets.only( - bottom: 70.0, - left: 49, - right: 49, - ), - child: Row( - mainAxisSize: MainAxisSize.max, - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - if (widget.isVideoCall) - RawMaterialButton( - onPressed: () { - _camOff(); - }, - elevation: 2.0, - fillColor: isCamOff ? MyColors.green2DColor : Colors.grey, - padding: const EdgeInsets.all( - 15.0, - ), - shape: const CircleBorder(), - child: Icon( - isCamOff ? Icons.videocam_off : Icons.videocam, - color: MyColors.white, - size: 35.0, - ), - ) - else - RawMaterialButton( - onPressed: () { - _loudOn(); - }, - elevation: 2.0, - fillColor: isLoudSpeaker ? MyColors.green2DColor : Colors.grey, - padding: const EdgeInsets.all( - 15.0, - ), - shape: const CircleBorder(), - child: const Icon( - Icons.volume_up, + margin: const EdgeInsets.all(21.0), + child: Container( + margin: const EdgeInsets.only( + left: 10.0, + right: 10.0, + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.center, + mainAxisSize: MainAxisSize.min, + mainAxisAlignment: MainAxisAlignment.spaceAround, + children: [ + SvgPicture.asset( + "assets/images/user.svg", + height: 70, + width: 70, + fit: BoxFit.cover, + ), + 10.height, + Text( + widget.outGoingCallData.receiverName.toString().replaceAll(".", " "), + style: const TextStyle( + fontSize: 21, + fontWeight: FontWeight.bold, color: MyColors.white, - size: 35.0, + letterSpacing: -1.26, + height: 23 / 12, ), ), - RawMaterialButton( - onPressed: () { - _micOff(); - }, - elevation: 2.0, - fillColor: isMicOff ? MyColors.green2DColor : Colors.grey, - padding: const EdgeInsets.all( - 15.0, - ), - shape: const CircleBorder(), - child: Icon( - isMicOff ? Icons.mic_off : Icons.mic, - color: MyColors.white, - size: 35.0, - ), - ), - RawMaterialButton( - onPressed: () { - backToHome(); - }, - elevation: 2.0, - fillColor: MyColors.redA3Color, - padding: const EdgeInsets.all( - 15.0, + const Text( + "Ringing...", + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.w600, + color: Color( + 0xffC6C6C6, + ), + letterSpacing: -0.48, + height: 23 / 24, + ), ), - shape: const CircleBorder(), - child: const Icon( - Icons.call_end, - color: MyColors.white, - size: 35.0, + const SizedBox( + height: 2, ), - ), - ], + ], + ), ), ), ], ), - ), + const Spacer(), + Container( + margin: const EdgeInsets.only( + bottom: 70.0, + left: 49, + right: 49, + ), + child: Row( + mainAxisSize: MainAxisSize.max, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + RawMaterialButton( + onPressed: () { + chatcp.endCall(isUserOnline: chatProvider.isUserOnline).then((bool value) { + if (value) { + Navigator.of(context).pop(); + // print("Reintiiiiiiitttzzzz"); + // chatcp.initStreams(); + } + }); + }, + elevation: 2.0, + fillColor: MyColors.redA3Color, + padding: const EdgeInsets.all( + 15.0, + ), + shape: const CircleBorder(), + child: const Icon( + Icons.call_end, + color: MyColors.white, + size: 35.0, + ), + ), + ], + ), + ), + ], ), ), ), - ], - ); - } else { - return const Center( - child: CircularProgressIndicator(), - ); - } - }, - ), + ), + ), + ], + ); + }), ); } - void _runAnimation() async { - _cameras = await availableCameras(); - CameraDescription firstCamera = _cameras[1]; - controller = CameraController(firstCamera, ResolutionPreset.medium); - _initializeControllerFuture = controller.initialize(); - setState(() {}); - // setAudioFile(); - for (int i = 0; i < 100; i++) { - await _animationController!.forward(); - await _animationController!.reverse(); - } - } - - void _micOff() { - setState(() { - isMicOff = !isMicOff; - }); - } - - void _camOff() { - setState(() { - isCamOff = !isCamOff; - }); - } - - void _loudOn() { - setState(() { - isLoudSpeaker = !isLoudSpeaker; - }); - } - - Future _submit() async { - try { - // backToHome(); - // final roomModel = RoomModel(name: widget.OutGoingCallData.name, token: widget.OutGoingCallData.sessionId, identity: widget.OutGoingCallData.identity); - await controller?.dispose(); - - // changeCallStatusAPI(4); - - // if (_session != null && _signaling != null) { - // await Navigator.of(context).pushReplacement( - // MaterialPageRoute( - // // fullscreenDialog: true, - // builder: (BuildContext context) { - // // if (widget.OutGoingCallData.isWebRTC == "true") { - // return StartVideoCall(signaling: _signaling, session: _session); - // - // // else { - // // return OpenTokConnectCallPage(apiKey: OPENTOK_API_KEY, sessionId: widget.OutGoingCallData.sessionId, token: widget.OutGoingCallData.token); - // // } - // - // // return VideoCallWebPage(receiverId: widget.OutGoingCallData.receiverID, callerId: widget.OutGoingCallData.callerID); // Web WebRTC VideoCall - // - // // return CallHomePage(receiverId: widget.OutGoingCallData.receiverID, callerId: widget.OutGoingCallData.callerID); // App WebRTC VideoCall - // }, - // ), - // ); - // } else { - // // Invalid Params/Data - // Utils.showToast("Failed to establish connection with server"); - // } - } catch (err) { - print(err); - // await PlatformExceptionAlertDialog( - // exception: err, - // ).show(context); - - Utils.showToast(err.toString()); - } - } - - // void changeCallStatusAPI(int sessionStatus) { - // LiveCareService service = new LiveCareService(); - // service.endCallAPI(widget.OutGoingCallData.sessionId, sessionStatus, context).then((res) {}).catchError((err) { - // print(err); - // }); - // } - - void backToHome() async { - // final connected = await signaling.declineCall(widget.OutGoingCallData.callerID, widget.OutGoingCallData.receiverID); - // LandingPage.isOpenCallPage = false; - // _signaling - _animationController!.dispose(); - // player.stop(); - // changeCallStatusAPI(3); - // _signaling.bye(_session, callRejected: true); - // _signaling.callDisconnected(_session, callRejected: true); - Navigator.of(context).pop(); - } - - // - // void disposeAudioResources() async { - // await player.dispose(); - // } - // - // void setAudioFile() async { - // player.stop(); - // await player.setVolume(1.0); // full volume - // try { - // await player.setAsset('assets/sounds/ring_60Sec.mp3').then((value) { - // player.setLoopMode(LoopMode.one); // loop ring sound - // player.play(); - // }).catchError((err) { - // print("Error: $err"); - // }); - // } catch (e) { - // print("Error: $e"); - // } - // } - // - // void connectSignaling({@required bool iAmCaller = false}) async { - // print("----------------- + Signaling Connection Started ---------------------------"); - // var caller = widget.OutGoingCallData.callerID; - // var receiver = widget.OutGoingCallData.receiverID; - // var host = widget.OutGoingCallData.server; - // - // var selfRole = iAmCaller ? "Caller" : "Receiver"; - // var selfId = iAmCaller ? caller : receiver; - // var selfUser = SocketUser(id: selfId, name: "$selfRole-$selfId", userAgent: DeviceInfo.userAgent, moreInfo: {}); - // - // var remoteRole = !iAmCaller ? "Caller" : "Receiver"; - // var remoteId = !iAmCaller ? caller : receiver; - // var remoteUser = SocketUser(id: remoteId, name: "$remoteRole-$remoteId", userAgent: DeviceInfo.userAgent, moreInfo: {}); - // - // var sessionId = "$caller-$receiver"; - // _session = SessionOneToOne(id: sessionId, local_user: selfUser, remote_user: remoteUser); - // - // _signaling = Signaling(host, session: _session); - // await _signaling.connect(); - // - // if (_signaling.state == SignalingState.Open) { - // return; - // } - // } - BoxDecoration cardRadius(double radius, {required Color color, double? elevation}) { return BoxDecoration( shape: BoxShape.rectangle, color: color ?? Colors.white, - borderRadius: BorderRadius.all( - Radius.circular(radius), - ), - boxShadow: [ - BoxShadow( - color: const Color( - 0xff000000, - ).withOpacity( - .05, - ), - //spreadRadius: 5, - blurRadius: elevation ?? 27, - offset: const Offset( - -2, - 3, - ), - ), - ], + borderRadius: BorderRadius.all(Radius.circular(radius)), + boxShadow: [BoxShadow(color: const Color(0xff000000).withOpacity(.05), blurRadius: elevation ?? 27, offset: const Offset(-2, 3))], ); } } diff --git a/lib/ui/chat/call/draggable_cam_screen.dart b/lib/ui/chat/call/draggable_cam_screen.dart new file mode 100644 index 0000000..14f0fc8 --- /dev/null +++ b/lib/ui/chat/call/draggable_cam_screen.dart @@ -0,0 +1,171 @@ +// import 'dart:async'; +// import 'dart:io'; +// import 'package:flutter/material.dart'; +// +// class DraggableCam extends StatefulWidget { +// //final Size availableScreenSize; +// final Widget child; +// final double scaleFactor; +// // final Stream onButtonBarVisible; +// // final Stream onButtonBarHeight; +// +// const DraggableCam({ +// Key? key, +// //@required this.availableScreenSize, +// required this.child, +// // @required this.onButtonBarVisible, +// // @required this.onButtonBarHeight, +// +// /// The portion of the screen the DraggableWidget should use. +// this.scaleFactor = .25, +// }) : assert(scaleFactor != null && scaleFactor > 0 && scaleFactor <= .4), +// // assert(availableScreenSize != null), +// // assert(onButtonBarVisible != null), +// // assert(onButtonBarHeight != null), +// super(key: key); +// +// @override +// _DraggablePublisherState createState() => _DraggablePublisherState(); +// } +// +// class _DraggablePublisherState extends State { +// bool _isButtonBarVisible = true; +// double _buttonBarHeight = 0; +// late double _width; +// late double _height; +// late double _top; +// late double _left; +// late double _viewPaddingTop; +// late double _viewPaddingBottom; +// final double _padding = 8.0; +// final Duration _duration300ms = const Duration(milliseconds: 300); +// final Duration _duration0ms = const Duration(milliseconds: 0); +// late Duration _duration; +// late StreamSubscription _streamSubscription; +// late StreamSubscription _streamHeightSubscription; +// +// @override +// void initState() { +// super.initState(); +// _duration = _duration300ms; +// _width = widget.availableScreenSize.width * widget.scaleFactor; +// _height = _width * (widget.availableScreenSize.height / widget.availableScreenSize.width); +// _top = widget.availableScreenSize.height - (_buttonBarHeight + _padding) - _height; +// _left = widget.availableScreenSize.width - _padding - _width; +// +// _streamSubscription = widget.onButtonBarVisible.listen(_buttonBarVisible); +// _streamHeightSubscription = widget.onButtonBarHeight.listen(_getButtonBarHeight); +// } +// +// @override +// void didChangeDependencies() { +// var mediaQuery = MediaQuery.of(context); +// _viewPaddingTop = mediaQuery.viewPadding.top; +// _viewPaddingBottom = mediaQuery.viewPadding.bottom; +// super.didChangeDependencies(); +// } +// +// @override +// void dispose() { +// _streamSubscription.cancel(); +// _streamHeightSubscription.cancel(); +// super.dispose(); +// } +// +// void _getButtonBarHeight(double height) { +// setState(() { +// _buttonBarHeight = height; +// _positionWidget(); +// }); +// } +// +// void _buttonBarVisible(bool visible) { +// if (!mounted) { +// return; +// } +// setState(() { +// _isButtonBarVisible = visible; +// if (_duration == _duration300ms) { +// // only position the widget when we are not currently dragging it around +// _positionWidget(); +// } +// }); +// } +// +// @override +// Widget build(BuildContext context) { +// return AnimatedPositioned( +// top: _top, +// left: _left, +// width: _width, +// height: _height, +// duration: _duration, +// child: Listener( +// onPointerDown: (_) => _duration = _duration0ms, +// onPointerMove: (PointerMoveEvent event) { +// setState(() { +// _left = (_left + event.delta.dx).roundToDouble(); +// _top = (_top + event.delta.dy).roundToDouble(); +// }); +// }, +// onPointerUp: (_) => _positionWidget(), +// onPointerCancel: (_) => _positionWidget(), +// child: ClippedVideo( +// height: _height, +// width: _width, +// child: widget.child, +// ), +// ), +// ); +// } +// +// double _getCurrentStatusBarHeight() { +// if (_isButtonBarVisible) { +// return _viewPaddingTop; +// } +// final _defaultViewPaddingTop = Platform.isIOS ? 20.0 : Platform.isAndroid ? 24.0 : 0.0; +// if (_viewPaddingTop > _defaultViewPaddingTop) { +// // There must be a hardware notch in the display. +// return _viewPaddingTop; +// } +// return 0.0; +// } +// +// double _getCurrentButtonBarHeight() { +// if (_isButtonBarVisible) { +// return _buttonBarHeight + _viewPaddingBottom; +// } +// return _viewPaddingBottom; +// } +// +// void _positionWidget() { +// // Determine the center of the object being dragged so we can decide +// // in which corner the object should be placed. +// var dx = (_width / 2) + _left; +// dx = dx < 0 ? 0 : dx >= widget.availableScreenSize.width ? widget.availableScreenSize.width - 1 : dx; +// var dy = (_height / 2) + _top; +// dy = dy < 0 ? 0 : dy >= widget.availableScreenSize.height ? widget.availableScreenSize.height - 1 : dy; +// final draggableCenter = Offset(dx, dy); +// +// setState(() { +// _duration = _duration300ms; +// if (Rect.fromLTRB(0, 0, widget.availableScreenSize.width / 2, widget.availableScreenSize.height / 2).contains(draggableCenter)) { +// // Top-left +// _top = _getCurrentStatusBarHeight() + _padding; +// _left = _padding; +// } else if (Rect.fromLTRB(widget.availableScreenSize.width / 2, 0, widget.availableScreenSize.width, widget.availableScreenSize.height / 2).contains(draggableCenter)) { +// // Top-right +// _top = _getCurrentStatusBarHeight() + _padding; +// _left = widget.availableScreenSize.width - _padding - _width; +// } else if (Rect.fromLTRB(0, widget.availableScreenSize.height / 2, widget.availableScreenSize.width / 2, widget.availableScreenSize.height).contains(draggableCenter)) { +// // Bottom-left +// _top = widget.availableScreenSize.height - (_getCurrentButtonBarHeight() + _padding) - _height; +// _left = _padding; +// } else if (Rect.fromLTRB(widget.availableScreenSize.width / 2, widget.availableScreenSize.height / 2, widget.availableScreenSize.width, widget.availableScreenSize.height).contains(draggableCenter)) { +// // Bottom-right +// _top = widget.availableScreenSize.height - (_getCurrentButtonBarHeight() + _padding) - _height; +// _left = widget.availableScreenSize.width - _padding - _width; +// } +// }); +// } +// } diff --git a/lib/ui/chat/chat_detailed_screen.dart b/lib/ui/chat/chat_detailed_screen.dart index 421eb91..d76bf9b 100644 --- a/lib/ui/chat/chat_detailed_screen.dart +++ b/lib/ui/chat/chat_detailed_screen.dart @@ -1,5 +1,5 @@ import 'dart:async'; -import 'dart:convert'; +import 'dart:io'; import 'package:audio_waveforms/audio_waveforms.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; @@ -10,11 +10,9 @@ import 'package:mohem_flutter_app/extensions/int_extensions.dart'; import 'package:mohem_flutter_app/extensions/string_extensions.dart'; import 'package:mohem_flutter_app/extensions/widget_extensions.dart'; import 'package:mohem_flutter_app/generated/locale_keys.g.dart'; -import 'package:mohem_flutter_app/main.dart'; import 'package:mohem_flutter_app/models/chat/call.dart'; import 'package:mohem_flutter_app/models/chat/get_search_user_chat_model.dart'; import 'package:mohem_flutter_app/models/chat/get_single_user_chat_list_model.dart'; -import 'package:mohem_flutter_app/models/chat/get_user_login_token_model.dart'; import 'package:mohem_flutter_app/provider/chat_call_provider.dart'; import 'package:mohem_flutter_app/provider/chat_provider_model.dart'; import 'package:mohem_flutter_app/ui/chat/custom_auto_direction.dart'; @@ -23,9 +21,9 @@ import 'package:mohem_flutter_app/ui/chat/chat_bubble.dart'; import 'package:mohem_flutter_app/ui/chat/common.dart'; import 'package:mohem_flutter_app/widgets/chat_app_bar_widge.dart'; import 'package:mohem_flutter_app/widgets/shimmer/dashboard_shimmer_widget.dart'; +import 'package:permission_handler/permission_handler.dart'; import 'package:provider/provider.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart'; -import 'package:signalr_netcore/signalr_client.dart'; import 'package:swipe_to/swipe_to.dart'; class ChatDetailedScreenParams { @@ -78,7 +76,7 @@ class _ChatDetailScreenState extends State { Widget build(BuildContext context) { params = ModalRoute.of(context)!.settings.arguments as ChatDetailedScreenParams; data = Provider.of(context, listen: false); - // callPro = Provider.of(context, listen: false); + // callPro = Provider.of(context, listen: false); if (params != null) { data.getSingleUserChatHistory( senderUID: AppState().chatDetails!.response!.id!.toInt(), @@ -98,14 +96,32 @@ class _ChatDetailScreenState extends State { showTyping: true, chatUser: params!.chatUser, actions: [ - // SvgPicture.asset("assets/icons/chat/call.svg", width: 21, height: 23).onPress(() { - // makeCall(callType: "AUDIO"); - // }), - // 24.width, - // SvgPicture.asset("assets/icons/chat/video_call.svg", width: 21, height: 18).onPress(() { - // makeCall(callType: "VIDEO"); - // }), - // 21.width, + // if (Platform.isAndroid) + SvgPicture.asset("assets/icons/chat/call.svg", width: 21, height: 23).onPress(() async { + Future micPer = Permission.microphone.request(); + if (await micPer.isGranted) { + makeCall(callType: "AUDIO"); + } else { + Permission.microphone.request().isGranted.then((value) { + makeCall(callType: "AUDIO"); + }); + } + }), + // if (Platform.isAndroid) + 24.width, + // if (Platform.isAndroid) + SvgPicture.asset("assets/icons/chat/video_call.svg", width: 21, height: 18).onPress(() async { + Future camPer = Permission.camera.request(); + if (await camPer.isGranted) { + makeCall(callType: "VIDEO"); + } else { + Permission.camera.request().isGranted.then((value) { + makeCall(callType: "VIDEO"); + }); + } + }), + // if (Platform.isAndroid) + 21.width, ], ), body: SafeArea( @@ -149,7 +165,7 @@ class _ChatDetailScreenState extends State { ); }, ).onPress(() async { - logger.w(m.userChatHistory[i].toJson()); + // logger.w(m.userChatHistory[i].toJson()); if (m.userChatHistory[i].fileTypeResponse != null && m.userChatHistory[i].fileTypeId != null) { if (m.userChatHistory[i].fileTypeId! == 1 || m.userChatHistory[i].fileTypeId! == 5 || @@ -352,29 +368,21 @@ class _ChatDetailScreenState extends State { } void makeCall({required String callType}) async { - callPro.initCallListeners(); - print("================== Make call Triggered ============================"); Map json = { - "callerID": AppState().chatDetails!.response!.id!.toString(), - "callerDetails": AppState().chatDetails!.toJson(), - "receiverID": params!.chatUser!.id.toString(), - "receiverDetails": params!.chatUser!.toJson(), + "callerID": AppState().chatDetails!.response!.id, + "callerName": AppState().chatDetails!.response!.userName, + "callerEmail": AppState().chatDetails!.response!.email, + "callerTitle": AppState().chatDetails!.response!.title, + "callerPhone": AppState().chatDetails!.response!.phone, + "receiverID": params!.chatUser!.id, + "receiverName": params!.chatUser!.userName, + "receiverEmail": params!.chatUser!.email, + "receiverTitle": params!.chatUser!.title, + "receiverPhone": params!.chatUser!.phone, "title": params!.chatUser!.userName!.replaceAll(".", " "), - "calltype": callType == "VIDEO" ? "Video" : "Audio", + "callType": callType == "VIDEO" ? "Video" : "Audio", }; - logger.w(json); CallDataModel callData = CallDataModel.fromJson(json); - await Navigator.push( - context, - MaterialPageRoute( - builder: (BuildContext context) => OutGoingCall( - isVideoCall: callType == "VIDEO" ? true : false, - outGoingCallData: callData, - ), - ), - ).then((value) { - print("then"); - callPro.stopListeners(); - }); + await Navigator.push(context, MaterialPageRoute(builder: (BuildContext context) => OutGoingCall(isVideoCall: callType == "VIDEO" ? true : false, outGoingCallData: callData))); } } diff --git a/lib/ui/chat/chat_home.dart b/lib/ui/chat/chat_home.dart index 9c5f216..c557bb1 100644 --- a/lib/ui/chat/chat_home.dart +++ b/lib/ui/chat/chat_home.dart @@ -7,6 +7,7 @@ import 'package:mohem_flutter_app/extensions/int_extensions.dart'; import 'package:mohem_flutter_app/extensions/string_extensions.dart'; import 'package:mohem_flutter_app/extensions/widget_extensions.dart'; import 'package:mohem_flutter_app/generated/locale_keys.g.dart'; +import 'package:mohem_flutter_app/provider/chat_call_provider.dart'; import 'package:mohem_flutter_app/provider/chat_provider_model.dart'; import 'package:mohem_flutter_app/ui/chat/chat_home_screen.dart'; import 'package:mohem_flutter_app/ui/chat/favorite_users_screen.dart'; @@ -27,12 +28,15 @@ class _ChatHomeState extends State { int tabIndex = 0; PageController controller = PageController(); late ChatProviderModel data; + late ChatCallProvider callProvider; @override void initState() { super.initState(); data = Provider.of(context, listen: false); + callProvider = Provider.of(context, listen: false); data.registerEvents(); + // callProvider.initCallListeners(); } @override @@ -44,7 +48,7 @@ class _ChatHomeState extends State { void fetchAgain() { if (chatHubConnection.state != HubConnectionState.Connected) { data.getUserAutoLoginToken().whenComplete(() async { - await data.buildHubConnection(); + await data.buildHubConnection(context: context, ccProvider: callProvider); data.getUserRecentChats(); }); return; @@ -52,11 +56,6 @@ class _ChatHomeState extends State { if (data.searchedChats == null || data.searchedChats!.isEmpty) { data.isLoading = true; data.getUserRecentChats().whenComplete(() async { - // String isAppOpendByChat = await Utils.getStringFromPrefs("isAppOpendByChat"); - // String notificationData = await Utils.getStringFromPrefs("notificationData"); - // if (isAppOpendByChat != "null" || isAppOpendByChat == "true" && notificationData != "null") { - // data.openChatByNoti(context); - // } }); } } diff --git a/lib/ui/chat/common.dart b/lib/ui/chat/common.dart index e0cb4d0..17e61da 100644 --- a/lib/ui/chat/common.dart +++ b/lib/ui/chat/common.dart @@ -1,3 +1,4 @@ +import 'dart:async'; import 'dart:math'; import 'package:audio_waveforms/audio_waveforms.dart'; import 'package:flutter/material.dart'; @@ -187,3 +188,40 @@ class WaveBubble extends StatelessWidget { ); } } + +class CallTimer extends StatefulWidget { + const CallTimer({Key? key}) : super(key: key); + + @override + State createState() => _CallTimerState(); +} + +class _CallTimerState extends State { + late Timer _timer; + int _timeExpandedBySeconds = 0; + + @override + void initState() { + // TODO: implement initState + super.initState(); + _timer = Timer.periodic(const Duration(seconds: 1), (Timer timer) { + setState(() { + _timeExpandedBySeconds += 1; + }); + }); + } + + @override + Widget build(BuildContext context) { + return Text( + _timeExpandedBySeconds.toString(), + style: const TextStyle( + fontSize: 17, + fontWeight: FontWeight.bold, + color: MyColors.white, + letterSpacing: -1.26, + height: 23 / 12, + ), + ); + } +} diff --git a/lib/ui/landing/dashboard_screen.dart b/lib/ui/landing/dashboard_screen.dart index 2db09d0..87eadd2 100644 --- a/lib/ui/landing/dashboard_screen.dart +++ b/lib/ui/landing/dashboard_screen.dart @@ -18,6 +18,7 @@ import 'package:mohem_flutter_app/extensions/widget_extensions.dart'; import 'package:mohem_flutter_app/generated/locale_keys.g.dart'; import 'package:mohem_flutter_app/models/offers_and_discounts/get_offers_list.dart'; import 'package:mohem_flutter_app/models/privilege_list_model.dart'; +import 'package:mohem_flutter_app/provider/chat_call_provider.dart'; import 'package:mohem_flutter_app/provider/chat_provider_model.dart'; import 'package:mohem_flutter_app/provider/dashboard_provider_model.dart'; import 'package:mohem_flutter_app/ui/landing/widget/app_drawer.dart'; @@ -48,6 +49,7 @@ class _DashboardScreenState extends State with WidgetsBindingOb late DashboardProviderModel data; late MarathonProvider marathonProvider; late ChatProviderModel cProvider; + late ChatCallProvider chatCallProvider; final GlobalKey _scaffoldState = GlobalKey(); final RefreshController _refreshController = RefreshController(initialRefresh: false); @@ -62,6 +64,7 @@ class _DashboardScreenState extends State with WidgetsBindingOb data = Provider.of(context, listen: false); marathonProvider = Provider.of(context, listen: false); cProvider = Provider.of(context, listen: false); + chatCallProvider = Provider.of(context, listen: false); if (checkIfPrivilegedForChat()) { _bHubCon(); } @@ -88,24 +91,24 @@ class _DashboardScreenState extends State with WidgetsBindingOb void dispose() { WidgetsBinding.instance.removeObserver(this); super.dispose(); - if (!cProvider.disbaleChatForThisUser) { + if (!cProvider.disableChatForThisUser) { chatHubConnection.stop(); } } void _bHubCon() { cProvider.getUserAutoLoginToken().whenComplete(() async { - if (!cProvider.disbaleChatForThisUser) { + if (!cProvider.disableChatForThisUser) { String isAppOpendByChat = await Utils.getStringFromPrefs("isAppOpendByChat"); if (isAppOpendByChat != "null" && isAppOpendByChat == "true") { Utils.showLoading(context); - cProvider.buildHubConnection(); + cProvider.buildHubConnection(context: context, ccProvider: chatCallProvider); Future.delayed(const Duration(seconds: 2), () async { cProvider.invokeChatCounter(userId: AppState().chatDetails!.response!.id!); gotoChat(context); }); } else { - cProvider.buildHubConnection(); + cProvider.buildHubConnection(context: context, ccProvider: chatCallProvider); Future.delayed(const Duration(seconds: 2), () { cProvider.invokeChatCounter(userId: AppState().chatDetails!.response!.id!); }); @@ -153,7 +156,7 @@ class _DashboardScreenState extends State with WidgetsBindingOb if (isFromInit) { checkERMChannel(); } - if (!cProvider.disbaleChatForThisUser && !isFromInit) checkHubCon(); + if (!cProvider.disableChatForThisUser && !isFromInit) checkHubCon(); _refreshController.refreshCompleted(); } @@ -186,6 +189,15 @@ class _DashboardScreenState extends State with WidgetsBindingOb "masterId": val.result!.data!.notificationMasterId, "advertisement": value.mohemmItgResponseItem!.result!.data!.advertisement, }); + // Navigator.push( + // context, + // MaterialPageRoute( + // builder: (BuildContext context) => ITGAdsScreen( + // addMasterId: val.result!.data!.notificationMasterId!, + // advertisement: value.mohemmItgResponseItem!.result!.data!.advertisement!, + // ), + // ), + // ); } } }, @@ -199,6 +211,46 @@ class _DashboardScreenState extends State with WidgetsBindingOb Widget build(BuildContext context) { return Scaffold( key: _scaffoldState, + // appBar: AppBar( + // actions: [ + // IconButton( + // onPressed: () { + // data.getITGNotification().then((val) { + // if (val!.result!.data != null) { + // print("-------------------- Survey ----------------------------"); + // if (val.result!.data!.notificationType == "Survey") { + // Navigator.pushNamed(context, AppRoutes.survey, arguments: val.result!.data); + // } else { + // print("------------------------------------------- Ads --------------------"); + // DashboardApiClient().getAdvertisementDetail(val.result!.data!.notificationMasterId ?? "").then( + // (value) { + // if (value!.mohemmItgResponseItem!.statusCode == 200) { + // if (value.mohemmItgResponseItem!.result!.data != null) { + // Navigator.pushNamed(context, AppRoutes.advertisement, arguments: { + // "masterId": val.result!.data!.notificationMasterId, + // "advertisement": value.mohemmItgResponseItem!.result!.data!.advertisement, + // }); + // + // // Navigator.push( + // // context, + // // MaterialPageRoute( + // // builder: (BuildContext context) => ITGAdsScreen( + // // addMasterId: val.result!.data!.notificationMasterId!, + // // advertisement: value.mohemmItgResponseItem!.result!.data!.advertisement!, + // // ), + // // ), + // // ); + // } + // } + // }, + // ); + // } + // } + // }); + // }, + // icon: Icon(Icons.add)) + // ], + // ), body: Column( children: [ Row( @@ -571,7 +623,7 @@ class _DashboardScreenState extends State with WidgetsBindingOb ? MyColors.lightGreyE3Color : currentIndex == 4 ? MyColors.grey3AColor - : cProvider.disbaleChatForThisUser + : cProvider.disableChatForThisUser ? MyColors.lightGreyE3Color : MyColors.grey98Color, ).paddingAll(4), @@ -585,7 +637,7 @@ class _DashboardScreenState extends State with WidgetsBindingOb child: Container( padding: const EdgeInsets.only(left: 4, right: 4), alignment: Alignment.center, - decoration: BoxDecoration(color: cProvider.disbaleChatForThisUser ? MyColors.pinkDarkColor : MyColors.redColor, borderRadius: BorderRadius.circular(17)), + decoration: BoxDecoration(color: cProvider.disableChatForThisUser ? MyColors.pinkDarkColor : MyColors.redColor, borderRadius: BorderRadius.circular(17)), child: data.chatUConvCounter.toString().toText10(color: Colors.white), ), ); @@ -612,7 +664,7 @@ class _DashboardScreenState extends State with WidgetsBindingOb } else if (index == 3) { Navigator.pushNamed(context, AppRoutes.itemsForSale); } else if (index == 4) { - if (!cProvider.disbaleChatForThisUser && checkIfPrivilegedForChat()) { + if (!cProvider.disableChatForThisUser) { Navigator.pushNamed(context, AppRoutes.chat); } } @@ -637,6 +689,7 @@ class _DashboardScreenState extends State with WidgetsBindingOb } } }); + Navigator.pushNamed(context, AppRoutes.offersAndDiscountsDetails, arguments: getOffersDetailList); } diff --git a/lib/ui/login/login_screen.dart b/lib/ui/login/login_screen.dart index 8d8e7c2..8a78dfd 100644 --- a/lib/ui/login/login_screen.dart +++ b/lib/ui/login/login_screen.dart @@ -21,6 +21,8 @@ import 'package:mohem_flutter_app/extensions/int_extensions.dart'; import 'package:mohem_flutter_app/extensions/string_extensions.dart'; import 'package:mohem_flutter_app/extensions/widget_extensions.dart'; import 'package:mohem_flutter_app/generated/locale_keys.g.dart'; +import 'package:mohem_flutter_app/main.dart'; +import 'package:mohem_flutter_app/models/chat/incoming_call_model.dart'; import 'package:mohem_flutter_app/models/check_mobile_app_version_model.dart'; import 'package:mohem_flutter_app/models/get_mobile_login_info_list_model.dart'; import 'package:mohem_flutter_app/models/member_information_list_model.dart'; @@ -221,9 +223,7 @@ class _LoginScreenState extends State { children: [ Row( children: [ - // Expanded( - // child:SizedBox(child: HmgConnectivityButton(),), - // ), + Expanded(child: SizedBox()), Row( children: [ LocaleKeys.english.tr().toText14(color: AppState().isArabic(context) ? null : MyColors.textMixColor).onPress(() { diff --git a/lib/ui/login/verify_last_login_screen.dart b/lib/ui/login/verify_last_login_screen.dart index c48d1f3..f94e59a 100644 --- a/lib/ui/login/verify_last_login_screen.dart +++ b/lib/ui/login/verify_last_login_screen.dart @@ -3,6 +3,7 @@ import 'dart:io'; import 'package:easy_localization/src/public_ext.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; +import 'package:flutter_callkit_incoming/flutter_callkit_incoming.dart'; import 'package:flutter_svg/svg.dart'; import 'package:local_auth/auth_strings.dart'; import 'package:local_auth/local_auth.dart'; @@ -50,11 +51,13 @@ class _VerifyLastLoginScreenState extends State { @override void initState() { - _getAvailableBiometrics(); + _getAvailableBiometrics(); // setDefault(); super.initState(); } + + @override Widget build(BuildContext context) { mobileLoginInfoListModel ??= ModalRoute.of(context)!.settings.arguments as GetMobileLoginInfoListModel; @@ -289,7 +292,7 @@ class _VerifyLastLoginScreenState extends State { width: 38, color: isDisable ? MyColors.darkTextColor.withOpacity(0.7) : null, ), - _title.toText16(height: 20/16) + _title.toText16(height: 20 / 16) ], ), ), @@ -404,5 +407,4 @@ class _VerifyLastLoginScreenState extends State { // // isLoading = isTrue; // }); // } - } diff --git a/pubspec.yaml b/pubspec.yaml index bc70be9..b50b4c6 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -87,9 +87,11 @@ dependencies: signalr_netcore: ^1.3.3 logging: ^1.0.1 swipe_to: ^1.0.2 - flutter_webrtc: ^0.9.16 - camera: ^0.10.3 - flutter_local_notifications: ^10.0.0 + flutter_webrtc: ^0.9.20 + draggable_widget: ^2.0.0 + flutter_local_notifications: any + flutter_callkit_incoming: ^1.0.3+3 + get_it: ^7.6.0 #firebase_analytics: any #Chat Voice Message Recoding & Play @@ -114,7 +116,7 @@ dependencies: carousel_slider: ^4.2.1 #Huawei Specified -# store_checker: ^1.1.0 + store_checker: ^1.1.0 google_api_availability: ^3.0.1