dev_v3.13.6_voipcall
Aamir Muhammad 2 years ago
parent ecc5454b98
commit 126bb2e056

@ -1,3 +1,5 @@
import 'package:diplomaticquarterapp/voipcall/model/get_user_login_token.dart';
class AppState { class AppState {
static final AppState _instance = AppState._internal(); static final AppState _instance = AppState._internal();
@ -10,4 +12,35 @@ class AppState {
set setLogged(v) => isLogged = v; set setLogged(v) => isLogged = v;
bool get getIsLogged => isLogged; bool get getIsLogged => isLogged;
// Calling
UserAutoLoginModel? chatDetails;
set setchatUserDetails(UserAutoLoginModel details) => chatDetails = details;
UserAutoLoginModel get getchatUserDetails => chatDetails!;
String _iosVoipPlayerID = "";
String get iosVoipPlayerID => _iosVoipPlayerID;
set setiosVoipPlayerID(String value) {
_iosVoipPlayerID = value;
}
bool _isUserOnline = false;
bool get getisUserOnline => _isUserOnline;
set setisUserOnline(bool value) {
_isUserOnline = value;
}
bool _isBackgroundCall = false;
bool get isBackgroundCall => _isBackgroundCall;
set isBackgroundCall(bool value) {
_isBackgroundCall = value;
}
} }

@ -4,11 +4,11 @@ import 'dart:io';
import 'dart:ui'; import 'dart:ui';
import 'package:diplomaticquarterapp/app_state/app_state.dart'; import 'package:diplomaticquarterapp/app_state/app_state.dart';
import 'package:diplomaticquarterapp/models/chat/call.dart';
import 'package:diplomaticquarterapp/models/chat/incoming_call_model.dart';
import 'package:diplomaticquarterapp/voipcall/consts.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_single_user_chat_call.dart';
import 'package:diplomaticquarterapp/voipcall/model/get_user_login_token.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:diplomaticquarterapp/voipcall/provider/chat_call_provider.dart';
import 'package:draggable_widget/draggable_widget.dart'; import 'package:draggable_widget/draggable_widget.dart';
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
@ -20,7 +20,7 @@ import 'package:provider/provider.dart';
bool isCallConnected = false; bool isCallConnected = false;
class StartCallPage extends StatefulWidget { class StartCallPage extends StatefulWidget {
IosCallPayload payload; IosCallPayload? payload;
StartCallPage({this.payload}); StartCallPage({this.payload});
@ -30,7 +30,7 @@ class StartCallPage extends StatefulWidget {
class _StartCallPageState extends State<StartCallPage> { class _StartCallPageState extends State<StartCallPage> {
DragController dragController = DragController(); DragController dragController = DragController();
ChatCallProvider cProv; ChatCallProvider? cProv;
@override @override
void initState() { void initState() {
@ -43,21 +43,21 @@ class _StartCallPageState extends State<StartCallPage> {
} }
void startCall() async { void startCall() async {
IncomingCallModel sessionData; IncomingCallModel? sessionData;
// dynamic calls = await FlutterCallkitIncoming.activeCalls(); // dynamic calls = await FlutterCallkitIncoming.activeCalls();
// if (calls.isNotEmpty) { // 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.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])); // sessionData = IncomingCallModel.fromRawJson(jsonEncode(calls[0]));
if (kDebugMode) { if (kDebugMode) {
print(sessionData.toRawJson()); print(sessionData!.toRawJson());
} }
if (cProv.isUserOnline) { if (cProv!.isUserOnline) {
AppState().isBackgroundCall = true; AppState().isBackgroundCall = true;
if (kDebugMode) { if (kDebugMode) {
print("====== Processing Incoming Call in Online State ========="); print("====== Processing Incoming Call in Online State =========");
} }
await cProv.startIncomingCallViaKit(inCallData: sessionData.extra.callerDetails.toJson(), isVCall: sessionData.extra.callType == "video" ? true : false); await cProv!.startIncomingCallViaKit(inCallData: sessionData!.extra!.callerDetails!.toJson(), isVCall: sessionData.extra!.callType == "video" ? true : false);
cProv.init(); cProv!.init();
isCallConnected = true; isCallConnected = true;
} else { } else {
AppState().isBackgroundCall = true; AppState().isBackgroundCall = true;
@ -65,11 +65,11 @@ class _StartCallPageState extends State<StartCallPage> {
print("====== Processing Incoming Call ========="); print("====== Processing Incoming Call =========");
} }
// cProv.isUserOnline = provider.isUserOnline; // cProv.isUserOnline = provider.isUserOnline;
await cProv.startIncomingCallViaKit(inCallData: sessionData.extra.callerDetails.toJson(), isVCall: sessionData.extra.callType == "video" ? true : false); await cProv!.startIncomingCallViaKit(inCallData: sessionData!.extra!.callerDetails!.toJson(), isVCall: sessionData!.extra!.callType == "video" ? true : false);
try { try {
AppState().setchatUserDetails = UserAutoLoginModel(response: Response.fromJson(sessionData.extra.loginDetails.toJson()), errorResponses: null); AppState().setchatUserDetails = UserAutoLoginModel(response: Response.fromJson(sessionData.extra!.loginDetails!.toJson()), errorResponses: null);
await cProv.buildHubConnection().whenComplete(() { await cProv!.buildHubConnection().whenComplete(() {
cProv.init(); cProv!.init();
isCallConnected = true; isCallConnected = true;
}); });
} catch (e) { } catch (e) {
@ -82,22 +82,22 @@ class _StartCallPageState extends State<StartCallPage> {
} }
void startIosCall() async { void startIosCall() async {
IosCallPayload iosCallPayload = widget.payload; IosCallPayload iosCallPayload = widget.payload!;
var userID = iosCallPayload.incomingCallReciverId; var userID = iosCallPayload.incomingCallReciverId;
var callType = iosCallPayload.incomingCallType; var callType = iosCallPayload.incomingCallType;
SingleUserChatModel inCallData = SingleUserChatModel( SingleUserChatModel inCallData = SingleUserChatModel(
targetUserName: iosCallPayload.incomingCallerName, targetUserName: iosCallPayload.incomingCallerName,
chatEventId: 3, chatEventId: 3,
targetUserId: int.parse(iosCallPayload.incomingCallerId), targetUserId: int.parse(iosCallPayload.incomingCallerId!),
currentUserId: int.parse(userID.toString()), currentUserId: int.parse(userID.toString()),
); );
if (cProv.isUserOnline) { if (cProv!.isUserOnline) {
AppState().isBackgroundCall = true; AppState().isBackgroundCall = true;
if (kDebugMode) { if (kDebugMode) {
print("====== Processing Incoming Call in Online State ========="); print("====== Processing Incoming Call in Online State =========");
} }
await cProv.startIncomingCallViaKit(inCallData: inCallData.toJson(), isVCall: callType == "video" ? true : false); await cProv!.startIncomingCallViaKit(inCallData: inCallData.toJson(), isVCall: callType == "video" ? true : false);
cProv.init(); cProv!.init();
isCallConnected = true; isCallConnected = true;
} else { } else {
if (kDebugMode) { if (kDebugMode) {
@ -109,11 +109,11 @@ class _StartCallPageState extends State<StartCallPage> {
AppState().setchatUserDetails = userLoginResponse; AppState().setchatUserDetails = userLoginResponse;
AppSharedPrefs().setStringFromPrefs("userLoginChatDetails", jsonEncode(userLoginResponse.response)); AppSharedPrefs().setStringFromPrefs("userLoginChatDetails", jsonEncode(userLoginResponse.response));
await cProv.startIncomingCallViaKit(inCallData: inCallData.toJson(), isVCall: callType == "video" ? true : false); await cProv!.startIncomingCallViaKit(inCallData: inCallData.toJson(), isVCall: callType == "video" ? true : false);
try { try {
AppState().setchatUserDetails = UserAutoLoginModel(response: userLoginResponse.response, errorResponses: null); AppState().setchatUserDetails = UserAutoLoginModel(response: userLoginResponse.response, errorResponses: null);
await cProv.buildHubConnection().whenComplete(() { await cProv!.buildHubConnection().whenComplete(() {
cProv.init(); cProv!.init();
isCallConnected = true; isCallConnected = true;
}); });
} catch (e) { } catch (e) {
@ -126,11 +126,11 @@ class _StartCallPageState extends State<StartCallPage> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
cProv = context.read<ChatCallProvider>(); cProv = context.read<ChatCallProvider>();
if (!cProv.isOutGoingCall) { if (!cProv!.isOutGoingCall) {
if (Platform.isAndroid) { if (Platform.isAndroid) {
startCall(); startCall();
} else if (Platform.isIOS) { } else if (Platform.isIOS) {
cProv.buildHubConnection(); cProv!.buildHubConnection();
startIosCall(); startIosCall();
} }
} }
@ -138,7 +138,7 @@ class _StartCallPageState extends State<StartCallPage> {
return Scaffold( return Scaffold(
extendBody: true, extendBody: true,
body: Consumer<ChatCallProvider>( body: Consumer<ChatCallProvider>(
builder: (BuildContext context, ChatCallProvider prov, Widget child) { builder: (BuildContext context, ChatCallProvider prov, Widget? child) {
return prov.isIncomingCallLoader return prov.isIncomingCallLoader
? const SizedBox( ? const SizedBox(
width: double.infinity, width: double.infinity,
@ -155,7 +155,7 @@ class _StartCallPageState extends State<StartCallPage> {
children: <Widget>[ children: <Widget>[
if (!prov.isAudioCall && prov.isVideoCall) if (!prov.isAudioCall && prov.isVideoCall)
RTCVideoView( RTCVideoView(
prov.remoteRenderer, prov.remoteRenderer!,
objectFit: RTCVideoViewObjectFit.RTCVideoViewObjectFitContain, objectFit: RTCVideoViewObjectFit.RTCVideoViewObjectFitContain,
key: const Key('remote'), key: const Key('remote'),
), ),
@ -174,7 +174,7 @@ class _StartCallPageState extends State<StartCallPage> {
height: 200, height: 200,
width: 140, width: 140,
child: RTCVideoView( child: RTCVideoView(
prov.localVideoRenderer, prov.localVideoRenderer!,
mirror: true, mirror: true,
// filterQuality: FilterQuality.high, // filterQuality: FilterQuality.high,
objectFit: RTCVideoViewObjectFit.RTCVideoViewObjectFitCover, objectFit: RTCVideoViewObjectFit.RTCVideoViewObjectFitCover,
@ -225,7 +225,7 @@ class _StartCallPageState extends State<StartCallPage> {
height: 10, height: 10,
), ),
Text( Text(
prov.incomingCallData.targetUserName ?? "", prov.incomingCallData!.targetUserName ?? "",
style: const TextStyle( style: const TextStyle(
fontSize: 21, fontSize: 21,
decoration: TextDecoration.none, decoration: TextDecoration.none,
@ -384,7 +384,7 @@ class _StartCallPageState extends State<StartCallPage> {
children: <Widget>[ children: <Widget>[
if (!prov.isAudioCall && prov.isVideoCall) if (!prov.isAudioCall && prov.isVideoCall)
RTCVideoView( RTCVideoView(
prov.remoteRenderer, prov.remoteRenderer!,
objectFit: RTCVideoViewObjectFit.RTCVideoViewObjectFitContain, objectFit: RTCVideoViewObjectFit.RTCVideoViewObjectFitContain,
key: const Key('remote'), key: const Key('remote'),
), ),
@ -403,7 +403,7 @@ class _StartCallPageState extends State<StartCallPage> {
height: 200, height: 200,
width: 140, width: 140,
child: RTCVideoView( child: RTCVideoView(
prov.localVideoRenderer, prov.localVideoRenderer!,
mirror: true, mirror: true,
objectFit: RTCVideoViewObjectFit.RTCVideoViewObjectFitCover, objectFit: RTCVideoViewObjectFit.RTCVideoViewObjectFitCover,
), ),
@ -453,7 +453,7 @@ class _StartCallPageState extends State<StartCallPage> {
height: 10, height: 10,
), ),
Text( Text(
prov.outGoingCallData.receiverName, prov.outGoingCallData!.receiverName!,
style: const TextStyle( style: const TextStyle(
fontSize: 21, fontSize: 21,
decoration: TextDecoration.none, decoration: TextDecoration.none,

@ -1,7 +1,7 @@
import 'dart:ui'; import 'dart:ui';
import 'package:diplomaticquarterapp/models/chat/call.dart';
import 'package:diplomaticquarterapp/voipcall/consts.dart'; import 'package:diplomaticquarterapp/voipcall/consts.dart';
import 'package:diplomaticquarterapp/voipcall/model/call.dart';
import 'package:diplomaticquarterapp/voipcall/provider/chat_call_provider.dart'; import 'package:diplomaticquarterapp/voipcall/provider/chat_call_provider.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart'; import 'package:flutter_svg/flutter_svg.dart';
@ -9,17 +9,17 @@ import 'package:flutter_webrtc/flutter_webrtc.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
class OutGoingCall extends StatefulWidget { class OutGoingCall extends StatefulWidget {
CallDataModel outGoingCallData; CallDataModel? outGoingCallData;
bool isVideoCall; bool isVideoCall;
OutGoingCall({Key key, this.outGoingCallData, this.isVideoCall}) : super(key: key); OutGoingCall({Key? key, this.outGoingCallData, this.isVideoCall = false}) : super(key: key);
@override @override
_OutGoingCallState createState() => _OutGoingCallState(); _OutGoingCallState createState() => _OutGoingCallState();
} }
class _OutGoingCallState extends State<OutGoingCall> { class _OutGoingCallState extends State<OutGoingCall> {
ChatCallProvider callProvider; ChatCallProvider? callProvider;
//late ChatProviderModel chatProvider; //late ChatProviderModel chatProvider;
bool loader = true; bool loader = true;
@ -29,8 +29,8 @@ class _OutGoingCallState extends State<OutGoingCall> {
} }
Future<void> init() async { Future<void> init() async {
widget.isVideoCall ? callProvider.isVideoCall = true : callProvider.isVideoCall = false; widget.isVideoCall ? callProvider!.isVideoCall = true : callProvider!.isVideoCall = false;
callProvider.isOutGoingCall = true; callProvider!.isOutGoingCall = true;
// IosCallPayload payload = IosCallPayload( // IosCallPayload payload = IosCallPayload(
// incomingCallerId: widget.outGoingCallData.callerId.toString(), // incomingCallerId: widget.outGoingCallData.callerId.toString(),
// incomingCallerName: widget.outGoingCallData.callerName, // incomingCallerName: widget.outGoingCallData.callerName,
@ -39,7 +39,7 @@ class _OutGoingCallState extends State<OutGoingCall> {
// uuid: "", // uuid: "",
// callData: widget.outGoingCallData.toRawJson()); // callData: widget.outGoingCallData.toRawJson());
// await Utils.saveStringFromPrefs("iosCallPayload", jsonEncode(payload)); // await Utils.saveStringFromPrefs("iosCallPayload", jsonEncode(payload));
await callProvider.initLocalCamera(callData: widget.outGoingCallData, context: context); await callProvider!.initLocalCamera(callData: widget.outGoingCallData, context: context);
loader = false; loader = false;
} }
@ -53,7 +53,7 @@ class _OutGoingCallState extends State<OutGoingCall> {
callProvider = Provider.of<ChatCallProvider>(context, listen: false); callProvider = Provider.of<ChatCallProvider>(context, listen: false);
init(); init();
return Scaffold( return Scaffold(
body: Consumer<ChatCallProvider>(builder: (BuildContext context, ChatCallProvider chatcp, Widget child) { body: Consumer<ChatCallProvider>(builder: (BuildContext context, ChatCallProvider chatcp, Widget? child) {
return loader return loader
? const Center( ? const Center(
child: CircularProgressIndicator(), child: CircularProgressIndicator(),
@ -64,7 +64,7 @@ class _OutGoingCallState extends State<OutGoingCall> {
if (chatcp.isVideoCall) if (chatcp.isVideoCall)
Positioned.fill( Positioned.fill(
child: RTCVideoView( child: RTCVideoView(
chatcp.localVideoRenderer, chatcp.localVideoRenderer!,
objectFit: RTCVideoViewObjectFit.RTCVideoViewObjectFitCover, objectFit: RTCVideoViewObjectFit.RTCVideoViewObjectFitCover,
), ),
), ),
@ -111,7 +111,7 @@ class _OutGoingCallState extends State<OutGoingCall> {
height: 10, height: 10,
), ),
Text( Text(
widget.outGoingCallData.receiverName.toString().replaceAll(".", " "), widget.outGoingCallData!.receiverName.toString().replaceAll(".", " "),
style: const TextStyle( style: const TextStyle(
fontSize: 21, fontSize: 21,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
@ -187,7 +187,7 @@ class _OutGoingCallState extends State<OutGoingCall> {
); );
} }
BoxDecoration cardRadius(double radius, {Color color, double elevation}) { BoxDecoration cardRadius(double radius, {Color? color, double? elevation}) {
return BoxDecoration( return BoxDecoration(
shape: BoxShape.rectangle, shape: BoxShape.rectangle,
color: color ?? Colors.white, color: color ?? Colors.white,

@ -20,18 +20,18 @@ class CallDataModel {
this.callType, this.callType,
}); });
int callerId; int? callerId;
String callerName; String? callerName;
String callerEmail; String? callerEmail;
String callerTitle; String? callerTitle;
dynamic callerPhone; dynamic? callerPhone;
int receiverId; int? receiverId;
String receiverName; String? receiverName;
String receiverEmail; String? receiverEmail;
dynamic receiverTitle; dynamic? receiverTitle;
dynamic receiverPhone; dynamic? receiverPhone;
String title; String? title;
String callType; String? callType;
factory CallDataModel.fromRawJson(String str) => CallDataModel.fromJson(json.decode(str)); factory CallDataModel.fromRawJson(String str) => CallDataModel.fromJson(json.decode(str));
@ -79,9 +79,9 @@ class CallSessionPayLoad {
this.sdp, this.sdp,
}); });
int target; int? target;
int caller; int? caller;
Sdp sdp; Sdp? sdp;
factory CallSessionPayLoad.fromRawJson(String str) => CallSessionPayLoad.fromJson(json.decode(str)); factory CallSessionPayLoad.fromRawJson(String str) => CallSessionPayLoad.fromJson(json.decode(str));
@ -106,8 +106,8 @@ class Sdp {
this.sdp, this.sdp,
}); });
String type; String? type;
String sdp; String? sdp;
factory Sdp.fromRawJson(String str) => Sdp.fromJson(json.decode(str)); factory Sdp.fromRawJson(String str) => Sdp.fromJson(json.decode(str));
@ -127,12 +127,12 @@ class Sdp {
// final iosCallPayload = iosCallPayloadFromJson(jsonString); // final iosCallPayload = iosCallPayloadFromJson(jsonString);
class IosCallPayload { class IosCallPayload {
String incomingCallType; String? incomingCallType;
String incomingCallerId; String? incomingCallerId;
String incomingCallReciverId; String? incomingCallReciverId;
String incomingCallerName; String? incomingCallerName;
String callData; String? callData;
String uuid; String? uuid;
IosCallPayload({ IosCallPayload({
this.incomingCallType, this.incomingCallType,

@ -38,32 +38,32 @@ class SingleUserChatModel {
this.voice, this.voice,
this.voiceController}); this.voiceController});
int userChatHistoryId; int? userChatHistoryId;
int userChatHistoryLineId; int? userChatHistoryLineId;
String contant; String? contant;
String contantNo; String? contantNo;
int currentUserId; int? currentUserId;
String currentUserName; String? currentUserName;
String currentUserEmail; String? currentUserEmail;
int targetUserId; int? targetUserId;
String targetUserName; String? targetUserName;
String targetUserEmail; String? targetUserEmail;
String encryptedTargetUserId; String? encryptedTargetUserId;
String encryptedTargetUserName; String? encryptedTargetUserName;
int chatEventId; int? chatEventId;
dynamic fileTypeId; dynamic fileTypeId;
bool isSeen; bool? isSeen;
bool isDelivered; bool? isDelivered;
DateTime createdDate; DateTime? createdDate;
int chatSource; int? chatSource;
String conversationId; String? conversationId;
FileTypeResponse fileTypeResponse; FileTypeResponse? fileTypeResponse;
UserChatReplyResponse userChatReplyResponse; UserChatReplyResponse? userChatReplyResponse;
bool isReplied; bool? isReplied;
bool isImageLoaded; bool? isImageLoaded;
Uint8List image; Uint8List? image;
File voice; File? voice;
AudioPlayer voiceController; AudioPlayer? voiceController;
factory SingleUserChatModel.fromJson(Map<String, dynamic> json) => SingleUserChatModel( factory SingleUserChatModel.fromJson(Map<String, dynamic> json) => SingleUserChatModel(
userChatHistoryId: json["userChatHistoryId"] == null ? null : json["userChatHistoryId"], userChatHistoryId: json["userChatHistoryId"] == null ? null : json["userChatHistoryId"],
@ -110,11 +110,11 @@ class SingleUserChatModel {
"fileTypeId": fileTypeId, "fileTypeId": fileTypeId,
"isSeen": isSeen == null ? null : isSeen, "isSeen": isSeen == null ? null : isSeen,
"isDelivered": isDelivered == null ? null : isDelivered, "isDelivered": isDelivered == null ? null : isDelivered,
"createdDate": createdDate == null ? null : createdDate.toIso8601String(), "createdDate": createdDate == null ? null : createdDate!.toIso8601String(),
"chatSource": chatSource == null ? null : chatSource, "chatSource": chatSource == null ? null : chatSource,
"conversationId": conversationId == null ? null : conversationId, "conversationId": conversationId == null ? null : conversationId,
"fileTypeResponse": fileTypeResponse == null ? null : fileTypeResponse.toJson(), "fileTypeResponse": fileTypeResponse == null ? null : fileTypeResponse!.toJson(),
"userChatReplyResponse": userChatReplyResponse == null ? null : userChatReplyResponse.toJson(), "userChatReplyResponse": userChatReplyResponse == null ? null : userChatReplyResponse!.toJson(),
}; };
} }
@ -127,7 +127,7 @@ class FileTypeResponse {
this.fileName, this.fileName,
}); });
int fileTypeId; int? fileTypeId;
dynamic fileTypeName; dynamic fileTypeName;
dynamic fileTypeDescription; dynamic fileTypeDescription;
dynamic fileKind; dynamic fileKind;
@ -165,18 +165,18 @@ class UserChatReplyResponse {
this.image, this.image,
this.voice}); this.voice});
int userChatHistoryId; int? userChatHistoryId;
int chatEventId; int? chatEventId;
String contant; String? contant;
String contantNo; String? contantNo;
dynamic fileTypeId; dynamic fileTypeId;
DateTime createdDate; DateTime? createdDate;
int targetUserId; int? targetUserId;
String targetUserName; String? targetUserName;
FileTypeResponse fileTypeResponse; FileTypeResponse? fileTypeResponse;
bool isImageLoaded; bool? isImageLoaded;
Uint8List image; Uint8List? image;
Uint8List voice; Uint8List? voice;
factory UserChatReplyResponse.fromJson(Map<String, dynamic> json) => UserChatReplyResponse( factory UserChatReplyResponse.fromJson(Map<String, dynamic> json) => UserChatReplyResponse(
userChatHistoryId: json["userChatHistoryId"] == null ? null : json["userChatHistoryId"], userChatHistoryId: json["userChatHistoryId"] == null ? null : json["userChatHistoryId"],
@ -199,9 +199,9 @@ class UserChatReplyResponse {
"contant": contant == null ? null : contant, "contant": contant == null ? null : contant,
"contantNo": contantNo == null ? null : contantNo, "contantNo": contantNo == null ? null : contantNo,
"fileTypeId": fileTypeId, "fileTypeId": fileTypeId,
"createdDate": createdDate == null ? null : createdDate.toIso8601String(), "createdDate": createdDate == null ? null : createdDate!.toIso8601String(),
"targetUserId": targetUserId == null ? null : targetUserId, "targetUserId": targetUserId == null ? null : targetUserId,
"targetUserName": targetUserName == null ? null : targetUserName, "targetUserName": targetUserName == null ? null : targetUserName,
"fileTypeResponse": fileTypeResponse == null ? null : fileTypeResponse.toJson(), "fileTypeResponse": fileTypeResponse == null ? null : fileTypeResponse!.toJson(),
}; };
} }

@ -10,8 +10,8 @@ class UserAutoLoginModel {
this.errorResponses, this.errorResponses,
}); });
Response response; Response? response;
List<ErrorResponse> errorResponses; List<ErrorResponse>? errorResponses;
factory UserAutoLoginModel.fromJson(Map<String, dynamic> json) => UserAutoLoginModel( factory UserAutoLoginModel.fromJson(Map<String, dynamic> json) => UserAutoLoginModel(
response: json["response"] == null ? null : Response.fromJson(json["response"]), response: json["response"] == null ? null : Response.fromJson(json["response"]),
@ -19,8 +19,8 @@ class UserAutoLoginModel {
); );
Map<String, dynamic> toJson() => { Map<String, dynamic> toJson() => {
"response": response == null ? null : response.toJson(), "response": response == null ? null : response!.toJson(),
"errorResponses": errorResponses == null ? null : List<dynamic>.from(errorResponses.map((x) => x.toJson())), "errorResponses": errorResponses == null ? null : List<dynamic>.from(errorResponses!.map((x) => x.toJson())),
}; };
} }
@ -38,16 +38,16 @@ class Response {
this.encryptedUserName, this.encryptedUserName,
}); });
int id; int? id;
String userName; String? userName;
String email; String? email;
String phone; String? phone;
String title; String? title;
String token; String? token;
bool isDomainUser; bool? isDomainUser;
bool isActiveCode; bool? isActiveCode;
String encryptedUserId; String? encryptedUserId;
String encryptedUserName; String? encryptedUserName;
factory Response.fromJson(Map<String, dynamic> json) => Response( factory Response.fromJson(Map<String, dynamic> json) => Response(
id: json["id"] == null ? null : json["id"], id: json["id"] == null ? null : json["id"],
@ -82,8 +82,8 @@ class ErrorResponse {
this.message, this.message,
}); });
String fieldName; String? fieldName;
String message; String? message;
factory ErrorResponse.fromJson(Map<String, dynamic> json) => ErrorResponse( factory ErrorResponse.fromJson(Map<String, dynamic> json) => ErrorResponse(
fieldName: json["fieldName"] == null ? null : json["fieldName"], fieldName: json["fieldName"] == null ? null : json["fieldName"],

@ -5,32 +5,32 @@
import 'dart:convert'; import 'dart:convert';
class IncomingCallModel { class IncomingCallModel {
String actionColor; String? actionColor;
String appName; String? appName;
Args args; Args? args;
String avatar; String? avatar;
String backgroundColor; String? backgroundColor;
String backgroundUrl; String? backgroundUrl;
int duration; int? duration;
Extra extra; Extra? extra;
String from; String? from;
String handle; String? handle;
Args headers; Args? headers;
String id; String? id;
bool isAccepted; bool? isAccepted;
bool isCustomNotification; bool? isCustomNotification;
bool isCustomSmallExNotification; bool? isCustomSmallExNotification;
bool isShowCallback; bool? isShowCallback;
bool isShowLogo; bool? isShowLogo;
bool isShowMissedCallNotification; bool? isShowMissedCallNotification;
String nameCaller; String? nameCaller;
String ringtonePath; String? ringtonePath;
String textAccept; String? textAccept;
String textCallback; String? textCallback;
String textDecline; String? textDecline;
String textMissedCall; String? textMissedCall;
int type; int? type;
String uuid; String? uuid;
IncomingCallModel({ IncomingCallModel({
this.actionColor, this.actionColor,
@ -137,10 +137,10 @@ class Args {
} }
class Extra { class Extra {
LoginDetails loginDetails; LoginDetails? loginDetails;
bool isIncomingCall; bool? isIncomingCall;
CallerDetails callerDetails; CallerDetails? callerDetails;
String callType; String? callType;
Extra({ Extra({
this.loginDetails, this.loginDetails,
@ -169,25 +169,25 @@ class Extra {
} }
class CallerDetails { class CallerDetails {
int userChatHistoryId; int? userChatHistoryId;
String contant; String? contant;
FileTypeResponse fileTypeResponse; FileTypeResponse? fileTypeResponse;
String currentUserName; String? currentUserName;
String targetUserEmail; String? targetUserEmail;
String conversationId; String? conversationId;
String encryptedTargetUserId; String? encryptedTargetUserId;
int targetUserId; int? targetUserId;
bool isSeen; bool? isSeen;
int userChatHistoryLineId; int? userChatHistoryLineId;
bool isDelivered; bool? isDelivered;
String targetUserName; String? targetUserName;
int currentUserId; int? currentUserId;
DateTime createdDate; DateTime? createdDate;
String currentUserEmail; String? currentUserEmail;
String contantNo; String? contantNo;
int chatEventId; int? chatEventId;
String encryptedTargetUserName; String? encryptedTargetUserName;
int chatSource; int? chatSource;
CallerDetails({ CallerDetails({
this.userChatHistoryId, this.userChatHistoryId,
@ -261,7 +261,7 @@ class CallerDetails {
} }
class FileTypeResponse { class FileTypeResponse {
int fileTypeId; int? fileTypeId;
FileTypeResponse({ FileTypeResponse({
this.fileTypeId, this.fileTypeId,
@ -281,15 +281,15 @@ class FileTypeResponse {
} }
class LoginDetails { class LoginDetails {
bool isActiveCode; bool? isActiveCode;
int id; int? id;
String encryptedUserName; String? encryptedUserName;
String userName; String? userName;
String title; String? title;
String encryptedUserId; String? encryptedUserId;
String email; String? email;
bool isDomainUser; bool? isDomainUser;
String token; String? token;
LoginDetails({ LoginDetails({
this.isActiveCode, this.isActiveCode,

@ -10,8 +10,8 @@ class RemoteIceCandidatePayLoad {
this.candidate, this.candidate,
}); });
int target; int? target;
Candidate candidate; Candidate? candidate;
factory RemoteIceCandidatePayLoad.fromRawJson(String str) => RemoteIceCandidatePayLoad.fromJson(json.decode(str)); factory RemoteIceCandidatePayLoad.fromRawJson(String str) => RemoteIceCandidatePayLoad.fromJson(json.decode(str));
@ -36,10 +36,10 @@ class Candidate {
this.usernameFragment, this.usernameFragment,
}); });
String candidate; String? candidate;
String sdpMid; String? sdpMid;
int sdpMLineIndex; int? sdpMLineIndex;
String usernameFragment; String? usernameFragment;
factory Candidate.fromRawJson(String str) => Candidate.fromJson(json.decode(str)); factory Candidate.fromRawJson(String str) => Candidate.fromJson(json.decode(str));

@ -9,8 +9,10 @@ import 'package:diplomaticquarterapp/uitl/navigation_service.dart';
import 'package:diplomaticquarterapp/uitl/utils.dart'; import 'package:diplomaticquarterapp/uitl/utils.dart';
import 'package:diplomaticquarterapp/voipcall/call/chat_incoming_call_screen.dart'; import 'package:diplomaticquarterapp/voipcall/call/chat_incoming_call_screen.dart';
import 'package:diplomaticquarterapp/voipcall/consts.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_single_user_chat_call.dart';
import 'package:diplomaticquarterapp/voipcall/model/get_user_login_token.dart'; import 'package:diplomaticquarterapp/voipcall/model/get_user_login_token.dart';
import 'package:diplomaticquarterapp/voipcall/model/webrtc_payloads.dart';
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_callkit_incoming/flutter_callkit_incoming.dart'; import 'package:flutter_callkit_incoming/flutter_callkit_incoming.dart';
@ -90,7 +92,7 @@ class ChatCallProvider with ChangeNotifier, DiagnosticableTreeMixin {
HubConnection hub; HubConnection hub;
HttpConnectionOptions httpOp = HttpConnectionOptions(skipNegotiation: false, logMessageContent: true); HttpConnectionOptions httpOp = HttpConnectionOptions(skipNegotiation: false, logMessageContent: true);
hub = HubConnectionBuilder() hub = HubConnectionBuilder()
.withUrl(ApiConsts.chatHubConnectionUrl + "?UserId=${AppState().chatDetails.response.id}&source=Desktop&access_token=${AppState().chatDetails.response.token}", options: httpOp) .withUrl(ApiConsts.chatHubConnectionUrl + "?UserId=${AppState().chatDetails!.response!.id}&source=Desktop&access_token=${AppState().chatDetails!.response!.token}", options: httpOp)
.withAutomaticReconnect(retryDelays: <int>[2000, 5000, 10000, 20000]).build(); .withAutomaticReconnect(retryDelays: <int>[2000, 5000, 10000, 20000]).build();
return hub; return hub;
} }
@ -99,11 +101,11 @@ class ChatCallProvider with ChangeNotifier, DiagnosticableTreeMixin {
if (kDebugMode) { if (kDebugMode) {
print("=================== Call Listeners Registered ======================="); print("=================== Call Listeners Registered =======================");
} }
chatHubConnection!.on("OnCallAcceptedAsync", onCallAcceptedAsync!); chatHubConnection!.on("OnCallAcceptedAsync", onCallAcceptedAsync);
chatHubConnection!.on("OnIceCandidateAsync", onIceCandidateAsync!); chatHubConnection!.on("OnIceCandidateAsync", onIceCandidateAsync);
chatHubConnection!.on("OnOfferAsync", onOfferAsync!); chatHubConnection!.on("OnOfferAsync", onOfferAsync);
chatHubConnection!.on("OnAnswerOffer", onAnswerOffer!); chatHubConnection!.on("OnAnswerOffer", onAnswerOffer);
chatHubConnection!.on("OnHangUpAsync", onHangUpAsync!); chatHubConnection!.on("OnHangUpAsync", onHangUpAsync);
// chatHubConnection!.on("OnCallDeclinedAsync", onCallDeclinedAsync); // chatHubConnection!.on("OnCallDeclinedAsync", onCallDeclinedAsync);
// chatHubConnection!.on("OnIncomingCallAsync", OnIncomingCallAsync); // chatHubConnection!.on("OnIncomingCallAsync", OnIncomingCallAsync);
} }
@ -126,12 +128,11 @@ class ChatCallProvider with ChangeNotifier, DiagnosticableTreeMixin {
///////////////////////////////////////////////OutGoing Call//////////////////////////////////////////////////// ///////////////////////////////////////////////OutGoing Call////////////////////////////////////////////////////
Future<void> initLocalCamera({callData, BuildContext context, bool isIncomingCall = false}) async { Future<void> initLocalCamera({callData, BuildContext? context, bool isIncomingCall = false}) async {
isCallEnded = false; isCallEnded = false;
outGoingCallData = callData; outGoingCallData = callData;
await initStreams(); await initStreams();
await startCall(callType: isVideoCall ? "Video" : "Audio");
await startCall(callType: isVideoCall ? "Video" : "Audio", context: context);
_pc = await creatOfferWithCon(); _pc = await creatOfferWithCon();
connectOutgoing(); connectOutgoing();
notifyListeners(); notifyListeners();
@ -142,7 +143,7 @@ class ChatCallProvider with ChangeNotifier, DiagnosticableTreeMixin {
// notifyListeners(); // notifyListeners();
} }
Future<void> startCall({String callType, BuildContext context}) async { Future<void> startCall({String? callType}) async {
// chatProvModel.isTextMsg = true; // chatProvModel.isTextMsg = true;
// chatProvModel.isAttachmentMsg = false; // chatProvModel.isAttachmentMsg = false;
// chatProvModel.isVoiceMsg = false; // chatProvModel.isVoiceMsg = false;
@ -158,10 +159,10 @@ class ChatCallProvider with ChangeNotifier, DiagnosticableTreeMixin {
// ); // );
await invoke( await invoke(
invokeMethod: "CallUserAsync", invokeMethod: "CallUserAsync",
currentUserID: outGoingCallData.callerId, currentUserID: outGoingCallData!.callerId!,
targetUserID: outGoingCallData.receiverId, targetUserID: outGoingCallData!.receiverId!,
); );
await invoke(invokeMethod: "UpdateUserStatusAsync", currentUserID: outGoingCallData.callerId, targetUserID: outGoingCallData.receiverId, userStatus: 4); await invoke(invokeMethod: "UpdateUserStatusAsync", currentUserID: outGoingCallData!.callerId!, targetUserID: outGoingCallData!.receiverId!, userStatus: 4);
} }
// OutGoing Listeners // OutGoing Listeners
@ -169,8 +170,8 @@ class ChatCallProvider with ChangeNotifier, DiagnosticableTreeMixin {
dynamic items = params!.toList(); dynamic items = params!.toList();
RTCSessionDescription description = await _createOffer(); RTCSessionDescription description = await _createOffer();
await _pc!.setLocalDescription(description); await _pc!.setLocalDescription(description);
dynamic payload = {"target": items[0]["id"], "caller": outGoingCallData.callerId, "sdp": description.toMap()}; 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)); invoke(invokeMethod: "OfferAsync", currentUserID: outGoingCallData!.callerId!, targetUserID: items[0]["id"], data: jsonEncode(payload));
} }
Future<void> onIceCandidateAsync(List<Object?>? params) async { Future<void> onIceCandidateAsync(List<Object?>? params) async {
@ -178,7 +179,7 @@ class ChatCallProvider with ChangeNotifier, DiagnosticableTreeMixin {
if (isIncomingCall) { if (isIncomingCall) {
RemoteIceCandidatePayLoad data = RemoteIceCandidatePayLoad.fromJson(jsonDecode(items.first.toString())); RemoteIceCandidatePayLoad data = RemoteIceCandidatePayLoad.fromJson(jsonDecode(items.first.toString()));
if (_pc != null) { if (_pc != null) {
await _pc.addCandidate(RTCIceCandidate(data.candidate.candidate, data.candidate.sdpMid, data.candidate.sdpMLineIndex)); await _pc!.addCandidate(RTCIceCandidate(data.candidate!.candidate, data.candidate!.sdpMid, data.candidate!.sdpMLineIndex));
} }
} else { } else {
if (kDebugMode) { if (kDebugMode) {
@ -186,7 +187,7 @@ class ChatCallProvider with ChangeNotifier, DiagnosticableTreeMixin {
} }
RemoteIceCandidatePayLoad data = RemoteIceCandidatePayLoad.fromJson(jsonDecode(items.first.toString())); RemoteIceCandidatePayLoad data = RemoteIceCandidatePayLoad.fromJson(jsonDecode(items.first.toString()));
if (_pc != null) { if (_pc != null) {
await _pc.addCandidate(RTCIceCandidate(data.candidate.candidate, data.candidate.sdpMid, data.candidate.sdpMLineIndex)); await _pc!.addCandidate(RTCIceCandidate(data.candidate!.candidate, data.candidate!.sdpMid, data.candidate!.sdpMLineIndex));
if (!isCallStarted) { if (!isCallStarted) {
isCallStarted = true; isCallStarted = true;
notifyListeners(); notifyListeners();
@ -196,14 +197,14 @@ class ChatCallProvider with ChangeNotifier, DiagnosticableTreeMixin {
if (Platform.isIOS) { if (Platform.isIOS) {
Future.delayed(Duration(seconds: 2), () { Future.delayed(Duration(seconds: 2), () {
Navigator.pushReplacement( Navigator.pushReplacement(
providerContext, providerContext!,
MaterialPageRoute( MaterialPageRoute(
builder: (BuildContext context) => StartCallPage(), builder: (BuildContext context) => StartCallPage(),
)); ));
}); });
} else { } else {
Navigator.pushReplacement( Navigator.pushReplacement(
providerContext, providerContext!,
MaterialPageRoute( MaterialPageRoute(
builder: (BuildContext context) => StartCallPage(), builder: (BuildContext context) => StartCallPage(),
)); ));
@ -222,8 +223,8 @@ class ChatCallProvider with ChangeNotifier, DiagnosticableTreeMixin {
_pc!.setRemoteDescription(RTCSessionDescription(data[0]["sdp"]["sdp"], data[0]["sdp"]["type"])); _pc!.setRemoteDescription(RTCSessionDescription(data[0]["sdp"]["sdp"], data[0]["sdp"]["type"]));
RTCSessionDescription description = await _createAnswer(); RTCSessionDescription description = await _createAnswer();
await _pc!.setLocalDescription(description); await _pc!.setLocalDescription(description);
dynamic payload = {"target": data[0]["caller"], "caller": AppState().chatDetails.response.id, "sdp": description.toMap()}; 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)); invoke(invokeMethod: "AnswerOfferAsync", currentUserID: AppState().chatDetails!.response!.id!, targetUserID: incomingCallData!.targetUserId!, data: jsonEncode(payload));
} }
// else { // else {
// RTCSessionDescription description = await _createAnswer(); // RTCSessionDescription description = await _createAnswer();
@ -240,8 +241,8 @@ class ChatCallProvider with ChangeNotifier, DiagnosticableTreeMixin {
if (isIncomingCall) { if (isIncomingCall) {
print("-----------------------Endeddddd By Me---------------------------"); print("-----------------------Endeddddd By Me---------------------------");
if (chatHubConnection!.state == HubConnectionState.Connected) { if (chatHubConnection!.state == HubConnectionState.Connected) {
await invoke(invokeMethod: "HangUpAsync", currentUserID: AppState().chatDetails.response.id, targetUserID: incomingCallData.targetUserId, userStatus: 0); 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); await invoke(invokeMethod: "UpdateUserStatusAsync", currentUserID: AppState().chatDetails!.response!.id!, targetUserID: incomingCallData!.targetUserId!, userStatus: 1);
} }
isCallStarted = false; isCallStarted = false;
isVideoCall = false; isVideoCall = false;
@ -253,38 +254,38 @@ class ChatCallProvider with ChangeNotifier, DiagnosticableTreeMixin {
isAudioCall = false; isAudioCall = false;
if (isCallConnected) { if (isCallConnected) {
if (_pc.connectionState == RTCPeerConnectionState.RTCPeerConnectionStateConnected) { if (_pc!.connectionState == RTCPeerConnectionState.RTCPeerConnectionStateConnected) {
if (kDebugMode) { if (kDebugMode) {
print("------------------ PC Stopped ----------------------------"); print("------------------ PC Stopped ----------------------------");
} }
_pc.close(); _pc!.close();
_pc.dispose(); _pc!.dispose();
} }
} }
if (remoteRenderer != null) { if (remoteRenderer != null) {
remoteRenderer.dispose(); remoteRenderer!.dispose();
remoteRenderer = null; remoteRenderer = null;
} }
if (localVideoRenderer != null) { if (localVideoRenderer != null) {
localVideoRenderer.dispose(); localVideoRenderer!.dispose();
localVideoRenderer = null; localVideoRenderer = null;
} }
if (_localStream != null) { if (_localStream != null) {
_localStream.dispose(); _localStream!.dispose();
_localStream = null; _localStream = null;
} }
if (chatHubConnection != null && !isUserOnline) { if (chatHubConnection != null && !isUserOnline!) {
chatHubConnection.stop(); chatHubConnection!.stop();
} }
await FlutterCallkitIncoming.endAllCalls(); await FlutterCallkitIncoming.endAllCalls();
return true; return true;
} else { } else {
if (isOutGoingCall) { if (isOutGoingCall) {
await invoke(invokeMethod: "HangUpAsync", currentUserID: outGoingCallData.callerId, targetUserID: outGoingCallData.receiverId, userStatus: 1); await invoke(invokeMethod: "HangUpAsync", currentUserID: outGoingCallData!.callerId!, targetUserID: outGoingCallData!.receiverId!, userStatus: 1);
await invoke(invokeMethod: "UpdateUserStatusAsync", currentUserID: outGoingCallData.callerId, targetUserID: outGoingCallData.receiverId, userStatus: 1); await invoke(invokeMethod: "UpdateUserStatusAsync", currentUserID: outGoingCallData!.callerId!, targetUserID: outGoingCallData!.receiverId!, userStatus: 1);
} else if (isIncomingCall) { } else if (isIncomingCall) {
await invoke(invokeMethod: "UpdateUserStatusAsync", currentUserID: AppState().chatDetails.response.id, targetUserID: incomingCallData.targetUserId, userStatus: 1); await invoke(invokeMethod: "UpdateUserStatusAsync", currentUserID: AppState().chatDetails!.response!.id!, targetUserID: incomingCallData!.targetUserId!, userStatus: 1);
} }
isCallStarted = false; isCallStarted = false;
isVideoCall = false; isVideoCall = false;
@ -292,22 +293,22 @@ class ChatCallProvider with ChangeNotifier, DiagnosticableTreeMixin {
isMicOff = false; isMicOff = false;
isLoudSpeaker = false; isLoudSpeaker = false;
if (isCallConnected) { if (isCallConnected) {
if (_pc.connectionState == RTCPeerConnectionState.RTCPeerConnectionStateConnected) { if (_pc!.connectionState == RTCPeerConnectionState.RTCPeerConnectionStateConnected) {
_pc.close(); _pc!.close();
_pc.dispose(); _pc!.dispose();
} }
} }
if (remoteRenderer != null) { if (remoteRenderer != null) {
remoteRenderer.dispose(); remoteRenderer!.dispose();
remoteRenderer = null; remoteRenderer = null;
} }
if (localVideoRenderer != null) { if (localVideoRenderer != null) {
localVideoRenderer.dispose(); localVideoRenderer!.dispose();
localVideoRenderer = null; localVideoRenderer = null;
} }
if (_localStream != null) { if (_localStream != null) {
_localStream.dispose(); _localStream!.dispose();
_localStream = null; _localStream = null;
} }
isOutGoingCall = false; isOutGoingCall = false;
@ -319,29 +320,29 @@ class ChatCallProvider with ChangeNotifier, DiagnosticableTreeMixin {
// Incoming Listeners // Incoming Listeners
void onAnswerOffer(List<Object> payload) async { void onAnswerOffer(List<Object?>? payload) async {
// if (isIncomingCall) { // if (isIncomingCall) {
// // print("--------------------- On Answer Offer Async ---------------------------------------"); // // print("--------------------- On Answer Offer Async ---------------------------------------");
// //await invoke(invokeMethod: "InvokeMobile", currentUserID: AppState().getchatUserDetails!.response!.id!, targetUserID: incomingCallData.targetUserId!, debugData: {"On Answer Offer Async"}); // //await invoke(invokeMethod: "InvokeMobile", currentUserID: AppState().getchatUserDetails!.response!.id!, targetUserID: incomingCallData.targetUserId!, debugData: {"On Answer Offer Async"});
// } else { // } else {
var items = payload.toList(); var items = payload!.toList();
if (kDebugMode) { if (kDebugMode) {
print("res: " + items.toString()); print("res: " + items.toString());
} }
CallSessionPayLoad data = CallSessionPayLoad.fromJson(jsonDecode(items.first.toString())); CallSessionPayLoad data = CallSessionPayLoad.fromJson(jsonDecode(items.first.toString()));
RTCSessionDescription description = RTCSessionDescription(data.sdp.sdp, 'answer'); RTCSessionDescription description = RTCSessionDescription(data.sdp!.sdp, 'answer');
_pc.setRemoteDescription(description); _pc!.setRemoteDescription(description);
// } // }
} }
void onHangUpAsync(List<Object> params) { void onHangUpAsync(List<Object?>? params) {
print("--------------------- onHangUp ASYNC ---------------------------------"); print("--------------------- onHangUp ASYNC ---------------------------------");
dynamic items = params.toList(); dynamic items = params!.toList();
// if (kDebugMode) { // if (kDebugMode) {
// logger.i("res: " + items.toString()); // logger.i("res: " + items.toString());
// } // }
if (items[0]["id"] != AppState().chatDetails.response.id) { if (items[0]["id"] != AppState().chatDetails!.response!.id!) {
if (kDebugMode) { if (kDebugMode) {
print("Call Ended By Other User"); print("Call Ended By Other User");
} }
@ -350,12 +351,12 @@ class ChatCallProvider with ChangeNotifier, DiagnosticableTreeMixin {
if (isCallConnected && isUserOnline) { if (isCallConnected && isUserOnline) {
isCallConnected = false; isCallConnected = false;
if (!AppState().isLogged) { if (!AppState().isLogged) {
Navigator.of(locator<NavigationService>().navigatorKey.currentContext).pop(); Navigator.of(locator<NavigationService>().navigatorKey.currentContext!).pop();
} else { } else {
Navigator.of(locator<NavigationService>().navigatorKey.currentContext).popUntil(ModalRoute.withName(HOME)); Navigator.of(locator<NavigationService>().navigatorKey.currentContext!).popUntil(ModalRoute.withName(HOME));
} }
} else { } else {
Navigator.of(locator<NavigationService>().navigatorKey.currentContext).pop(); Navigator.of(locator<NavigationService>().navigatorKey.currentContext!).pop();
} }
}); });
} else { } else {
@ -363,9 +364,9 @@ class ChatCallProvider with ChangeNotifier, DiagnosticableTreeMixin {
endCall(isUserOnline: isUserOnline).then((bool value) { endCall(isUserOnline: isUserOnline).then((bool value) {
if (isCallConnected && isUserOnline) { if (isCallConnected && isUserOnline) {
isCallConnected = false; isCallConnected = false;
Navigator.of(locator<NavigationService>().navigatorKey.currentContext).popUntil(ModalRoute.withName(HOME)); Navigator.of(locator<NavigationService>().navigatorKey.currentContext!).popUntil(ModalRoute.withName(HOME));
} else { } else {
Navigator.of(locator<NavigationService>().navigatorKey.currentContext).pop(); Navigator.of(locator<NavigationService>().navigatorKey.currentContext!).pop();
} }
}); });
} }
@ -377,9 +378,9 @@ class ChatCallProvider with ChangeNotifier, DiagnosticableTreeMixin {
if (isOutGoingCall) { if (isOutGoingCall) {
if (isCallConnected && isUserOnline) { if (isCallConnected && isUserOnline) {
isCallConnected = false; isCallConnected = false;
Navigator.of(locator<NavigationService>().navigatorKey.currentContext).popUntil(ModalRoute.withName(HOME)); Navigator.of(locator<NavigationService>().navigatorKey.currentContext!).popUntil(ModalRoute.withName(HOME));
} else { } else {
Navigator.of(locator<NavigationService>().navigatorKey.currentContext).pop(); Navigator.of(locator<NavigationService>().navigatorKey.currentContext!).pop();
} }
} }
} }
@ -388,7 +389,7 @@ class ChatCallProvider with ChangeNotifier, DiagnosticableTreeMixin {
// Navigator.of(AppRoutes.navigatorKey.currentContext!).popUntil(ModalRoute.withName(AppRoutes.chatDetailed)); // Navigator.of(AppRoutes.navigatorKey.currentContext!).popUntil(ModalRoute.withName(AppRoutes.chatDetailed));
// isCallConnected = false; // isCallConnected = false;
// } // }
// if (items[0]["id"] != AppState().chatDetails!.response!.id && !AppState().isBackgroundCall) { // if (items[0]["id"] != AppState().chatDetails!!.response!.id && !AppState().isBackgroundCall) {
// if (kDebugMode) { // if (kDebugMode) {
// print("Popped Due to Another User"); // print("Popped Due to Another User");
// } // }
@ -418,12 +419,12 @@ class ChatCallProvider with ChangeNotifier, DiagnosticableTreeMixin {
// // "callerEmail": items[0]["email"], // // "callerEmail": items[0]["email"],
// // "callerTitle": items[0]["title"], // // "callerTitle": items[0]["title"],
// // "callerPhone": null, // // "callerPhone": null,
// // "receiverID": AppState().chatDetails!.response!.id, // // "receiverID": AppState().chatDetails!!.response!.id,
// // "receiverName": AppState().chatDetails!.response!.userName, // // "receiverName": AppState().chatDetails!!.response!.userName,
// // "receiverEmail": AppState().chatDetails!.response!.email, // // "receiverEmail": AppState().chatDetails!!.response!.email,
// // "receiverTitle": AppState().chatDetails!.response!.title, // // "receiverTitle": AppState().chatDetails!!.response!.title,
// // "receiverPhone": AppState().chatDetails!.response!.phone, // // "receiverPhone": AppState().chatDetails!!.response!.phone,
// // "title": AppState().chatDetails!.response!.userName!.replaceAll(".", " "), // // "title": AppState().chatDetails!!.response!.userName!.replaceAll(".", " "),
// // "callType": items[1] ? "Video" : "Audio", // // "callType": items[1] ? "Video" : "Audio",
// // }; // // };
// // CallDataModel callData = CallDataModel.fromJson(json); // // CallDataModel callData = CallDataModel.fromJson(json);
@ -436,12 +437,12 @@ class ChatCallProvider with ChangeNotifier, DiagnosticableTreeMixin {
// // "callerEmail": items[0]["email"], // // "callerEmail": items[0]["email"],
// // "callerTitle": items[0]["title"], // // "callerTitle": items[0]["title"],
// // "callerPhone": null, // // "callerPhone": null,
// // "receiverID": AppState().chatDetails!.response!.id, // // "receiverID": AppState().chatDetails!!.response!.id,
// // "receiverName": AppState().chatDetails!.response!.userName, // // "receiverName": AppState().chatDetails!!.response!.userName,
// // "receiverEmail": AppState().chatDetails!.response!.email, // // "receiverEmail": AppState().chatDetails!!.response!.email,
// // "receiverTitle": AppState().chatDetails!.response!.title, // // "receiverTitle": AppState().chatDetails!!.response!.title,
// // "receiverPhone": AppState().chatDetails!.response!.phone, // // "receiverPhone": AppState().chatDetails!!.response!.phone,
// // "title": AppState().chatDetails!.response!.userName!.replaceAll(".", " "), // // "title": AppState().chatDetails!!.response!.userName!.replaceAll(".", " "),
// // "callType": items[1] ? "Video" : "Audio", // // "callType": items[1] ? "Video" : "Audio",
// // }; // // };
// // CallDataModel callData = CallDataModel.fromJson(json); // // CallDataModel callData = CallDataModel.fromJson(json);
@ -480,7 +481,7 @@ class ChatCallProvider with ChangeNotifier, DiagnosticableTreeMixin {
//// Invoke Methods //// Invoke Methods
Future<void> invoke({String invokeMethod, int currentUserID, int targetUserID, var data, int userStatus = 1, var debugData}) async { Future<void> invoke({required String invokeMethod, required int currentUserID, required int targetUserID, var data, int userStatus = 1, var debugData}) async {
List<Object> args = []; List<Object> args = [];
if (invokeMethod == "CallUserAsync") { if (invokeMethod == "CallUserAsync") {
args = [currentUserID, targetUserID, isVideoCall]; args = [currentUserID, targetUserID, isVideoCall];
@ -501,17 +502,17 @@ class ChatCallProvider with ChangeNotifier, DiagnosticableTreeMixin {
args = [debugData]; args = [debugData];
} }
try { try {
await chatHubConnection.invoke("$invokeMethod", args: args); await chatHubConnection!.invoke("$invokeMethod", args: args);
} catch (e) { } catch (e) {
print(e); print(e);
} }
} }
void stopListeners() async { void stopListeners() async {
chatHubConnection.off('OnCallDeclinedAsync'); chatHubConnection!.off('OnCallDeclinedAsync');
chatHubConnection.off('OnCallAcceptedAsync'); chatHubConnection!.off('OnCallAcceptedAsync');
chatHubConnection.off('OnIceCandidateAsync'); chatHubConnection!.off('OnIceCandidateAsync');
chatHubConnection.off('OnAnswerOffer'); chatHubConnection!.off('OnAnswerOffer');
} }
void playRingtone() async { void playRingtone() async {
@ -559,24 +560,24 @@ class ChatCallProvider with ChangeNotifier, DiagnosticableTreeMixin {
// await pc.addStream(_localStream!); // await pc.addStream(_localStream!);
//Changed By Aamir //Changed By Aamir
_localStream?.getTracks().forEach((track) { _localStream?.getTracks().forEach((track) {
pc.addTrack(track, _localStream); pc.addTrack(track, _localStream!);
}); });
pc.onConnectionState = (RTCPeerConnectionState state) {}; pc.onConnectionState = (RTCPeerConnectionState state) {};
pc.onAddStream = (MediaStream stream) { pc.onAddStream = (MediaStream stream) {
remoteRenderer.srcObject = stream; remoteRenderer!.srcObject = stream;
notifyListeners(); notifyListeners();
}; };
pc.onIceCandidate = (RTCIceCandidate e) async { pc.onIceCandidate = (RTCIceCandidate e) async {
if (isIncomingCall) { if (isIncomingCall) {
if (e.candidate != null) { if (e.candidate != null) {
var payload = {"target": incomingCallData.targetUserId, "candidate": e.toMap()}; var payload = {"target": incomingCallData!.targetUserId, "candidate": e.toMap()};
invoke(invokeMethod: "IceCandidateAsync", currentUserID: AppState().chatDetails.response.id, targetUserID: incomingCallData.targetUserId, data: jsonEncode(payload)); invoke(invokeMethod: "IceCandidateAsync", currentUserID: AppState().chatDetails!.response!.id!, targetUserID: incomingCallData!.targetUserId!, data: jsonEncode(payload));
notifyListeners(); notifyListeners();
} }
} else { } else {
if (e.candidate != null) { if (e.candidate != null) {
var payload = {"target": outGoingCallData.callerId, "candidate": e.toMap()}; var payload = {"target": outGoingCallData!.callerId, "candidate": e.toMap()};
invoke(invokeMethod: "IceCandidateAsync", currentUserID: outGoingCallData.callerId, targetUserID: outGoingCallData.receiverId, data: jsonEncode(payload)); invoke(invokeMethod: "IceCandidateAsync", currentUserID: outGoingCallData!.callerId!, targetUserID: outGoingCallData!.receiverId!, data: jsonEncode(payload));
} }
} }
}; };
@ -635,13 +636,13 @@ class ChatCallProvider with ChangeNotifier, DiagnosticableTreeMixin {
// } // }
Future<RTCSessionDescription> _createOffer() async { Future<RTCSessionDescription> _createOffer() async {
RTCSessionDescription description = await _pc.createOffer(); RTCSessionDescription description = await _pc!.createOffer();
// _offer = true; // _offer = true;
return description; return description;
} }
Future<RTCSessionDescription> _createAnswer() async { Future<RTCSessionDescription> _createAnswer() async {
RTCSessionDescription description = await _pc.createAnswer(); RTCSessionDescription description = await _pc!.createAnswer();
// _offer = false; // _offer = false;
return description; return description;
} }
@ -652,7 +653,7 @@ class ChatCallProvider with ChangeNotifier, DiagnosticableTreeMixin {
void micOff() { void micOff() {
isMicOff = !isMicOff; isMicOff = !isMicOff;
_localStream.getAudioTracks().forEach((track) { _localStream!.getAudioTracks().forEach((track) {
track.enabled = !track.enabled; track.enabled = !track.enabled;
}); });
notifyListeners(); notifyListeners();
@ -660,7 +661,7 @@ class ChatCallProvider with ChangeNotifier, DiagnosticableTreeMixin {
void camOff() { void camOff() {
isCamOff = !isCamOff; isCamOff = !isCamOff;
_localStream.getVideoTracks().forEach((track) { _localStream!.getVideoTracks().forEach((track) {
track.enabled = !track.enabled; track.enabled = !track.enabled;
}); });
// if (isCamOff) { // if (isCamOff) {
@ -673,7 +674,7 @@ class ChatCallProvider with ChangeNotifier, DiagnosticableTreeMixin {
void loudOn() { void loudOn() {
isLoudSpeaker = !isLoudSpeaker; isLoudSpeaker = !isLoudSpeaker;
remoteRenderer.srcObject?.getAudioTracks().forEach((track) { remoteRenderer!.srcObject?.getAudioTracks().forEach((track) {
if (isLoudSpeaker) { if (isLoudSpeaker) {
track.enableSpeakerphone(true); track.enableSpeakerphone(true);
} else { } else {
@ -685,7 +686,7 @@ class ChatCallProvider with ChangeNotifier, DiagnosticableTreeMixin {
void switchCamera() { void switchCamera() {
isFrontCamera = !isFrontCamera; isFrontCamera = !isFrontCamera;
Helper.switchCamera(_localStream.getVideoTracks()[0]); Helper.switchCamera(_localStream!.getVideoTracks()[0]);
notifyListeners(); notifyListeners();
} }
@ -695,7 +696,7 @@ class ChatCallProvider with ChangeNotifier, DiagnosticableTreeMixin {
List<MediaDeviceInfo> devices = await navigator.mediaDevices.enumerateDevices(); List<MediaDeviceInfo> devices = await navigator.mediaDevices.enumerateDevices();
remoteRenderer = RTCVideoRenderer(); remoteRenderer = RTCVideoRenderer();
localVideoRenderer ??= RTCVideoRenderer(); localVideoRenderer ??= RTCVideoRenderer();
await localVideoRenderer.initialize(); await localVideoRenderer!.initialize();
try { try {
_localStream = await navigator.mediaDevices.getUserMedia({ _localStream = await navigator.mediaDevices.getUserMedia({
'audio': true, 'audio': true,
@ -714,8 +715,8 @@ class ChatCallProvider with ChangeNotifier, DiagnosticableTreeMixin {
if (kDebugMode) { if (kDebugMode) {
print(_localStream..toString()); print(_localStream..toString());
} }
localVideoRenderer.srcObject = _localStream; localVideoRenderer!.srcObject = _localStream;
localVideoRenderer.value = (const RTCVideoValue(width: 200, height: 200, renderVideo: true)); localVideoRenderer!.value = (const RTCVideoValue(width: 200, height: 200, renderVideo: true));
print("Working localStream"); print("Working localStream");
} catch (e) { } catch (e) {
print("Failed to get user media: $e"); print("Failed to get user media: $e");
@ -781,7 +782,7 @@ class ChatCallProvider with ChangeNotifier, DiagnosticableTreeMixin {
// : audioConstraints); // : audioConstraints);
// localVideoRenderer.srcObject = _localStream; // localVideoRenderer.srcObject = _localStream;
await remoteRenderer.initialize(); await remoteRenderer!.initialize();
notifyListeners(); notifyListeners();
} }
@ -800,7 +801,7 @@ class ChatCallProvider with ChangeNotifier, DiagnosticableTreeMixin {
} }
void connectIncomingCall() { void connectIncomingCall() {
invoke(invokeMethod: "answerCallAsync", currentUserID: AppState().getchatUserDetails.response.id, targetUserID: incomingCallData.targetUserId); invoke(invokeMethod: "answerCallAsync", currentUserID: AppState().getchatUserDetails.response!.id!, targetUserID: incomingCallData!.targetUserId!);
isIncomingCallLoader = false; isIncomingCallLoader = false;
isIncomingCall = true; isIncomingCall = true;
// isVideoCall = true; // isVideoCall = true;
@ -842,7 +843,7 @@ class ChatCallProvider with ChangeNotifier, DiagnosticableTreeMixin {
} }
class ChatService extends BaseService { class ChatService extends BaseService {
Future<UserAutoLoginModel> getUserCallToken({String userid}) async { Future<UserAutoLoginModel> getUserCallToken({required String userid}) async {
UserAutoLoginModel userLoginResponse = UserAutoLoginModel(); UserAutoLoginModel userLoginResponse = UserAutoLoginModel();
baseAppClient.post( baseAppClient.post(
"${ApiConsts.chatLoginTokenUrl}externaluserlogin", "${ApiConsts.chatLoginTokenUrl}externaluserlogin",

Loading…
Cancel
Save