From 3b8332ce21bc9ff14815efb30ee681eac79b3a62 Mon Sep 17 00:00:00 2001 From: Aamir Date: Sun, 10 Mar 2024 11:14:54 +0300 Subject: [PATCH] changes local --- .../call/chat_incoming_call_screen.dart | 208 ++- .../call/chat_outgoing_call_screen.dart | 398 ++--- lib/voipcall/provider/chat_call_provider.dart | 1303 ++++++++++------- lib/widgets/drawer/app_drawer_widget.dart | 104 +- 4 files changed, 1085 insertions(+), 928 deletions(-) diff --git a/lib/voipcall/call/chat_incoming_call_screen.dart b/lib/voipcall/call/chat_incoming_call_screen.dart index 83ea9160..841eb1bb 100644 --- a/lib/voipcall/call/chat_incoming_call_screen.dart +++ b/lib/voipcall/call/chat_incoming_call_screen.dart @@ -1,17 +1,10 @@ -import 'dart:convert'; import 'dart:core'; -import 'dart:io'; import 'dart:ui'; -import 'package:diplomaticquarterapp/app_state/app_state.dart'; import 'package:diplomaticquarterapp/voipcall/consts.dart'; import 'package:diplomaticquarterapp/voipcall/model/call.dart'; -import 'package:diplomaticquarterapp/voipcall/model/get_single_user_chat_call.dart'; -import 'package:diplomaticquarterapp/voipcall/model/get_user_login_token.dart'; -import 'package:diplomaticquarterapp/voipcall/model/incoming_call_model.dart'; import 'package:diplomaticquarterapp/voipcall/provider/chat_call_provider.dart'; import 'package:draggable_widget/draggable_widget.dart'; -import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:flutter_webrtc/flutter_webrtc.dart'; @@ -42,98 +35,103 @@ class _StartCallPageState extends State { super.dispose(); } - void startCall() async { - IncomingCallModel? sessionData; - // dynamic calls = await FlutterCallkitIncoming.activeCalls(); - // if (calls.isNotEmpty) { - // sessionData.extra.callerDetails = {"id":341682,"userName":"Aamir.Muhammad","email":"Aamir.Muhammad@cloudsolutions.com.sa","phone":null,"title":"Aamir Saleem Ahmad Dost Muhammad","token":"eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJuYW1laWQiOiIzNDE2ODIiLCJlbWFpbCI6IkFhbWlyLk11aGFtbWFkQGNsb3Vkc29sdXRpb25zLmNvbS5zYSIsImh0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vd3MvMjAwOC8wNi9pZGVudGl0eS9jbGFpbXMvdXNlcmRhdGEiOiJBYW1pci5NdWhhbW1hZCIsIm5iZiI6MTcwNzIwNTAyMywiZXhwIjoxNzA3MjkxNDIzLCJpYXQiOjE3MDcyMDUwMjN9.Zz2bcsMwiLAAWGZh2E_p5Qs6ItMt0JHhDFI_0DLdggCQtt6HHcT4n8nvqMZx-uYr3jLwqhA_IAjTuaCeSE15sw","isDomainUser":true,"isActiveCode":false,"encryptedUserId":"nn7RkYzbnQc=","encryptedUserName":"/QruOyp4QMcmNXKZlljUgg=="}; - // sessionData = IncomingCallModel.fromRawJson(jsonEncode(calls[0])); - if (kDebugMode) { - print(sessionData!.toRawJson()); - } - if (cProv!.isUserOnline) { - AppState().isBackgroundCall = true; - if (kDebugMode) { - print("====== Processing Incoming Call in Online State ========="); - } - await cProv!.startIncomingCallViaKit(inCallData: sessionData!.extra!.callerDetails!.toJson(), isVCall: sessionData.extra!.callType == "video" ? true : false); - cProv!.init(); - isCallConnected = true; - } else { - AppState().isBackgroundCall = true; - if (kDebugMode) { - print("====== Processing Incoming Call ========="); - } - // cProv.isUserOnline = provider.isUserOnline; - await cProv!.startIncomingCallViaKit(inCallData: sessionData!.extra!.callerDetails!.toJson(), isVCall: sessionData!.extra!.callType == "video" ? true : false); - try { - AppState().setchatUserDetails = UserAutoLoginModel(response: Response.fromJson(sessionData.extra!.loginDetails!.toJson()), errorResponses: null); - // await cProv!.buildHubConnection().whenComplete(() { - // cProv!.init(); - // isCallConnected = true; - // }); - } catch (e) { - print(e); - } - } - //} + // void startCall() async { + // IncomingCallModel? sessionData; + // // dynamic calls = await FlutterCallkitIncoming.activeCalls(); + // // if (calls.isNotEmpty) { + // // sessionData.extra.callerDetails = {"id":341682,"userName":"Aamir.Muhammad","email":"Aamir.Muhammad@cloudsolutions.com.sa","phone":null,"title":"Aamir Saleem Ahmad Dost Muhammad","token":"eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJuYW1laWQiOiIzNDE2ODIiLCJlbWFpbCI6IkFhbWlyLk11aGFtbWFkQGNsb3Vkc29sdXRpb25zLmNvbS5zYSIsImh0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vd3MvMjAwOC8wNi9pZGVudGl0eS9jbGFpbXMvdXNlcmRhdGEiOiJBYW1pci5NdWhhbW1hZCIsIm5iZiI6MTcwNzIwNTAyMywiZXhwIjoxNzA3MjkxNDIzLCJpYXQiOjE3MDcyMDUwMjN9.Zz2bcsMwiLAAWGZh2E_p5Qs6ItMt0JHhDFI_0DLdggCQtt6HHcT4n8nvqMZx-uYr3jLwqhA_IAjTuaCeSE15sw","isDomainUser":true,"isActiveCode":false,"encryptedUserId":"nn7RkYzbnQc=","encryptedUserName":"/QruOyp4QMcmNXKZlljUgg=="}; + // // sessionData = IncomingCallModel.fromRawJson(jsonEncode(calls[0])); + // // if (kDebugMode) { + // // print(sessionData!.toRawJson()); + // // } + // if (cProv!.isUserOnline) { + // AppState().isBackgroundCall = true; + // if (kDebugMode) { + // print("====== Processing Incoming Call in Online State ========="); + // } + // await cProv!.startIncomingCallViaKit(inCallData: sessionData!.extra!.callerDetails!.toJson(), isVCall: sessionData.extra!.callType == "video" ? true : false); + // cProv!.init(); + // isCallConnected = true; + // } else { + // AppState().isBackgroundCall = true; + // if (kDebugMode) { + // print("====== Processing Incoming Call ========="); + // } + // // cProv.isUserOnline = provider.isUserOnline; + // await cProv!.startIncomingCallViaKit(inCallData: sessionData!.extra!.callerDetails!.toJson(), isVCall: sessionData!.extra!.callType == "video" ? true : false); + // try { + // AppState().setchatUserDetails = UserAutoLoginModel(response: Response.fromJson(sessionData.extra!.loginDetails!.toJson()), errorResponses: null); + // // await cProv!.buildHubConnection().whenComplete(() { + // // cProv!.init(); + // // isCallConnected = true; + // // }); + // } catch (e) { + // print(e); + // } + // } + // //} + // + // // cProv.startRecording(); + // } - // cProv.startRecording(); - } - - void startIosCall() async { - IosCallPayload iosCallPayload = widget.payload!; - var userID = iosCallPayload.incomingCallReciverId; - var callType = iosCallPayload.incomingCallType; - SingleUserChatModel inCallData = SingleUserChatModel( - targetUserName: iosCallPayload.incomingCallerName, - chatEventId: 3, - targetUserId: int.parse(iosCallPayload.incomingCallerId!), - currentUserId: int.parse(userID.toString()), - ); - if (cProv!.isUserOnline) { - AppState().isBackgroundCall = true; - if (kDebugMode) { - print("====== Processing Incoming Call in Online State ========="); - } - await cProv!.startIncomingCallViaKit(inCallData: inCallData.toJson(), isVCall: callType == "video" ? true : false); - cProv!.init(); - isCallConnected = true; - } else { - if (kDebugMode) { - print("====== Processing Incoming Call ========="); - } - AppState().isBackgroundCall = true; - UserAutoLoginModel userLoginResponse = await ChatService().getUserCallToken(userid: userID.toString()); - if (userLoginResponse.response != null) { - AppState().setchatUserDetails = userLoginResponse; - AppSharedPrefs().setStringFromPrefs("userLoginChatDetails", jsonEncode(userLoginResponse.response)); + // void startIosCall() async { + // IosCallPayload iosCallPayload = widget.payload!; + // var userID = iosCallPayload.incomingCallReciverId; + // var callType = iosCallPayload.incomingCallType; + // SingleUserChatModel inCallData = SingleUserChatModel( + // targetUserName: iosCallPayload.incomingCallerName, + // chatEventId: 3, + // targetUserId: int.parse(iosCallPayload.incomingCallerId!), + // currentUserId: int.parse(userID.toString()), + // ); + // if (cProv!.isUserOnline) { + // AppState().isBackgroundCall = true; + // if (kDebugMode) { + // print("====== Processing Incoming Call in Online State ========="); + // } + // await cProv!.startIncomingCallViaKit(inCallData: inCallData.toJson(), isVCall: callType == "video" ? true : false); + // cProv!.init(); + // isCallConnected = true; + // } else { + // if (kDebugMode) { + // print("====== Processing Incoming Call ========="); + // } + // AppState().isBackgroundCall = true; + // UserAutoLoginModel userLoginResponse = await ChatService().getUserCallToken(userid: userID.toString()); + // if (userLoginResponse.response != null) { + // AppState().setchatUserDetails = userLoginResponse; + // AppSharedPrefs().setStringFromPrefs("userLoginChatDetails", jsonEncode(userLoginResponse.response)); + // + // await cProv!.startIncomingCallViaKit(inCallData: inCallData.toJson(), isVCall: callType == "video" ? true : false); + // try { + // AppState().setchatUserDetails = UserAutoLoginModel(response: userLoginResponse.response, errorResponses: null); + // // await cProv!.buildHubConnection().whenComplete(() { + // // cProv!.init(); + // // isCallConnected = true; + // // }); + // } catch (e) { + // print(e); + // } + // } + // } + // } - await cProv!.startIncomingCallViaKit(inCallData: inCallData.toJson(), isVCall: callType == "video" ? true : false); - try { - AppState().setchatUserDetails = UserAutoLoginModel(response: userLoginResponse.response, errorResponses: null); - // await cProv!.buildHubConnection().whenComplete(() { - // cProv!.init(); - // isCallConnected = true; - // }); - } catch (e) { - print(e); - } - } - } - } + // void startIosCall() { + // cProv!.startCallByRTC(); + // } @override Widget build(BuildContext context) { cProv = context.read(); - if (!cProv!.isOutGoingCall) { - if (Platform.isAndroid) { - startCall(); - } else if (Platform.isIOS) { - // cProv!.buildHubConnection(); - // startIosCall(); - } - } + // if (!cProv!.isOutGoingCall) { + // if (Platform.isAndroid) { + // // startCall(); + // } else if (Platform.isIOS) { + // // cProv!.buildHubConnection(); + // // startIosCall(); + // // startIosCall(); + // } + // } return Scaffold( extendBody: true, @@ -349,11 +347,11 @@ class _StartCallPageState extends State { RawMaterialButton( constraints: const BoxConstraints(), onPressed: () { - prov.endCall(isUserOnline: prov.isUserOnline).then((bool value) { - if (value) { - Navigator.of(context).pop(); - } - }); + // prov.endCall(isUserOnline: prov.isUserOnline).then((bool value) { + // if (value) { + // Navigator.of(context).pop(); + // } + // }); }, elevation: 2.0, fillColor: MyColors.redA3Color, @@ -578,13 +576,13 @@ class _StartCallPageState extends State { RawMaterialButton( constraints: const BoxConstraints(), onPressed: () { - prov.endCall(isUserOnline: prov.isUserOnline).then( - (bool value) { - if (value) { - Navigator.of(context).pop(); - } - }, - ); + // prov.endCall(isUserOnline: prov.isUserOnline).then( + // (bool value) { + // if (value) { + // Navigator.of(context).pop(); + // } + // }, + // ); }, elevation: 2.0, fillColor: MyColors.redA3Color, diff --git a/lib/voipcall/call/chat_outgoing_call_screen.dart b/lib/voipcall/call/chat_outgoing_call_screen.dart index 0c03759f..4da874ae 100644 --- a/lib/voipcall/call/chat_outgoing_call_screen.dart +++ b/lib/voipcall/call/chat_outgoing_call_screen.dart @@ -1,199 +1,199 @@ -import 'dart:ui'; - -import 'package:diplomaticquarterapp/voipcall/consts.dart'; -import 'package:diplomaticquarterapp/voipcall/model/call.dart'; -import 'package:diplomaticquarterapp/voipcall/provider/chat_call_provider.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_svg/flutter_svg.dart'; -import 'package:flutter_webrtc/flutter_webrtc.dart'; -import 'package:provider/provider.dart'; - -class OutGoingCall extends StatefulWidget { - CallDataModel? outGoingCallData; - bool isVideoCall; - - OutGoingCall({Key? key, this.outGoingCallData, this.isVideoCall = false}) : super(key: key); - - @override - _OutGoingCallState createState() => _OutGoingCallState(); -} - -class _OutGoingCallState extends State { - ChatCallProvider? callProvider; - //late ChatProviderModel chatProvider; - bool loader = true; - - @override - void initState() { - super.initState(); - } - - Future init() async { - // widget.isVideoCall ? callProvider!.isVideoCall = true : callProvider!.isVideoCall = false; - widget.isVideoCall = true; - callProvider!.isOutGoingCall = true; - // IosCallPayload payload = IosCallPayload( - // incomingCallerId: widget.outGoingCallData.callerId.toString(), - // incomingCallerName: widget.outGoingCallData.callerName, - // incomingCallReciverId: widget.outGoingCallData.receiverId.toString(), - // incomingCallType: widget.outGoingCallData.callType, - // uuid: "", - // callData: widget.outGoingCallData.toRawJson()); - // await Utils.saveStringFromPrefs("iosCallPayload", jsonEncode(payload)); - await callProvider!.initLocalCamera(callData: widget.outGoingCallData); - loader = false; - } - - @override - void dispose() { - super.dispose(); - } - - @override - Widget build(BuildContext context) { - callProvider = Provider.of(context, listen: false); - init(); - return Scaffold( - body: Consumer(builder: (BuildContext context, ChatCallProvider chatcp, Widget? child) { - return loader - ? const Center( - child: CircularProgressIndicator(), - ) - : 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, - ), - ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisSize: MainAxisSize.max, - children: [ - SizedBox( - height: 40, - ), - 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, - ), - SizedBox( - height: 10, - ), - Text( - widget.outGoingCallData!.receiverName.toString().replaceAll(".", " "), - 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, - ), - ], - ), - ), - ), - ], - ), - 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: chatcp.isUserOnline).then((bool value) { - if (value) { - Navigator.of(context).pop(); - } - }); - }, - 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, - ), - ), - ], - ), - ), - ], - ), - ), - ), - ), - ), - ], - ); - }), - ); - } - - BoxDecoration cardRadius(double radius, {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), blurRadius: elevation ?? 27, offset: const Offset(-2, 3))], - ); - } -} +// import 'dart:ui'; +// +// import 'package:diplomaticquarterapp/voipcall/consts.dart'; +// import 'package:diplomaticquarterapp/voipcall/model/call.dart'; +// import 'package:diplomaticquarterapp/voipcall/provider/chat_call_provider.dart'; +// import 'package:flutter/material.dart'; +// import 'package:flutter_svg/flutter_svg.dart'; +// import 'package:flutter_webrtc/flutter_webrtc.dart'; +// import 'package:provider/provider.dart'; +// +// class OutGoingCall extends StatefulWidget { +// CallDataModel? outGoingCallData; +// bool isVideoCall; +// +// OutGoingCall({Key? key, this.outGoingCallData, this.isVideoCall = false}) : super(key: key); +// +// @override +// _OutGoingCallState createState() => _OutGoingCallState(); +// } +// +// class _OutGoingCallState extends State { +// ChatCallProvider? callProvider; +// //late ChatProviderModel chatProvider; +// bool loader = true; +// +// @override +// void initState() { +// super.initState(); +// } +// +// Future init() async { +// // widget.isVideoCall ? callProvider!.isVideoCall = true : callProvider!.isVideoCall = false; +// widget.isVideoCall = true; +// callProvider!.isOutGoingCall = true; +// // IosCallPayload payload = IosCallPayload( +// // incomingCallerId: widget.outGoingCallData.callerId.toString(), +// // incomingCallerName: widget.outGoingCallData.callerName, +// // incomingCallReciverId: widget.outGoingCallData.receiverId.toString(), +// // incomingCallType: widget.outGoingCallData.callType, +// // uuid: "", +// // callData: widget.outGoingCallData.toRawJson()); +// // await Utils.saveStringFromPrefs("iosCallPayload", jsonEncode(payload)); +// await callProvider!.initLocalCamera(callData: widget.outGoingCallData); +// loader = false; +// } +// +// @override +// void dispose() { +// super.dispose(); +// } +// +// @override +// Widget build(BuildContext context) { +// callProvider = Provider.of(context, listen: false); +// init(); +// return Scaffold( +// body: Consumer(builder: (BuildContext context, ChatCallProvider chatcp, Widget? child) { +// return loader +// ? const Center( +// child: CircularProgressIndicator(), +// ) +// : 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, +// ), +// ), +// child: Column( +// crossAxisAlignment: CrossAxisAlignment.start, +// mainAxisSize: MainAxisSize.max, +// children: [ +// SizedBox( +// height: 40, +// ), +// 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, +// ), +// SizedBox( +// height: 10, +// ), +// Text( +// widget.outGoingCallData!.receiverName.toString().replaceAll(".", " "), +// 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, +// ), +// ], +// ), +// ), +// ), +// ], +// ), +// 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: chatcp.isUserOnline).then((bool value) { +// if (value) { +// Navigator.of(context).pop(); +// } +// }); +// }, +// 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, +// ), +// ), +// ], +// ), +// ), +// ], +// ), +// ), +// ), +// ), +// ), +// ], +// ); +// }), +// ); +// } +// +// BoxDecoration cardRadius(double radius, {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), blurRadius: elevation ?? 27, offset: const Offset(-2, 3))], +// ); +// } +// } diff --git a/lib/voipcall/provider/chat_call_provider.dart b/lib/voipcall/provider/chat_call_provider.dart index ec1adca1..6f53e9dd 100644 --- a/lib/voipcall/provider/chat_call_provider.dart +++ b/lib/voipcall/provider/chat_call_provider.dart @@ -2,22 +2,17 @@ import 'dart:async'; import 'dart:convert'; import 'dart:io'; -import 'package:diplomaticquarterapp/app_state/app_state.dart'; -import 'package:diplomaticquarterapp/core/service/base_service.dart'; import 'package:diplomaticquarterapp/locator.dart'; -import 'package:diplomaticquarterapp/routes.dart'; +import 'package:diplomaticquarterapp/main.dart'; import 'package:diplomaticquarterapp/uitl/navigation_service.dart'; +import 'package:diplomaticquarterapp/uitl/utils.dart'; import 'package:diplomaticquarterapp/voipcall/call/chat_incoming_call_screen.dart'; -import 'package:diplomaticquarterapp/voipcall/consts.dart'; import 'package:diplomaticquarterapp/voipcall/model/call.dart'; import 'package:diplomaticquarterapp/voipcall/model/get_single_user_chat_call.dart'; -import 'package:diplomaticquarterapp/voipcall/model/get_user_login_token.dart' as getUserToken; import 'package:diplomaticquarterapp/voipcall/model/webrtc_payloads.dart'; 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:http/http.dart' as http; import 'package:http/http.dart'; import 'package:just_audio/just_audio.dart'; import 'package:logging/logging.dart'; @@ -101,65 +96,65 @@ class ChatCallProvider with ChangeNotifier, DiagnosticableTreeMixin { // } //{"id":341682,"userName":"Aamir.Muhammad","email":"Aamir.Muhammad@cloudsolutions.com.sa","phone":null,"title":"Aamir Saleem Ahmad Dost Muhammad","token":"eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJuYW1laWQiOiIzNDE2ODIiLCJlbWFpbCI6IkFhbWlyLk11aGFtbWFkQGNsb3Vkc29sdXRpb25zLmNvbS5zYSIsImh0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vd3MvMjAwOC8wNi9pZGVudGl0eS9jbGFpbXMvdXNlcmRhdGEiOiJBYW1pci5NdWhhbW1hZCIsIm5iZiI6MTcwNzIwNTAyMywiZXhwIjoxNzA3MjkxNDIzLCJpYXQiOjE3MDcyMDUwMjN9.Zz2bcsMwiLAAWGZh2E_p5Qs6ItMt0JHhDFI_0DLdggCQtt6HHcT4n8nvqMZx-uYr3jLwqhA_IAjTuaCeSE15sw","isDomainUser":true,"isActiveCode":false,"encryptedUserId":"nn7RkYzbnQc=","encryptedUserName":"/QruOyp4QMcmNXKZlljUgg=="} - Future getHubConnection() async { - AppState().chatDetails = getUserToken.UserAutoLoginModel( - response: getUserToken.Response.fromJson({ - "id": 341682, - "userName": "Aamir.Muhammad", - "email": "Aamir.Muhammad@cloudsolutions.com.sa", - "phone": null, - "title": "Aamir Saleem Ahmad Dost Muhammad", - "token": - "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJuYW1laWQiOiIzNDE2ODIiLCJlbWFpbCI6IkFhbWlyLk11aGFtbWFkQGNsb3Vkc29sdXRpb25zLmNvbS5zYSIsImh0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vd3MvMjAwOC8wNi9pZGVudGl0eS9jbGFpbXMvdXNlcmRhdGEiOiJBYW1pci5NdWhhbW1hZCIsIm5iZiI6MTcwODI1NjI5NywiZXhwIjoxNzA4MzQyNjk3LCJpYXQiOjE3MDgyNTYyOTd9.Y-QDVbSbPzcMVkHyIT06WgM0EsKH183hASZrIsXGkFOR_XZcqCJS-CrgdN0nOtxCWV6wd01dgfhMTNTZhybwiQ", - "isDomainUser": true, - "isActiveCode": false, - "encryptedUserId": "nn7RkYzbnQc=", - "encryptedUserName": "/QruOyp4QMcmNXKZlljUgg==" - }), - ); - String to = "dfK3ZqFD-BTlJLnuf1F5Cw"; - HubConnection hub; - HttpConnectionOptions httpOp = HttpConnectionOptions(skipNegotiation: false, logMessageContent: true); - // hub = HubConnectionBuilder() - // .withUrl(ApiConsts.chatHubConnectionUrl + "?UserId=${AppState().chatDetails!.response!.id}&source=Desktop&access_token=${AppState().chatDetails!.response!.token}", options: httpOp) - // .withAutomaticReconnect(retryDelays: [2000, 5000, 10000, 20000]).build(); - var urlWithParams = "https://ms.hmg.com/livecare/liveCareHub?UserID=4767770&ProjectId=15&IsAdmin=false&To=$to"; - print("ChatHubURL:::: " + urlWithParams); - hub = await HubConnectionBuilder().withUrl(urlWithParams, options: httpOp).withAutomaticReconnect(retryDelays: [2000, 5000, 10000, 20000]).build(); - return hub; - } +// Future getHubConnection() async { +// AppState().chatDetails = getUserToken.UserAutoLoginModel( +// response: getUserToken.Response.fromJson({ +// "id": 341682, +// "userName": "Aamir.Muhammad", +// "email": "Aamir.Muhammad@cloudsolutions.com.sa", +// "phone": null, +// "title": "Aamir Saleem Ahmad Dost Muhammad", +// "token": +// "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJuYW1laWQiOiIzNDE2ODIiLCJlbWFpbCI6IkFhbWlyLk11aGFtbWFkQGNsb3Vkc29sdXRpb25zLmNvbS5zYSIsImh0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vd3MvMjAwOC8wNi9pZGVudGl0eS9jbGFpbXMvdXNlcmRhdGEiOiJBYW1pci5NdWhhbW1hZCIsIm5iZiI6MTcwODI1NjI5NywiZXhwIjoxNzA4MzQyNjk3LCJpYXQiOjE3MDgyNTYyOTd9.Y-QDVbSbPzcMVkHyIT06WgM0EsKH183hASZrIsXGkFOR_XZcqCJS-CrgdN0nOtxCWV6wd01dgfhMTNTZhybwiQ", +// "isDomainUser": true, +// "isActiveCode": false, +// "encryptedUserId": "nn7RkYzbnQc=", +// "encryptedUserName": "/QruOyp4QMcmNXKZlljUgg==" +// }), +// ); +// String to = "dfK3ZqFD-BTlJLnuf1F5Cw"; +// HubConnection hub; +// HttpConnectionOptions httpOp = HttpConnectionOptions(skipNegotiation: false, logMessageContent: true); +// // hub = HubConnectionBuilder() +// // .withUrl(ApiConsts.chatHubConnectionUrl + "?UserId=${AppState().chatDetails!.response!.id}&source=Desktop&access_token=${AppState().chatDetails!.response!.token}", options: httpOp) +// // .withAutomaticReconnect(retryDelays: [2000, 5000, 10000, 20000]).build(); +// var urlWithParams = "https://ms.hmg.com/livecare/liveCareHub?UserID=4767770&ProjectId=15&IsAdmin=false&To=$to"; +// print("ChatHubURL:::: " + urlWithParams); +// hub = await HubConnectionBuilder().withUrl(urlWithParams, options: httpOp).withAutomaticReconnect(retryDelays: [2000, 5000, 10000, 20000]).build(); +// return hub; +// } - Future makeCall({required String callType}) async { - Map json = { - "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": 266642, - "receiverName": "Muhammad Alam", - "receiverEmail": "Muhamad.Alam@cloudsolutions.com.sa", - "receiverTitle": "Muhammad Alam", - "receiverPhone": "123456789", - "title": "Muhammad Alam", - "callType": callType == "VIDEO" ? "Video" : "Audio", - }; - CallDataModel res = CallDataModel.fromJson(json); - return res; - } + // Future makeCall({required String callType}) async { + // Map json = { + // "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": 266642, + // "receiverName": "Muhammad Alam", + // "receiverEmail": "Muhamad.Alam@cloudsolutions.com.sa", + // "receiverTitle": "Muhammad Alam", + // "receiverPhone": "123456789", + // "title": "Muhammad Alam", + // "callType": callType == "VIDEO" ? "Video" : "Audio", + // }; + // CallDataModel res = CallDataModel.fromJson(json); + // return res; + // } - void registerCallListners() { - 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); - } + // void registerCallListners() { + // 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); + // } // Audio Constraints Map audioConstraints = { @@ -170,295 +165,295 @@ class ChatCallProvider with ChangeNotifier, DiagnosticableTreeMixin { "audio": true, }; - Future init() async { - _pc = await creatOfferWithCon(); - Future.delayed(const Duration(seconds: 2), () { - connectIncomingCall(); - }); - } + // Future init() async { + // _pc = await creatOfferWithCon(); + // Future.delayed(const Duration(seconds: 2), () { + // connectIncomingCall(); + // }); + // } ///////////////////////////////////////////////OutGoing Call//////////////////////////////////////////////////// + // + // Future initLocalCamera({callData, bool isIncomingCall = false}) async { + // isCallEnded = false; + // outGoingCallData = callData; + // await initStreams(); + // await startCall(); + // _pc = await creatOfferWithCon(); + // connectOutgoing(); + // notifyListeners(); + // } + // + // void connectOutgoing() { + // isOutGoingCall = true; + // // notifyListeners(); + // } + // + // Future startCall() 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); + // } - Future initLocalCamera({callData, bool isIncomingCall = false}) async { - isCallEnded = false; - outGoingCallData = callData; - await initStreams(); - await startCall(); - _pc = await creatOfferWithCon(); - connectOutgoing(); - notifyListeners(); - } - - void connectOutgoing() { - isOutGoingCall = true; - // notifyListeners(); - } - - Future startCall() 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); - } - - // 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)); - } - - 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) { - print("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; - if (Platform.isIOS) { - Future.delayed(Duration(seconds: 2), () { - Navigator.pushReplacement( - locator().navigatorKey.currentContext!, - MaterialPageRoute( - builder: (BuildContext context) => StartCallPage(), - )); - }); - } else { - Navigator.pushReplacement( - locator().navigatorKey.currentContext!, - MaterialPageRoute( - builder: (BuildContext context) => StartCallPage(), - )); - } - } - } - } - notifyListeners(); - } - } - - 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(); - } + // // 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)); + // } + // + // 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) { + // print("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; + // if (Platform.isIOS) { + // Future.delayed(Duration(seconds: 2), () { + // Navigator.pushReplacement( + // locator().navigatorKey.currentContext!, + // MaterialPageRoute( + // builder: (BuildContext context) => StartCallPage(), + // )); + // }); + // } else { + // Navigator.pushReplacement( + // locator().navigatorKey.currentContext!, + // MaterialPageRoute( + // builder: (BuildContext context) => StartCallPage(), + // )); + // } + // } + // } + // } + // notifyListeners(); + // } + // } + // + // 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(); + // } //////////////////////////// OutGoing Call End /////////////////////////////////////// - Future endCall({bool? isUserOnline}) async { - if (isIncomingCall) { - print("-----------------------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; - isAudioCall = false; - - if (isCallConnected) { - if (_pc!.connectionState == RTCPeerConnectionState.RTCPeerConnectionStateConnected) { - if (kDebugMode) { - print("------------------ PC Stopped ----------------------------"); - } - _pc!.close(); - _pc!.dispose(); - } - } - if (remoteRenderer != null) { - remoteRenderer!.dispose(); - remoteRenderer = null; - } - if (localVideoRenderer != null) { - localVideoRenderer!.dispose(); - localVideoRenderer = null; - } - - if (_localStream != null) { - _localStream!.dispose(); - _localStream = null; - } - if (chatHubConnection != null && !isUserOnline!) { - chatHubConnection!.stop(); - } - await FlutterCallkitIncoming.endAllCalls(); - return true; - } else { - if (isOutGoingCall) { - 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); - } - isCallStarted = false; - isVideoCall = false; - isCamOff = false; - isMicOff = false; - isLoudSpeaker = false; - if (isCallConnected) { - if (_pc!.connectionState == RTCPeerConnectionState.RTCPeerConnectionStateConnected) { - _pc!.close(); - _pc!.dispose(); - } - } - if (remoteRenderer != null) { - remoteRenderer!.dispose(); - remoteRenderer = null; - } - if (localVideoRenderer != null) { - localVideoRenderer!.dispose(); - localVideoRenderer = null; - } - - if (_localStream != null) { - _localStream!.dispose(); - _localStream = null; - } - isOutGoingCall = false; - isIncomingCall = false; - isAudioCall = false; - return true; - } - } + // Future endCall({bool? isUserOnline}) async { + // if (isIncomingCall) { + // print("-----------------------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; + // isAudioCall = false; + // + // if (isCallConnected) { + // if (_pc!.connectionState == RTCPeerConnectionState.RTCPeerConnectionStateConnected) { + // if (kDebugMode) { + // print("------------------ PC Stopped ----------------------------"); + // } + // _pc!.close(); + // _pc!.dispose(); + // } + // } + // if (remoteRenderer != null) { + // remoteRenderer!.dispose(); + // remoteRenderer = null; + // } + // if (localVideoRenderer != null) { + // localVideoRenderer!.dispose(); + // localVideoRenderer = null; + // } + // + // if (_localStream != null) { + // _localStream!.dispose(); + // _localStream = null; + // } + // if (chatHubConnection != null && !isUserOnline!) { + // chatHubConnection!.stop(); + // } + // await FlutterCallkitIncoming.endAllCalls(); + // return true; + // } else { + // if (isOutGoingCall) { + // 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); + // } + // isCallStarted = false; + // isVideoCall = false; + // isCamOff = false; + // isMicOff = false; + // isLoudSpeaker = false; + // if (isCallConnected) { + // if (_pc!.connectionState == RTCPeerConnectionState.RTCPeerConnectionStateConnected) { + // _pc!.close(); + // _pc!.dispose(); + // } + // } + // if (remoteRenderer != null) { + // remoteRenderer!.dispose(); + // remoteRenderer = null; + // } + // if (localVideoRenderer != null) { + // localVideoRenderer!.dispose(); + // localVideoRenderer = null; + // } + // + // if (_localStream != null) { + // _localStream!.dispose(); + // _localStream = null; + // } + // isOutGoingCall = false; + // isIncomingCall = false; + // isAudioCall = false; + // 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) { - print("res: " + items.toString()); - } - CallSessionPayLoad data = CallSessionPayLoad.fromJson(jsonDecode(items.first.toString())); - RTCSessionDescription description = RTCSessionDescription(data.sdp!.sdp, 'answer'); - _pc!.setRemoteDescription(description); - // } - } - - void onHangUpAsync(List? params) { - print("--------------------- onHangUp ASYNC ---------------------------------"); + // 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) { + // print("res: " + items.toString()); + // } + // CallSessionPayLoad data = CallSessionPayLoad.fromJson(jsonDecode(items.first.toString())); + // RTCSessionDescription description = RTCSessionDescription(data.sdp!.sdp, 'answer'); + // _pc!.setRemoteDescription(description); + // // } + // } - dynamic items = params!.toList(); - // if (kDebugMode) { - // logger.i("res: " + items.toString()); - // } - if (items[0]["id"] != AppState().chatDetails!.response!.id!) { - if (kDebugMode) { - print("Call Ended By Other User"); - } - if (isIncomingCall) { - endCall(isUserOnline: isUserOnline).then((bool value) { - if (isCallConnected && isUserOnline) { - isCallConnected = false; - if (!AppState().isLogged) { - Navigator.of(locator().navigatorKey.currentContext!).pop(); - } else { - Navigator.of(locator().navigatorKey.currentContext!).popUntil(ModalRoute.withName(HOME)); - } - } else { - Navigator.of(locator().navigatorKey.currentContext!).pop(); - } - }); - } else { - if (isOutGoingCall) { - endCall(isUserOnline: isUserOnline).then((bool value) { - if (isCallConnected && isUserOnline) { - isCallConnected = false; - Navigator.of(locator().navigatorKey.currentContext!).popUntil(ModalRoute.withName(HOME)); - } else { - Navigator.of(locator().navigatorKey.currentContext!).pop(); - } - }); - } - } - } else { - if (kDebugMode) { - print("Call Ended By Me"); - } - if (isOutGoingCall) { - if (isCallConnected && isUserOnline) { - isCallConnected = false; - Navigator.of(locator().navigatorKey.currentContext!).popUntil(ModalRoute.withName(HOME)); - } else { - Navigator.of(locator().navigatorKey.currentContext!).pop(); - } - } - } - // endCall(isUserOnline: isUserOnline).then((bool value) { - // if (isCallConnected && isUserOnline) { - // Navigator.of(AppRoutes.navigatorKey.currentContext!).popUntil(ModalRoute.withName(AppRoutes.chatDetailed)); - // isCallConnected = false; - // } - // if (items[0]["id"] != AppState().chatDetails!!.response!.id && !AppState().isBackgroundCall) { - // if (kDebugMode) { - // print("Popped Due to Another User"); - // } - // if (AppState().isBackgroundCall) { - // Navigator.of(AppRoutes.navigatorKey.currentContext!).pop(); - // // Navigator.of(AppRoutes.navigatorKey.currentContext!).popUntil(ModalRoute.withName(AppRoutes.login)); - // } else { - // Navigator.of(AppRoutes.navigatorKey.currentContext!).popUntil(ModalRoute.withName(AppRoutes.chat)); - // } - // } - // if (AppState().isBackgroundCall) { - // Navigator.of(AppRoutes.navigatorKey.currentContext!).pop(); - // } - // - notifyListeners(); - isCallEnded = true; - // }); - } + // void onHangUpAsync(List? params) { + // print("--------------------- onHangUp ASYNC ---------------------------------"); + // + // dynamic items = params!.toList(); + // // if (kDebugMode) { + // // logger.i("res: " + items.toString()); + // // } + // if (items[0]["id"] != AppState().chatDetails!.response!.id!) { + // if (kDebugMode) { + // print("Call Ended By Other User"); + // } + // if (isIncomingCall) { + // endCall(isUserOnline: isUserOnline).then((bool value) { + // if (isCallConnected && isUserOnline) { + // isCallConnected = false; + // if (!AppState().isLogged) { + // Navigator.of(locator().navigatorKey.currentContext!).pop(); + // } else { + // Navigator.of(locator().navigatorKey.currentContext!).popUntil(ModalRoute.withName(HOME)); + // } + // } else { + // Navigator.of(locator().navigatorKey.currentContext!).pop(); + // } + // }); + // } else { + // if (isOutGoingCall) { + // endCall(isUserOnline: isUserOnline).then((bool value) { + // if (isCallConnected && isUserOnline) { + // isCallConnected = false; + // Navigator.of(locator().navigatorKey.currentContext!).popUntil(ModalRoute.withName(HOME)); + // } else { + // Navigator.of(locator().navigatorKey.currentContext!).pop(); + // } + // }); + // } + // } + // } else { + // if (kDebugMode) { + // print("Call Ended By Me"); + // } + // if (isOutGoingCall) { + // if (isCallConnected && isUserOnline) { + // isCallConnected = false; + // Navigator.of(locator().navigatorKey.currentContext!).popUntil(ModalRoute.withName(HOME)); + // } else { + // Navigator.of(locator().navigatorKey.currentContext!).pop(); + // } + // } + // } + // // endCall(isUserOnline: isUserOnline).then((bool value) { + // // if (isCallConnected && isUserOnline) { + // // Navigator.of(AppRoutes.navigatorKey.currentContext!).popUntil(ModalRoute.withName(AppRoutes.chatDetailed)); + // // isCallConnected = false; + // // } + // // if (items[0]["id"] != AppState().chatDetails!!.response!.id && !AppState().isBackgroundCall) { + // // if (kDebugMode) { + // // print("Popped Due to Another User"); + // // } + // // if (AppState().isBackgroundCall) { + // // Navigator.of(AppRoutes.navigatorKey.currentContext!).pop(); + // // // Navigator.of(AppRoutes.navigatorKey.currentContext!).popUntil(ModalRoute.withName(AppRoutes.login)); + // // } else { + // // Navigator.of(AppRoutes.navigatorKey.currentContext!).popUntil(ModalRoute.withName(AppRoutes.chat)); + // // } + // // } + // // if (AppState().isBackgroundCall) { + // // Navigator.of(AppRoutes.navigatorKey.currentContext!).pop(); + // // } + // // + // notifyListeners(); + // isCallEnded = true; + // // }); + // } // Future OnIncomingCallAsync(List? params) async { // print("--------------------- On Incoming Call ---------------------------------------"); @@ -532,32 +527,32 @@ class ChatCallProvider with ChangeNotifier, DiagnosticableTreeMixin { //// Invoke Methods - Future invoke({required String invokeMethod, required int currentUserID, required int targetUserID, var data, int userStatus = 1, var debugData}) async { - List args = []; - 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 - } 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) { - print(e); - } - } + // Future invoke({required String invokeMethod, required int currentUserID, required int targetUserID, var data, int userStatus = 1, var debugData}) async { + // List args = []; + // 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 + // } 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) { + // print(e); + // } + // } void stopListeners() async { chatHubConnection!.off('OnCallDeclinedAsync'); @@ -586,87 +581,87 @@ class ChatCallProvider with ChangeNotifier, DiagnosticableTreeMixin { //////////////////// 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!); - //Changed By Aamir - _localStream?.getTracks().forEach((track) { - pc.addTrack(track, _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) { - print("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) { - print("rtc ice gathering state: " + state.name); - }; - pc.onIceConnectionState = (RTCIceConnectionState state) { - if (RTCIceConnectionState.RTCIceConnectionStateFailed == state || - RTCIceConnectionState.RTCIceConnectionStateDisconnected == state || - RTCIceConnectionState.RTCIceConnectionStateClosed == state) { - print("Ice Connection State:" + state.name); - - // endCall().then((value) { - // notifyListeners(); - // }); - } - }; - // pc!.onRenegotiationNeeded = _onRenegotiate; - return pc; - } + // 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!); + // //Changed By Aamir + // _localStream?.getTracks().forEach((track) { + // pc.addTrack(track, _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) { + // print("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) { + // print("rtc ice gathering state: " + state.name); + // }; + // pc.onIceConnectionState = (RTCIceConnectionState state) { + // if (RTCIceConnectionState.RTCIceConnectionStateFailed == state || + // RTCIceConnectionState.RTCIceConnectionStateDisconnected == state || + // RTCIceConnectionState.RTCIceConnectionStateClosed == state) { + // print("Ice Connection State:" + state.name); + // + // // endCall().then((value) { + // // notifyListeners(); + // // }); + // } + // }; + // // pc!.onRenegotiationNeeded = _onRenegotiate; + // return pc; + // } // void _onRenegotiate() async { // try { @@ -686,17 +681,17 @@ class ChatCallProvider with ChangeNotifier, DiagnosticableTreeMixin { // } // } - Future _createOffer() async { - RTCSessionDescription description = await _pc!.createOffer(); - // _offer = true; - return description; - } - - Future _createAnswer() async { - RTCSessionDescription description = await _pc!.createAnswer(); - // _offer = false; - return description; - } + // 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 //////////////////// @@ -751,20 +746,18 @@ class ChatCallProvider with ChangeNotifier, DiagnosticableTreeMixin { try { _localStream = await navigator.mediaDevices.getUserMedia({ 'audio': true, - 'video': - //isVideoCall? - { + 'video': { 'mandatory': { 'minWidth': '640', // Provide your own width, height and frame rate here 'minHeight': '480', - 'minFrameRate': '30', + 'minFrameRate': '25', }, 'facingMode': 'user', 'optional': [], "audio": true, } - // : false }); + _localStream!.getAudioTracks().first.enableSpeakerphone(true); localVideoRenderer!.srcObject = _localStream; localVideoRenderer!.value = (const RTCVideoValue( width: 200, @@ -775,34 +768,32 @@ class ChatCallProvider with ChangeNotifier, DiagnosticableTreeMixin { } catch (e) { print("Failed to get user media: $e"); } - - // localVideoRenderer.srcObject = _localStream; await remoteRenderer!.initialize(); notifyListeners(); } - Future startIncomingCallViaKit({bool isVCall = true, var inCallData}) async { - AppSharedPrefs().setStringFromPrefs("isIncomingCall", "false"); - if (isVCall) { - isVideoCall = isVCall; - } else { - isAudioCall = true; - } - await initStreams(); - isIncomingCall = true; - incomingCallData = SingleUserChatModel.fromJson(inCallData); - loudOn(); - // notifyListeners(); - } - - void connectIncomingCall() { - invoke(invokeMethod: "answerCallAsync", currentUserID: AppState().getchatUserDetails.response!.id!, targetUserID: incomingCallData!.targetUserId!); - isIncomingCallLoader = false; - isIncomingCall = true; - // isVideoCall = true; + // Future startIncomingCallViaKit({bool isVCall = true, var inCallData}) async { + // AppSharedPrefs().setStringFromPrefs("isIncomingCall", "false"); + // if (isVCall) { + // isVideoCall = isVCall; + // } else { + // isAudioCall = true; + // } + // await initStreams(); + // isIncomingCall = true; + // incomingCallData = SingleUserChatModel.fromJson(inCallData); + // loudOn(); + // // notifyListeners(); + // } - notifyListeners(); - } + // void connectIncomingCall() { + // invoke(invokeMethod: "answerCallAsync", currentUserID: AppState().getchatUserDetails.response!.id!, targetUserID: incomingCallData!.targetUserId!); + // isIncomingCallLoader = false; + // isIncomingCall = true; + // // isVideoCall = true; + // + // notifyListeners(); + // } // void startRecording() async { // print("=-=-=-=-=-=-= Call Recoding Started -=-=-=-=-=-=-=-=-==-="); @@ -838,77 +829,271 @@ class ChatCallProvider with ChangeNotifier, DiagnosticableTreeMixin { // WebRtc -// If you want only to log out the message for the higer level hub protocol: - final hubProtLogger = Logger("SignalR - hub"); final transportProtLogger = Logger("SignalR - transport"); late Logger _logger; - late StreamSubscription _logMessagesSub; - void _handleLogMessage(LogRecord msg) { - print(msg.message); + RTCPeerConnection? pCon; + String? _doctorID; + String? _patientID; + + String? get doctorID => _doctorID; + + set doctorID(String? value) { + _doctorID = value; + } + + String? get patientID => _patientID; + + set patientID(String? value) { + _patientID = value; } void _httpClientCreateCallback(Client httpClient) { HttpOverrides.global = HttpOverrideCertificateVerificationInDev(); } - // Future buildHubConnection() async { - // try { - // chatHubConnection = await HubConnectionBuilder().withUrl(urlWithParams, options: httpOp).build(); - // await chatHubConnection!.start(); - // print(chatHubConnection!.state); - // chatHubConnection!.onclose(({error}) { - // print("Connection Closed"); - // }); - // // if (chatHubConnection!.state == HubConnectionState.Connected) { - // // print("Success Chat Con ID::: " + chatHubConnection!.connectionId.toString()); - // // if (kDebugMode) { - // // print("Hub Conn: Startedddddddd"); - // // } - // // //registerCallListners(); - // // } - // } catch (e) { - // print(e.toString()); - // Utils.showErrorToast(e.toString()); - // } - // } + Future buildHubConnection() async { + _logger = Logger("ChatPageViewModel"); + final logger = _logger; + + if (chatHubConnection != null) { + chatHubConnection!.stop(); + chatHubConnection = null; + } + if (doctorID != null) { + try { + final httpConnectionOptions = + new HttpConnectionOptions(httpClient: WebSupportingHttpClient(logger, httpClientCreateCallback: _httpClientCreateCallback), logger: logger, logMessageContent: true); + + var urlWithParams = "https://ms.hmg.com/livecare/liveCareHub?UserID=4767770&ProjectId=15&IsAdmin=false&To=$doctorID"; + chatHubConnection = + await HubConnectionBuilder().withUrl(urlWithParams, options: httpConnectionOptions).withAutomaticReconnect(retryDelays: [2000, 5000, 10000, 20000]).configureLogging(logger).build(); + + chatHubConnection!.onclose(({error}) { + print("Connection Closed"); + Utils.showErrorToast(error.toString()); + }); + register(); + if (chatHubConnection!.state == HubConnectionState.Disconnected) { + await chatHubConnection!.start(); + print(chatHubConnection!.state); + print("Success Chat Con ID::: " + chatHubConnection!.connectionId.toString()); + } + if (chatHubConnection!.state == HubConnectionState.Connected) { + if (chatHubConnection != null) { + print(chatHubConnection!.connectionId); + try { + chatHubConnection!.invoke("Call_Accept", args: [ + {"UserID": 4767770} + ]); + // .onError((error, stackTrace) { + // Utils.showErrorToast(error.toString()); + // }); + } catch (e) { + print(e); + } + } + } + } catch (e) { + print(e.toString()); + Utils.showErrorToast(e.toString()); + await buildHubConnection(); + } + } else { + Utils.showErrorToast("Doctor ID is not correct"); + } + } - handleRecivedOffer(List? val) { - print("----------Event Received ----------"); - print(val); + void register() async { + chatHubConnection!.on("pre-offer", handlePreOffer); + chatHubConnection!.on("OnOffer", handleOnOffer); + chatHubConnection!.on("IceCandidate", handleIceCandidate); + // New Events + chatHubConnection!.on("Call_Decline", handleCallDecline); + chatHubConnection!.on("Call_NoAnswer", handleNoAnswerCall); + chatHubConnection!.on("CallCompleted", handleCallComplete); } - Future openChatConnection() async { - _logger = Logger("Demo"); - final logger = _logger; - if (chatHubConnection == null) { - final httpConnectionOptions = HttpConnectionOptions(httpClient: WebSupportingHttpClient(logger, httpClientCreateCallback: _httpClientCreateCallback), logger: logger, logMessageContent: true); - Logger.root.level = Level.ALL; - _logMessagesSub = Logger.root.onRecord.listen(_handleLogMessage); - String to = "aXvFIMTEFRAKLJv5flIEWw"; - var urlWithParams = "https://ms.hmg.com/livecare/liveCareHub?UserID=4767770&ProjectId=15&IsAdmin=false&To=$to"; - print("ChatHubURL:::: " + urlWithParams); - chatHubConnection = - await HubConnectionBuilder().withUrl(urlWithParams, options: httpConnectionOptions).withAutomaticReconnect(retryDelays: [2000, 5000, 10000, 20000]).configureLogging(logger).build(); + handlePreOffer(List? params) async { + print("----------Event Pre Offer Received ----------"); + dynamic items = params!.toList(); + print("Doctor ID : " + items[0]['from'].toString()); + print("Patient ID: " + items[0]['to'].toString()); + doctorID = items[0]['from']; + patientID = items[0]['to']; + initStreams(); + createPConnection(); + sendPreAnswerOffer(); + } + + handleOnOffer(List? params) async { + print("----------Event On Offer Received ----------"); + dynamic items = params!.toList(); + var data = jsonDecode(items[0]["offer"]); + _localStream?.getTracks().forEach((track) { + pCon!.addTrack(track, _localStream!); + }); + await pCon!.setRemoteDescription(RTCSessionDescription(data["sdp"], data["type"])); + RTCSessionDescription description = await pCon!.createAnswer(); + await pCon!.setLocalDescription(description); + var payload = { + "to": doctorID, + "callerSocketId": patientID, + "answer": "${json.encode(description.toMap())}", + }; + if (chatHubConnection!.state == HubConnectionState.Connected) { + print("---------Answer Offer Invoke --------"); + await chatHubConnection!.invoke("OnAnswerOffer", args: [payload]).onError((error, stackTrace) { + print("error sending offer answer"); + Utils.showErrorToast(error.toString()); + }); } + startCallByRTC(); + Future.delayed(Duration(seconds: 5), () { + Navigator.push( + locator().navigatorKey.currentContext!, + MaterialPageRoute( + builder: (BuildContext context) => StartCallPage(), + )); + }); + } - print(" ------------ Connection State --------------" + chatHubConnection!.state.toString()); + handleIceCandidate(List? params) async { + print("----------Event Ice Candidate Received ----------"); + dynamic items = params!.toList(); + var val = jsonDecode(items[0]["candidate"]); + RemoteIceCandidatePayLoad data = await RemoteIceCandidatePayLoad( + target: 00000, candidate: Candidate(candidate: val["candidate"], sdpMid: val["sdpMid"], sdpMLineIndex: val["sdpMLineIndex"], usernameFragment: val["usernameFragment"])); + if (pCon != null) { + pCon!.addCandidate(RTCIceCandidate(data.candidate!.candidate, data.candidate!.sdpMid, data.candidate!.sdpMLineIndex)); + } + } - if (chatHubConnection!.state != HubConnectionState.Connected) { - try { - await chatHubConnection!.start(); - print(" ------------ Connection State --------------" + chatHubConnection!.state.toString()); - print("Connection Stablished --------------"); - } catch (e) { - print(e); + handleCallDecline(List? params) { + print("----------handle Call Decline Received ----------"); + dynamic items = params!.toList(); + logger.d(items); + } + + handleNoAnswerCall(List? params) { + print("----------handle No Answer Received ----------"); + dynamic items = params!.toList(); + logger.d(items); + } + + handleCallComplete(List? params) { + print("----------handle Call Complete Received ----------"); + dynamic items = params!.toList(); + logger.d(items); + + isCallStarted = false; + isVideoCall = false; + isCamOff = false; + isMicOff = false; + isLoudSpeaker = false; + isIncomingCall = false; + isOutGoingCall = false; + isAudioCall = false; + if (pCon!.connectionState == RTCPeerConnectionState.RTCPeerConnectionStateConnected) { + pCon!.close(); + pCon!.dispose(); + } + + if (remoteRenderer != null) { + remoteRenderer!.dispose(); + remoteRenderer = null; + } + if (localVideoRenderer != null) { + localVideoRenderer!.dispose(); + localVideoRenderer = null; + } + + if (_localStream != null) { + _localStream!.dispose(); + _localStream = null; + } + if (chatHubConnection != null && !isUserOnline) { + chatHubConnection!.stop(); + } + } + + void createPConnection() 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', + } + ], + "iceCandidatePoolSize": 10 + }; + Map offerSdpConstraints = { + 'mandatory': { + 'OfferToReceiveAudio': true, + 'OfferToReceiveVideo': true, + }, + 'optional': [] + }; + pCon = await createPeerConnection(configuration, offerSdpConstraints); + + pCon!.onConnectionState = (RTCPeerConnectionState state) {}; + pCon!.onAddStream = (MediaStream stream) { + remoteRenderer!.srcObject = stream; + notifyListeners(); + }; + + pCon!.onIceCandidate = (RTCIceCandidate e) async { + if (e.candidate != null) { + await pCon!.addCandidate(e); + var data = {"target": doctorID, "callerSocketId": doctorID, "from": patientID, "calleePersonalCode": patientID, "to": doctorID, "candidate": "${json.encode(e.toMap())}"}; + if (chatHubConnection!.state == HubConnectionState.Connected) { + await chatHubConnection!.invoke('IceCandidate', args: [data]).onError((error, stackTrace) { + Utils.showErrorToast(error.toString()); + }); + } + } + }; + + pCon!.onSignalingState = (RTCSignalingState state) { + print("signaling state: " + state.name); + }; + pCon!.onIceGatheringState = (RTCIceGatheringState state) { + print("rtc ice gathering state: " + state.name); + }; + pCon!.onIceConnectionState = (RTCIceConnectionState state) { + if (RTCIceConnectionState.RTCIceConnectionStateFailed == state || + RTCIceConnectionState.RTCIceConnectionStateDisconnected == state || + RTCIceConnectionState.RTCIceConnectionStateClosed == state) { + print("Ice Connection State:" + state.name); } + }; + } + + sendPreAnswerOffer() async { + var data = { + "to": doctorID, + "calleePersonalCode": patientID, + "preOfferAnswer": "", + }; + print(data); + if (chatHubConnection!.state == HubConnectionState.Connected) { + await chatHubConnection!.invoke("SendPreOfferAnswer", args: [data]).onError((error, stackTrace) { + print("error sending pre offer answer"); + Utils.showErrorToast(error.toString()); + }); } + } - print(" ------------ Before Events Register --------------"); - chatHubConnection!.on("pre-offer", handleRecivedOffer); - chatHubConnection!.on("OnOffer", handleRecivedOffer); - chatHubConnection!.on("IceCandidate", handleRecivedOffer); - print(" ------------ After Events Register --------------"); + startCallByRTC() { + isVideoCall = true; + isIncomingCallLoader = false; + isIncomingCall = true; + isCallConnected = true; } } @@ -919,20 +1104,20 @@ class HttpOverrideCertificateVerificationInDev extends HttpOverrides { } } -class ChatService extends BaseService { - Future getUserCallToken({required String userid}) async { - getUserToken.UserAutoLoginModel userLoginResponse = getUserToken.UserAutoLoginModel(); - http.post(Uri.parse("${ApiConsts.chatLoginTokenUrl}externaluserlogin"), body: { - "employeeNumber": userid, - "password": "FxIu26rWIKoF8n6mpbOmAjDLphzFGmpG", - }).then((response) { - userLoginResponse = getUserToken.userAutoLoginModelFromJson(response.body); - }).onError((error, stackTrace) { - hasError = true; - print(error); - super.error = error.toString(); - }); - - return userLoginResponse; - } -} +// class ChatService extends BaseService { +// Future getUserCallToken({required String userid}) async { +// getUserToken.UserAutoLoginModel userLoginResponse = getUserToken.UserAutoLoginModel(); +// http.post(Uri.parse("${ApiConsts.chatLoginTokenUrl}externaluserlogin"), body: { +// "employeeNumber": userid, +// "password": "FxIu26rWIKoF8n6mpbOmAjDLphzFGmpG", +// }).then((response) { +// userLoginResponse = getUserToken.userAutoLoginModelFromJson(response.body); +// }).onError((error, stackTrace) { +// hasError = true; +// print(error); +// super.error = error.toString(); +// }); +// +// return userLoginResponse; +// } +// } diff --git a/lib/widgets/drawer/app_drawer_widget.dart b/lib/widgets/drawer/app_drawer_widget.dart index 07fb9e47..7cb12313 100644 --- a/lib/widgets/drawer/app_drawer_widget.dart +++ b/lib/widgets/drawer/app_drawer_widget.dart @@ -31,7 +31,6 @@ import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart'; import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart'; import 'package:diplomaticquarterapp/uitl/utils.dart'; import 'package:diplomaticquarterapp/uitl/utils_new.dart'; -import 'package:diplomaticquarterapp/voipcall/call/chat_outgoing_call_screen.dart'; import 'package:diplomaticquarterapp/voipcall/provider/chat_call_provider.dart'; import 'package:diplomaticquarterapp/widgets/dialogs/confirm_dialog.dart'; import 'package:diplomaticquarterapp/widgets/text/app_texts_widget.dart'; @@ -461,75 +460,50 @@ class _AppDrawerState extends State { Navigator.of(context).push(FadePage(page: UserAgreementPage())); }, ), - GestureDetector( - onTap: () async { - //Aamir Call - Future micPer = Permission.microphone.request(); - Future camPer = Permission.camera.request(); - if (await micPer.isGranted && await camPer.isGranted) { - // callProv!.buildHubConnection(); - await callProv!.makeCall(callType: "VIDEO").then((value) { - Future.delayed(Duration(seconds: 3), () { - Navigator.push( - context, - MaterialPageRoute( - builder: (BuildContext context) => OutGoingCall( - isVideoCall: value.callType == "VIDEO" ? true : false, - outGoingCallData: value, - ), - ), - ); - }); - }); - } else if (await micPer.isDenied) { - micPer = Permission.microphone.request(); - } else if (await camPer.isDenied) { - camPer = Permission.camera.request(); - } - }, - child: Card( - child: Container( - height: 50, - width: 200, - child: Center(child: Text("Call")), + SizedBox(height: 20), + Padding( + padding: const EdgeInsets.all(8.0), + child: TextField( + decoration: InputDecoration( + border: OutlineInputBorder( + borderSide: BorderSide(width: 2, color: Colors.black), + ), ), + onChanged: (val) { + print(val); + callProv!.doctorID = val; + print(callProv!.doctorID); + }, ), ), - GestureDetector( - onTap: () async { - //Aamir Call - Future micPer = Permission.microphone.request(); - Future camPer = Permission.camera.request(); - if (await micPer.isGranted && await camPer.isGranted) { - await callProv!.openChatConnection(); - // IosCallPayload _iosCallPayload = IosCallPayload( - // uuid: "342h8f=-few-3f23rsd-s-f32-r--sd-3rt-2", - // incomingCallerId: "341682", - // incomingCallReciverId: "266642", - // incomingCallerName: "Aamir.Muhammad", - // incomingCallType: "video"); - // Future.delayed(Duration(seconds: 2), () { - // MaterialPageRoute pageRoute = MaterialPageRoute( - // builder: (BuildContext context) => StartCallPage( - // payload: _iosCallPayload, - // ), - // ); - // Navigator.push(context, pageRoute); - // }); - } else if (await micPer.isDenied) { - micPer = Permission.microphone.request(); - } else if (await camPer.isDenied) { - camPer = Permission.camera.request(); - } - }, - child: Card( - child: Container( - height: 50, - width: 200, - child: Center(child: Text("Receive Call")), + SizedBox(height: 20), + Center( + child: Padding( + padding: const EdgeInsets.all(8.0), + child: ElevatedButton( + style: ButtonStyle( + backgroundColor: MaterialStateProperty.all(Colors.blue), + ), + onPressed: () async { + Future micPer = Permission.microphone.request(); + Future camPer = Permission.camera.request(); + if (await micPer.isGranted && await camPer.isGranted) { + await callProv!.buildHubConnection(); + } else if (await micPer.isDenied) { + micPer = Permission.microphone.request(); + } else if (await camPer.isDenied) { + camPer = Permission.camera.request(); + } + }, + child: Center( + child: Padding( + padding: const EdgeInsets.all(12.0), + child: Text("Receive Call"), + ), + ), ), ), - ), + ) ], )) ],