diff --git a/lib/controllers/api_routes/urls.dart b/lib/controllers/api_routes/urls.dart index 6749e87f..6bb88970 100644 --- a/lib/controllers/api_routes/urls.dart +++ b/lib/controllers/api_routes/urls.dart @@ -15,7 +15,10 @@ class URLs { // static final String _baseUrl = "$_host/v3/mobile"; // v3 for production CM,PM,TM // static final String _baseUrl = "$_host/v5/mobile"; // v5 for data segregation - static const String chatHubUrl = "https://apiderichat.hmg.com/chathub/api"; // new V2 apis + static const String chatHubUrl = "https://apiderichat.hmg.com/chathub"; + static const String chatHubUrlApi = "$chatHubUrl/api"; // new V2 apis + static const String chatHubUrlChat = "$chatHubUrl/hubs/chat"; // new V2 apis + static const String chatApiKey = "f53a98286f82798d588f67a7f0db19f7aebc839e"; // new V2 apis static String _host = host1; @@ -341,4 +344,10 @@ class URLs { static get convertDetailToComplete => '$_baseUrl/AssetInventory/ConvertDetailToComplete'; static get getClassification => '$_baseUrl/AssetInventory/Classification'; + + //chat + static get chatSdkToken => '$chatHubUrlApi/auth/sdk-token'; + + //survey + static get getQuestionnaire => '$_baseUrl/SurveyQuestionnaire/GetQuestionnaire'; } diff --git a/lib/main.dart b/lib/main.dart index 59cb86ee..6b47386e 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -30,6 +30,7 @@ import 'package:test_sa/controllers/providers/api/status_drop_down/report/servic import 'package:test_sa/modules/asset_inventory_module/provider/asset_inventory_provider.dart'; import 'package:test_sa/modules/cm_module/service_request_detail_provider.dart'; import 'package:test_sa/modules/cm_module/views/nurse/create_new_request_view.dart'; +import 'package:test_sa/modules/cx_module/chat/chat_provider.dart'; import 'package:test_sa/modules/tm_module/tasks_wo/create_task_view.dart'; import 'package:test_sa/modules/traf_module/create_traf_request_page.dart'; import 'package:test_sa/modules/traf_module/traf_request_provider.dart'; @@ -99,6 +100,7 @@ import 'controllers/providers/api/gas_refill_comments.dart'; import 'controllers/providers/api/user_provider.dart'; import 'controllers/providers/settings/setting_provider.dart'; import 'dashboard_latest/dashboard_provider.dart'; +import 'modules/cx_module/survey/survey_provider.dart'; import 'new_views/pages/gas_refill_request_form.dart'; import 'providers/lookups/classification_lookup_provider.dart'; import 'providers/lookups/department_lookup_provider.dart'; @@ -238,8 +240,11 @@ class MyApp extends StatelessWidget { ChangeNotifierProvider(create: (_) => ServiceReportRepairLocationProvider()), ChangeNotifierProvider(create: (_) => ServiceRequestFaultDescriptionProvider()), - ///todo deleted - //ChangeNotifierProvider(create: (_) => ServiceReportVisitOperatorProvider()), + //chat + ChangeNotifierProvider(create: (_) => ChatProvider()), + //chat + ChangeNotifierProvider(create: (_) => SurveyProvider()), + ///todo deleted //ChangeNotifierProvider(create: (_) => ServiceReportMaintenanceSituationProvider()), //ChangeNotifierProvider(create: (_) => ServiceReportUsersProvider()), diff --git a/lib/models/user.dart b/lib/models/user.dart index 0bb4ab23..20158748 100644 --- a/lib/models/user.dart +++ b/lib/models/user.dart @@ -112,7 +112,6 @@ class User { } } - Map toUpdateProfileJson() { Map jsonObject = {}; // if (departmentId != null) jsonObject["department"] = departmentId; diff --git a/lib/modules/cm_module/views/service_request_detail_main_view.dart b/lib/modules/cm_module/views/service_request_detail_main_view.dart index bd89910c..aeed58a1 100644 --- a/lib/modules/cm_module/views/service_request_detail_main_view.dart +++ b/lib/modules/cm_module/views/service_request_detail_main_view.dart @@ -1,3 +1,4 @@ +import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:test_sa/controllers/providers/api/user_provider.dart'; @@ -10,6 +11,8 @@ import 'package:test_sa/models/enums/work_order_next_step.dart'; import 'package:test_sa/models/helper_data_models/workorder/work_order_helper_models.dart'; import 'package:test_sa/modules/cm_module/service_request_detail_provider.dart'; import 'package:test_sa/modules/cm_module/views/components/bottom_sheets/service_request_bottomsheet.dart'; +import 'package:test_sa/modules/cx_module/chat/chat_page.dart'; +import 'package:test_sa/modules/cx_module/survey/survey_page.dart'; import 'package:test_sa/new_views/app_style/app_color.dart'; import 'package:test_sa/new_views/common_widgets/default_app_bar.dart'; import 'package:test_sa/views/widgets/loaders/no_data_found.dart'; @@ -81,6 +84,18 @@ class _ServiceRequestDetailMainState extends State { Navigator.pop(context); }, actions: [ + IconButton( + icon: const Icon(Icons.feedback_rounded), + onPressed: () { + Navigator.push(context, CupertinoPageRoute(builder: (context) => SurveyPage(moduleId: 1, requestId: widget.requestId))); + }, + ), + IconButton( + icon: const Icon(Icons.chat_bubble), + onPressed: () { + Navigator.push(context, CupertinoPageRoute(builder: (context) => ChatPage(moduleId: 1, requestId: widget.requestId))); + }, + ), isNurse ? IconButton( icon: 'qr'.toSvgAsset( diff --git a/lib/modules/cx_module/chat/api_client.dart b/lib/modules/cx_module/chat/api_client.dart new file mode 100644 index 00000000..63e57b93 --- /dev/null +++ b/lib/modules/cx_module/chat/api_client.dart @@ -0,0 +1,295 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter/foundation.dart'; +import 'package:http/http.dart'; +import 'package:http/io_client.dart'; +// ignore_for_file: avoid_annotating_with_dynamic + +typedef FactoryConstructor = U Function(dynamic); + +class APIError { + dynamic errorCode; + int? errorType; + String? errorMessage; + int? errorStatusCode; + + APIError(this.errorCode, this.errorMessage, this.errorType, this.errorStatusCode); + + Map toJson() => {'errorCode': errorCode, 'errorMessage': errorMessage, 'errorType': errorType, 'ErrorStatusCode': errorStatusCode}; + + @override + String toString() { + return jsonEncode(this); + } +} + +APIException _throwAPIException(Response response) { + switch (response.statusCode) { + case 200: + APIError? apiError; + if (response.body != null && response.body.isNotEmpty) { + var jsonError = jsonDecode(response.body); + print(jsonError); + apiError = APIError(jsonError['ErrorCode'], jsonError['ErrorMessage'], jsonError['ErrorType'], jsonError['ErrorStatusCode']); + } + return APIException(APIException.BAD_REQUEST, error: apiError); + case 400: + APIError? apiError; + if (response.body != null && response.body.isNotEmpty) { + var jsonError = jsonDecode(response.body); + apiError = APIError(jsonError['ErrorCode'], jsonError['ErrorMessage'], jsonError['ErrorType'], jsonError['ErrorStatusCode']); + } + return APIException(APIException.BAD_REQUEST, error: apiError); + case 401: + return APIException(APIException.UNAUTHORIZED); + case 403: + return APIException(APIException.FORBIDDEN); + case 404: + return APIException(APIException.NOT_FOUND); + case 500: + return APIException(APIException.INTERNAL_SERVER_ERROR); + case 444: + var downloadUrl = response.headers["location"]; + return APIException(APIException.UPGRADE_REQUIRED, arguments: downloadUrl); + default: + return APIException(APIException.OTHER); + } +} + +class ApiClient { + static final ApiClient _instance = ApiClient._internal(); + + ApiClient._internal(); + + factory ApiClient() => _instance; + + Future postJsonForObject(FactoryConstructor factoryConstructor, String url, T jsonObject, + {String? token, Map? queryParameters, Map? headers, int retryTimes = 0, bool isFormData = false}) async { + var _headers = {'Accept': 'application/json'}; + if (headers != null && headers.isNotEmpty) { + _headers.addAll(headers); + } + if (!kReleaseMode) { + print("Url:$url"); + var bodyJson = json.encode(jsonObject); + print("body:$bodyJson"); + } + var response = await postJsonForResponse(url, jsonObject, token: token, queryParameters: queryParameters, headers: _headers, retryTimes: retryTimes, isFormData: isFormData); + try { + if (!kReleaseMode) { + // logger.i("Url: " + url); + // logger.i("res: " + response.body); + } + + var jsonData = jsonDecode(response.body); + if (jsonData["IsAuthenticated"] != null) { + // AppState().setIsAuthenticated = jsonData["IsAuthenticated"]; + } + + // if(url.contains("GetOfferDiscountsConfigData")) { + // jsonData["ErrorMessage"] = "Service Not Available"; + // jsonData["ErrorEndUserMessage"] = "Service Not Available"; + // } + + if (jsonData["ErrorMessage"] == null) { + return factoryConstructor(jsonData); + } else if (jsonData["MessageStatus"] == 2 && jsonData["IsOTPMaxLimitExceed"] == true) { + // await Utils.performLogout(AppRoutes.navigatorKey.currentContext, null); + throw const APIException(APIException.UNAUTHORIZED, error: null); + } else { + APIError? apiError; + apiError = APIError(jsonData['ErrorCode'], jsonData['ErrorEndUserMessage'], jsonData['ErrorType'] ?? 0, jsonData['ErrorStatusCode']); + throw APIException(APIException.BAD_REQUEST, error: apiError); + } + } catch (ex) { + if (ex is APIException) { + rethrow; + } else { + throw APIException(APIException.BAD_RESPONSE_FORMAT, arguments: ex); + } + } + } + + Future postJsonForResponse(String url, T jsonObject, + {String? token, Map? queryParameters, Map? headers, int retryTimes = 0, bool isFormData = false}) async { + String? requestBody; + late Map stringObj; + if (jsonObject != null) { + requestBody = jsonEncode(jsonObject); + if (headers == null) { + headers = {'Content-Type': 'application/json'}; + } else { + headers['Content-Type'] = 'application/json'; + } + } + + if (isFormData) { + headers = {'Content-Type': 'application/x-www-form-urlencoded'}; + stringObj = ((jsonObject ?? {}) as Map).map((key, value) => MapEntry(key, value?.toString() ?? "")); + } + + return await _postForResponse(url, isFormData ? stringObj : requestBody, token: token, queryParameters: queryParameters, headers: headers, retryTimes: retryTimes); + } + + Future _postForResponse(String url, requestBody, {String? token, Map? queryParameters, Map? headers, int retryTimes = 0}) async { + try { + var _headers = {}; + if (token != null) { + _headers['Authorization'] = 'Bearer $token'; + } + + if (headers != null && headers.isNotEmpty) { + _headers.addAll(headers); + } + + if (queryParameters != null) { + var queryString = new Uri(queryParameters: queryParameters).query; + url = url + '?' + queryString; + } + var response = await _post(Uri.parse(url), body: requestBody, headers: _headers).timeout(Duration(seconds: 120)); + + if (response.statusCode >= 200 && response.statusCode < 300) { + return response; + } else { + throw _throwAPIException(response); + } + } on SocketException catch (e) { + if (retryTimes > 0) { + print('will retry after 3 seconds...'); + await Future.delayed(Duration(seconds: 3)); + return await _postForResponse(url, requestBody, token: token, queryParameters: queryParameters, headers: headers, retryTimes: retryTimes - 1); + } else { + throw APIException(APIException.OTHER, arguments: e); + } + } on HttpException catch (e) { + if (retryTimes > 0) { + print('will retry after 3 seconds...'); + await Future.delayed(Duration(seconds: 3)); + return await _postForResponse(url, requestBody, token: token, queryParameters: queryParameters, headers: headers, retryTimes: retryTimes - 1); + } else { + throw APIException(APIException.OTHER, arguments: e); + } + } on TimeoutException catch (e) { + throw APIException(APIException.TIMEOUT, arguments: e); + } on ClientException catch (e) { + if (retryTimes > 0) { + print('will retry after 3 seconds...'); + await Future.delayed(Duration(seconds: 3)); + return await _postForResponse(url, requestBody, token: token, queryParameters: queryParameters, headers: headers, retryTimes: retryTimes - 1); + } else { + throw APIException(APIException.OTHER, arguments: e); + } + } + } + + Future getJsonForResponse(String url, {String? token, Map? queryParameters, Map? headers, int retryTimes = 0}) async { + if (headers == null) { + headers = {'Content-Type': 'application/json'}; + } else { + headers['Content-Type'] = 'application/json'; + } + + if (!kReleaseMode) { + print("Url:$url"); + // var bodyJson = json.encode(jsonObject); + // print("body:$bodyJson"); + } + + return await _getForResponse(url, token: token, queryParameters: queryParameters, headers: headers, retryTimes: retryTimes); + } + + Future _getForResponse(String url, {String? token, Map? queryParameters, Map? headers, int retryTimes = 0}) async { + try { + var _headers = {}; + if (token != null) { + _headers['Authorization'] = 'Bearer $token'; + } + + if (headers != null && headers.isNotEmpty) { + _headers.addAll(headers); + } + + if (queryParameters != null) { + var queryString = new Uri(queryParameters: queryParameters).query; + url = url + '?' + queryString; + } + var response = await _get(Uri.parse(url), headers: _headers).timeout(Duration(seconds: 60)); + + if (response.statusCode >= 200 && response.statusCode < 300) { + return response; + } else { + throw _throwAPIException(response); + } + } on SocketException catch (e) { + if (retryTimes > 0) { + print('will retry after 3 seconds...'); + await Future.delayed(Duration(seconds: 3)); + return await _getForResponse(url, token: token, queryParameters: queryParameters, headers: headers, retryTimes: retryTimes - 1); + } else { + throw APIException(APIException.OTHER, arguments: e); + } + } on HttpException catch (e) { + if (retryTimes > 0) { + print('will retry after 3 seconds...'); + await Future.delayed(Duration(seconds: 3)); + return await _getForResponse(url, token: token, queryParameters: queryParameters, headers: headers, retryTimes: retryTimes - 1); + } else { + throw APIException(APIException.OTHER, arguments: e); + } + } on TimeoutException catch (e) { + throw APIException(APIException.TIMEOUT, arguments: e); + } on ClientException catch (e) { + if (retryTimes > 0) { + print('will retry after 3 seconds...'); + await Future.delayed(Duration(seconds: 3)); + return await _getForResponse(url, token: token, queryParameters: queryParameters, headers: headers, retryTimes: retryTimes - 1); + } else { + throw APIException(APIException.OTHER, arguments: e); + } + } + } + + Future _get(url, {Map? headers}) => _withClient((client) => client.get(url, headers: headers)); + + bool _certificateCheck(X509Certificate cert, String host, int port) => true; + + Future _withClient(Future Function(Client) fn) async { + var httpClient = HttpClient()..badCertificateCallback = _certificateCheck; + var client = IOClient(httpClient); + try { + return await fn(client); + } finally { + client.close(); + } + } + + Future _post(url, {Map? headers, body, Encoding? encoding}) => _withClient((client) => client.post(url, headers: headers, body: body, encoding: encoding)); +} + +class APIException implements Exception { + static const String BAD_REQUEST = 'api_common_bad_request'; + static const String UNAUTHORIZED = 'api_common_unauthorized'; + static const String FORBIDDEN = 'api_common_forbidden'; + static const String NOT_FOUND = 'api_common_not_found'; + static const String INTERNAL_SERVER_ERROR = 'api_common_internal_server_error'; + static const String UPGRADE_REQUIRED = 'api_common_upgrade_required'; + static const String BAD_RESPONSE_FORMAT = 'api_common_bad_response_format'; + static const String OTHER = 'api_common_http_error'; + static const String TIMEOUT = 'api_common_http_timeout'; + static const String UNKNOWN = 'unexpected_error'; + + final String message; + final APIError? error; + final arguments; + + const APIException(this.message, {this.arguments, this.error}); + + Map toJson() => {'message': message, 'error': error, 'arguments': '$arguments'}; + + @override + String toString() { + return jsonEncode(this); + } +} diff --git a/lib/modules/cx_module/chat/chat_api_client.dart b/lib/modules/cx_module/chat/chat_api_client.dart index fc473329..985666c0 100644 --- a/lib/modules/cx_module/chat/chat_api_client.dart +++ b/lib/modules/cx_module/chat/chat_api_client.dart @@ -6,10 +6,15 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:http/http.dart'; import 'package:test_sa/controllers/api_routes/api_manager.dart'; +import 'package:test_sa/controllers/api_routes/urls.dart'; import 'package:test_sa/extensions/string_extensions.dart'; - +import 'package:http/http.dart' as http; +import 'api_client.dart'; +import 'model/chat_login_response_model.dart'; +import 'model/chat_participant_model.dart'; import 'model/get_search_user_chat_model.dart'; -import 'model/get_user_login_token_model.dart'; +import 'model/get_user_login_token_model.dart' as userLoginTokenModel; +import 'model/user_chat_history_model.dart'; // import 'package:mohem_flutter_app/api/api_client.dart'; // import 'package:mohem_flutter_app/app_state/app_state.dart'; @@ -33,100 +38,137 @@ class ChatApiClient { factory ChatApiClient() => _instance; - Future getUserLoginToken() async { - UserAutoLoginModel userLoginResponse = UserAutoLoginModel(); - String? deviceToken = AppState().getIsHuawei ? AppState().getHuaweiPushToken : AppState().getDeviceToken; - Response response = await ApiClient().postJsonForResponse( - "${ApiConsts.chatLoginTokenUrl}externaluserlogin", - { - "employeeNumber": AppState().memberInformationList!.eMPLOYEENUMBER.toString(), - "password": "FxIu26rWIKoF8n6mpbOmAjDLphzFGmpG", - "isMobile": true, - "platform": Platform.isIOS ? "ios" : "android", - "deviceToken": AppState().getIsHuawei ? AppState().getHuaweiPushToken : AppState().getDeviceToken, - "isHuaweiDevice": AppState().getIsHuawei, - "voipToken": Platform.isIOS ? "80a3b01fc1ef2453eb4f1daa4fc31d8142d9cb67baf848e91350b607971fe2ba" : "", - }, - ); + ChatLoginResponse? chatLoginResponse; + + Future getChatLoginToken(int moduleId, int requestId, String title, String employeeNumber) async { + Response response = await ApiClient().postJsonForResponse(URLs.chatSdkToken, { + "apiKey": URLs.chatApiKey, + "employeeNumber": employeeNumber, + "userDetails": {"userName": ApiManager.instance.user?.username, "email": ApiManager.instance.user?.email}, + "contextEnabled": true, + "moduleCode": moduleId.toString(), + "referenceId": requestId.toString(), + "referenceType": "ticket", + "title": title + }); if (!kReleaseMode) { // logger.i("login-res: " + response.body); } if (response.statusCode == 200) { - userLoginResponse = user.userAutoLoginModelFromJson(response.body); - } else if (response.statusCode == 501 || response.statusCode == 502 || response.statusCode == 503 || response.statusCode == 504) { - getUserLoginToken(); - } else { - userLoginResponse = user.userAutoLoginModelFromJson(response.body); - userLoginResponse.errorResponses!.first.message!.showToast; + chatLoginResponse = ChatLoginResponse.fromJson(jsonDecode(response.body)); } - return userLoginResponse; + return chatLoginResponse; } - Future getChatMemberFromSearch(String searchParam, int cUserId, int pageNo) async { - ChatUserModel chatUserModel; - Response response = await ApiClient().postJsonForResponse("${ApiConsts.chatLoginTokenUrl}getUserWithStatusAndFavAsync", {"employeeNumber": cUserId, "userName": searchParam, "pageNumber": pageNo}, - token: AppState().chatDetails!.response!.token); + Future loadParticipants(int moduleId, int referenceId,String? assigneeEmployeeNumber) async { + Response response = await ApiClient().getJsonForResponse("${URLs.chatHubUrlApi}/chat/context/$moduleId/$referenceId?assigneeEmployeeNumber=$assigneeEmployeeNumber", token: chatLoginResponse!.token); + if (!kReleaseMode) { - logger.i("res: " + response.body); + // logger.i("login-res: " + response.body); + } + if (response.statusCode == 200) { + return ChatParticipantModel.fromJson(jsonDecode(response.body)); + } else { + return null; } - chatUserModel = chatUserModelFromJson(response.body); - return chatUserModel; } - //Get User Recent Chats - Future getRecentChats() async { + Future loadChatHistory(int moduleId, int referenceId, String myId, String otherId) async { + Response response = await ApiClient().postJsonForResponse( + "${URLs.chatHubUrlApi}/UserChatHistory/GetUserChatHistory/$myId/$otherId/0", {"moduleCode": moduleId.toString(), "referenceId": referenceId.toString()}, + token: chatLoginResponse!.token); try { - Response response = - - - // await ApiManager.instance.get(URLs.getAllRequestsAndCount,h); - - - await ApiClient().getJsonForResponse( - "${ApiConsts.chatRecentUrl}getchathistorybyuserid", - token: AppState().chatDetails!.response!.token, - ); - if (!kReleaseMode) { - logger.i("res: " + response.body); + if (response.statusCode == 200) { + return UserChatHistoryModel.fromJson(jsonDecode(response.body)); + } else { + return null; } - return ChatUserModel.fromJson( - json.decode(response.body), - ); - } catch (e) { - throw e; + } catch (ex) { + return null; } } - // // Get Favorite Users - // Future getFavUsers() async { - // Response favRes = await ApiClient().getJsonForResponse( - // "${ApiConsts.chatFavUser}getFavUserById/${AppState().chatDetails!.response!.id}", - // token: AppState().chatDetails!.response!.token, - // ); - // if (!kReleaseMode) { - // logger.i("res: " + favRes.body); - // } - // return ChatUserModel.fromJson(json.decode(favRes.body)); - // } - - //Get User Chat History - Future getSingleUserChatHistory({required int senderUID, required int receiverUID, required bool loadMore, bool isNewChat = false, required int paginationVal}) async { + Future sendTextMessage(String message, int conversationId) async { try { - Response response = await ApiClient().getJsonForResponse( - "${ApiConsts.chatSingleUserHistoryUrl}GetUserChatHistory/$senderUID/$receiverUID/$paginationVal", - token: AppState().chatDetails!.response!.token, - ); - if (!kReleaseMode) { - logger.i("res: " + response.body); + Response response = + await ApiClient().postJsonForResponse("${URLs.chatHubUrlApi}/chat/conversations/$conversationId/messages", {"content": message, "messageType": "Text"}, token: chatLoginResponse!.token); + + if (response.statusCode == 200) { + return ChatResponse.fromJson(jsonDecode(response.body)); + } else { + return null; } - return response; - } catch (e) { - getSingleUserChatHistory(senderUID: senderUID, receiverUID: receiverUID, loadMore: loadMore, paginationVal: paginationVal); - throw e; + } catch (ex) { + print(ex); + return null; } } +// Future getChatMemberFromSearch(String searchParam, int cUserId, int pageNo) async { +// ChatUserModel chatUserModel; +// Response response = await ApiClient().postJsonForResponse("${ApiConsts.chatLoginTokenUrl}getUserWithStatusAndFavAsync", {"employeeNumber": cUserId, "userName": searchParam, "pageNumber": pageNo}, +// token: AppState().chatDetails!.response!.token); +// if (!kReleaseMode) { +// logger.i("res: " + response.body); +// } +// chatUserModel = chatUserModelFromJson(response.body); +// return chatUserModel; +// } + +// //Get User Recent Chats +// Future getRecentChats() async { +// try { +// Response response = +// +// +// // await ApiManager.instance.get(URLs.getAllRequestsAndCount,h); +// +// +// await ApiClient().getJsonForResponse( +// "${ApiConsts.chatRecentUrl}getchathistorybyuserid", +// token: AppState().chatDetails!.response!.token, +// ); +// if (!kReleaseMode) { +// logger.i("res: " + response.body); +// } +// return ChatUserModel.fromJson( +// json.decode(response.body), +// ); +// } catch (e) { +// throw e; +// } +// } + +// // Get Favorite Users +// Future getFavUsers() async { +// Response favRes = await ApiClient().getJsonForResponse( +// "${ApiConsts.chatFavUser}getFavUserById/${AppState().chatDetails!.response!.id}", +// token: AppState().chatDetails!.response!.token, +// ); +// if (!kReleaseMode) { +// logger.i("res: " + favRes.body); +// } +// return ChatUserModel.fromJson(json.decode(favRes.body)); +// } + +// //Get User Chat History +// Future getSingleUserChatHistory({required int senderUID, required int receiverUID, required bool loadMore, bool isNewChat = false, required int paginationVal}) async { +// try { +// Response response = await ApiClient().getJsonForResponse( +// "${ApiConsts.chatSingleUserHistoryUrl}GetUserChatHistory/$senderUID/$receiverUID/$paginationVal", +// token: AppState().chatDetails!.response!.token, +// ); +// if (!kReleaseMode) { +// logger.i("res: " + response.body); +// } +// return response; +// } catch (e) { +// getSingleUserChatHistory(senderUID: senderUID, receiverUID: receiverUID, loadMore: loadMore, paginationVal: paginationVal); +// throw e; +// } +// } + // //Favorite Users // Future favUser({required int userID, required int targetUserID}) async { // Response response = await ApiClient().postJsonForResponse("${ApiConsts.chatFavUser}addFavUser", {"targetUserId": targetUserID, "userId": userID}, token: AppState().chatDetails!.response!.token); @@ -137,54 +179,54 @@ class ChatApiClient { // return favoriteChatUser; // } - // //UnFavorite Users - // Future unFavUser({required int userID, required int targetUserID}) async { - // try { - // Response response = await ApiClient().postJsonForResponse( - // "${ApiConsts.chatFavUser}deleteFavUser", - // {"targetUserId": targetUserID, "userId": userID}, - // token: AppState().chatDetails!.response!.token, - // ); - // if (!kReleaseMode) { - // logger.i("res: " + response.body); - // } - // fav.FavoriteChatUser favoriteChatUser = fav.FavoriteChatUser.fromRawJson(response.body); - // return favoriteChatUser; - // } catch (e) { - // e as APIException; - // throw e; - // } - // } +// //UnFavorite Users +// Future unFavUser({required int userID, required int targetUserID}) async { +// try { +// Response response = await ApiClient().postJsonForResponse( +// "${ApiConsts.chatFavUser}deleteFavUser", +// {"targetUserId": targetUserID, "userId": userID}, +// token: AppState().chatDetails!.response!.token, +// ); +// if (!kReleaseMode) { +// logger.i("res: " + response.body); +// } +// fav.FavoriteChatUser favoriteChatUser = fav.FavoriteChatUser.fromRawJson(response.body); +// return favoriteChatUser; +// } catch (e) { +// e as APIException; +// throw e; +// } +// } // Upload Chat Media - Future uploadMedia(String userId, File file, String fileSource) async { - if (kDebugMode) { - print("${ApiConsts.chatMediaImageUploadUrl}upload"); - print(AppState().chatDetails!.response!.token); - } - - dynamic request = MultipartRequest('POST', Uri.parse('${ApiConsts.chatMediaImageUploadUrl}upload')); - request.fields.addAll({'userId': userId, 'fileSource': fileSource}); - request.files.add(await MultipartFile.fromPath('files', file.path)); - request.headers.addAll({'Authorization': 'Bearer ${AppState().chatDetails!.response!.token}'}); - StreamedResponse response = await request.send(); - String data = await response.stream.bytesToString(); - if (!kReleaseMode) { - logger.i("res: " + data); - } - return jsonDecode(data); - } +// Future uploadMedia(String userId, File file, String fileSource) async { +// if (kDebugMode) { +// print("${ApiConsts.chatMediaImageUploadUrl}upload"); +// print(AppState().chatDetails!.response!.token); +// } +// +// dynamic request = MultipartRequest('POST', Uri.parse('${ApiConsts.chatMediaImageUploadUrl}upload')); +// request.fields.addAll({'userId': userId, 'fileSource': fileSource}); +// request.files.add(await MultipartFile.fromPath('files', file.path)); +// request.headers.addAll({'Authorization': 'Bearer ${AppState().chatDetails!.response!.token}'}); +// StreamedResponse response = await request.send(); +// String data = await response.stream.bytesToString(); +// if (!kReleaseMode) { +// logger.i("res: " + data); +// } +// return jsonDecode(data); +// } - // Download File For Chat - Future downloadURL({required String fileName, required String fileTypeDescription, required int fileSource}) async { - Response response = await ApiClient().postJsonForResponse( - "${ApiConsts.chatMediaImageUploadUrl}download", - {"fileType": fileTypeDescription, "fileName": fileName, "fileSource": fileSource}, - token: AppState().chatDetails!.response!.token, - ); - Uint8List data = Uint8List.fromList(response.bodyBytes); - return data; - } +// Download File For Chat +// Future downloadURL({required String fileName, required String fileTypeDescription, required int fileSource}) async { +// Response response = await ApiClient().postJsonForResponse( +// "${ApiConsts.chatMediaImageUploadUrl}download", +// {"fileType": fileTypeDescription, "fileName": fileName, "fileSource": fileSource}, +// token: AppState().chatDetails!.response!.token, +// ); +// Uint8List data = Uint8List.fromList(response.bodyBytes); +// return data; +// } // //Get Chat Users & Favorite Images // Future> getUsersImages({required List encryptedEmails}) async { diff --git a/lib/modules/cx_module/chat/chat_page.dart b/lib/modules/cx_module/chat/chat_page.dart index 5c5e34a9..75cb2fba 100644 --- a/lib/modules/cx_module/chat/chat_page.dart +++ b/lib/modules/cx_module/chat/chat_page.dart @@ -1,17 +1,27 @@ import 'package:audio_waveforms/audio_waveforms.dart'; import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import 'package:test_sa/extensions/context_extension.dart'; import 'package:test_sa/extensions/int_extensions.dart'; import 'package:test_sa/extensions/string_extensions.dart'; import 'package:test_sa/extensions/text_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart'; +import 'package:test_sa/modules/cx_module/chat/chat_api_client.dart'; +import 'package:test_sa/modules/cx_module/chat/chat_provider.dart'; import 'package:test_sa/new_views/app_style/app_color.dart'; +import 'package:test_sa/new_views/common_widgets/app_filled_button.dart'; import 'package:test_sa/new_views/common_widgets/default_app_bar.dart'; enum ChatState { idle, voiceRecordingStarted, voiceRecordingCompleted } class ChatPage extends StatefulWidget { - ChatPage({Key? key}) : super(key: key); + int moduleId; + int requestId; + String title; + bool readOnly; + + ChatPage({Key? key, required this.moduleId, required this.requestId, this.title = "Chat", this.readOnly = false}) : super(key: key); @override _ChatPageState createState() { @@ -27,11 +37,14 @@ class _ChatPageState extends State { final RecorderController recorderController = RecorderController(); PlayerController playerController = PlayerController(); + TextEditingController textEditingController = TextEditingController(); + ChatState chatState = ChatState.idle; @override void initState() { super.initState(); + getChatToken(); playerController.addListener(() async { // if (playerController.playerState == PlayerState.playing && playerController.maxDuration == await playerController.getDuration()) { // await playerController.stopPlayer(); @@ -40,6 +53,11 @@ class _ChatPageState extends State { }); } + void getChatToken() { + String assigneeEmployeeNumber = ""; + Provider.of(context, listen: false).getUserAutoLoginToken(widget.moduleId, widget.requestId + 2, widget.title, context.settingProvider.username, assigneeEmployeeNumber); + } + @override void dispose() { playerController.dispose(); @@ -50,342 +68,394 @@ class _ChatPageState extends State { @override Widget build(BuildContext context) { return Scaffold( - backgroundColor: AppColor.white10, - appBar: const DefaultAppBar(title: "Req No. 343443"), - body: Column( - children: [ - Container( - color: AppColor.neutral50, - constraints: const BoxConstraints(maxHeight: 56), - padding: const EdgeInsets.all(16), - child: Row( + backgroundColor: AppColor.white10, + appBar: DefaultAppBar(title: widget.title), + body: Consumer(builder: (context, chatProvider, child) { + if (chatProvider.chatLoginTokenLoading) return const CircularProgressIndicator(color: AppColor.primary10, strokeWidth: 3).center; + + if (chatProvider.chatLoginResponse == null) { + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.center, children: [ Text( - "Engineer: Mahmoud Shrouf", + "Failed to connect chat", overflow: TextOverflow.ellipsis, - maxLines: 2, - style: AppTextStyles.bodyText2.copyWith(color: AppColor.white10), - ).expanded, - 4.width, - Text( - "View All Documents", - style: AppTextStyles.bodyText.copyWith( - color: AppColor.white10, - decoration: TextDecoration.underline, - decorationColor: AppColor.white10, - ), + maxLines: 1, + style: AppTextStyles.heading6.copyWith(color: AppColor.neutral50, fontWeight: FontWeight.w500), ), + 24.height, + AppFilledButton( + label: "Retry", + maxWidth: true, + buttonColor: AppColor.primary10, + onPressed: () async { + getChatToken(); + }, + ).paddingOnly(start: 48, end: 48) ], - ), - ), - Container( - // width: double.infinity, - color: AppColor.neutral100, - child: ListView( + ).center; + } + return Column( + children: [ + Container( + color: AppColor.neutral50, + constraints: const BoxConstraints(maxHeight: 56), padding: const EdgeInsets.all(16), - children: [ - recipientMsgCard(true, "Please let me know what is the issue? Please let me know what is the issue?"), - recipientMsgCard(false, "testing"), - recipientMsgCard(false, "testing testing testing"), - dateCard("Mon 27 Oct"), - senderMsgCard(true, "Please let me know what is the issue? Please let me know what is the issue?"), - senderMsgCard(false, "Please let me know what is the issue?"), - ], - )).expanded, - Divider(height: 1, thickness: 1, color: const Color(0xff767676).withOpacity(.11)), - SafeArea( - child: ConstrainedBox( - constraints: const BoxConstraints(minHeight: 56), - child: Row( - children: [ - if (chatState == ChatState.idle) ...[ - TextFormField( - cursorColor: AppColor.neutral50, - style: AppTextStyles.bodyText.copyWith(color: AppColor.neutral50), - minLines: 1, - maxLines: 3, - textInputAction: TextInputAction.none, - keyboardType: TextInputType.multiline, - decoration: InputDecoration( - enabledBorder: InputBorder.none, - focusedBorder: InputBorder.none, - border: InputBorder.none, - errorBorder: InputBorder.none, - contentPadding: const EdgeInsets.only(left: 16, top: 8, bottom: 8), - alignLabelWithHint: true, - filled: true, - constraints: const BoxConstraints(), - suffixIconConstraints: const BoxConstraints(), - hintText: "Type your message here...", - hintStyle: AppTextStyles.bodyText.copyWith(color: const Color(0xffCCCCCC)), - // suffixIcon: Row( - // mainAxisSize: MainAxisSize.min, - // crossAxisAlignment: CrossAxisAlignment.end, - // mainAxisAlignment: MainAxisAlignment.end, - // children: [ - // - // 8.width, - // ], - // ) - ), - ).expanded, - IconButton( - onPressed: () {}, - style: const ButtonStyle( - tapTargetSize: MaterialTapTargetSize.shrinkWrap, // or .padded - ), - icon: "chat_attachment".toSvgAsset(width: 24, height: 24), - constraints: const BoxConstraints(), - ), - IconButton( - onPressed: () async { - await recorderController.checkPermission(); - if (recorderController.hasPermission) { - chatState = ChatState.voiceRecordingStarted; - recorderController.record(); - setState(() {}); - } else { - "Audio permission denied. Please enable from setting".showToast; - } - // if (!isPermissionGranted) { - // "Audio permission denied. Please enable from setting".showToast; - // return; - // } - }, - style: const ButtonStyle( - tapTargetSize: MaterialTapTargetSize.shrinkWrap, // or .padded - ), - icon: "chat_mic".toSvgAsset(width: 24, height: 24), - constraints: const BoxConstraints(), - ), - ] else if (chatState == ChatState.voiceRecordingStarted) ...[ - AudioWaveforms( - size: Size(MediaQuery.of(context).size.width, 56.0), - waveStyle: const WaveStyle(waveColor: AppColor.neutral50, extendWaveform: true, showMiddleLine: false), - padding: const EdgeInsets.only(left: 16), - recorderController: recorderController, // Customize how waveforms looks. + child: Row( + children: [ + Text( + "Engineer: Mahmoud Shrouf", + overflow: TextOverflow.ellipsis, + maxLines: 2, + style: AppTextStyles.bodyText2.copyWith(color: AppColor.white10), ).expanded, - IconButton( - onPressed: () async { - isAudioRecording = false; - await recorderController.pause(); - recordedFilePath = await recorderController.stop(); - chatState = ChatState.voiceRecordingCompleted; - setState(() {}); - }, - style: const ButtonStyle( - tapTargetSize: MaterialTapTargetSize.shrinkWrap, // or .padded + 4.width, + Text( + "View All Documents", + style: AppTextStyles.bodyText.copyWith( + color: AppColor.white10, + decoration: TextDecoration.underline, + decorationColor: AppColor.white10, ), - icon: Icon(Icons.stop_circle_rounded), - constraints: const BoxConstraints(), - ) - ] else if (chatState == ChatState.voiceRecordingCompleted) ...[ - if (playerController.playerState == PlayerState.playing) - IconButton( - onPressed: () async { - await playerController.pausePlayer(); - await playerController.stopPlayer(); - setState(() {}); - }, - style: const ButtonStyle( - tapTargetSize: MaterialTapTargetSize.shrinkWrap, // or .padded - ), - icon: const Icon(Icons.stop_circle_outlined, size: 20), - constraints: const BoxConstraints(), - ) - else - IconButton( - onPressed: () async { - await playerController.preparePlayer(path: recordedFilePath!); - await playerController.startPlayer(); - setState(() {}); - }, - style: const ButtonStyle( - tapTargetSize: MaterialTapTargetSize.shrinkWrap, // or .padded - ), - icon: const Icon(Icons.play_circle_fill_rounded, size: 20), - constraints: const BoxConstraints(), - ), - AudioFileWaveforms( - playerController: playerController, - waveformData: recorderController.waveData, - enableSeekGesture: false, - continuousWaveform: false, - waveformType: WaveformType.long, - playerWaveStyle: const PlayerWaveStyle( - fixedWaveColor: AppColor.neutral50, - liveWaveColor: AppColor.primary10, - showSeekLine: true, - ), - size: Size(MediaQuery.of(context).size.width, 56.0), - ).expanded, - IconButton( - onPressed: () async { - await playerController.stopPlayer(); - recorderController.reset(); - recordedFilePath = null; - chatState = ChatState.idle; - setState(() {}); - }, - style: const ButtonStyle( - tapTargetSize: MaterialTapTargetSize.shrinkWrap, // or .padded - ), - icon: "delete_icon".toSvgAsset(width: 24, height: 24), - constraints: const BoxConstraints(), ), ], + ), + ), + Container( + // width: double.infinity, + color: AppColor.neutral100, + child: !chatProvider.userChatHistoryLoading + ? ListView( + padding: const EdgeInsets.all(16), + children: [ + recipientMsgCard(true, "Please let me know what is the issue? Please let me know what is the issue?", loading: true), + recipientMsgCard(false, "testing", loading: true), + recipientMsgCard(false, "testing testing testing", loading: true), + // dateCard("Mon 27 Oct",), + senderMsgCard(true, "Please let me know what is the issue? Please let me know what is the issue?", loading: true), + senderMsgCard(false, "Please let me know what is the issue?", loading: true), + ], + ) + : chatProvider.chatResponseList.isEmpty + ? Text( + "Send a message to start conversation", + overflow: TextOverflow.ellipsis, + maxLines: 1, + style: AppTextStyles.heading6.copyWith(color: AppColor.neutral50.withOpacity(.5), fontWeight: FontWeight.w500), + ).center + : ListView.builder( + itemBuilder: (cxt, index) => recipientMsgCard(true, chatProvider.chatResponseList[index].content ?? ""), itemCount: chatProvider.chatResponseList.length)) + .expanded, + if (!widget.readOnly) ...[ + Divider(height: 1, thickness: 1, color: const Color(0xff767676).withOpacity(.11)), + SafeArea( + child: ConstrainedBox( + constraints: const BoxConstraints(minHeight: 56), + child: Row( + children: [ + if (chatState == ChatState.idle) ...[ + TextFormField( + controller: textEditingController, + cursorColor: AppColor.neutral50, + style: AppTextStyles.bodyText.copyWith(color: AppColor.neutral50), + minLines: 1, + maxLines: 3, + textInputAction: TextInputAction.none, + keyboardType: TextInputType.multiline, + decoration: InputDecoration( + enabledBorder: InputBorder.none, + focusedBorder: InputBorder.none, + border: InputBorder.none, + errorBorder: InputBorder.none, + contentPadding: const EdgeInsets.only(left: 16, top: 8, bottom: 8), + alignLabelWithHint: true, + filled: true, + constraints: const BoxConstraints(), + suffixIconConstraints: const BoxConstraints(), + hintText: "Type your message here...", + hintStyle: AppTextStyles.bodyText.copyWith(color: const Color(0xffCCCCCC)), + // suffixIcon: Row( + // mainAxisSize: MainAxisSize.min, + // crossAxisAlignment: CrossAxisAlignment.end, + // mainAxisAlignment: MainAxisAlignment.end, + // children: [ + // + // 8.width, + // ], + // ) + ), + ).expanded, + IconButton( + onPressed: () {}, + style: const ButtonStyle( + tapTargetSize: MaterialTapTargetSize.shrinkWrap, // or .padded + ), + icon: "chat_attachment".toSvgAsset(width: 24, height: 24), + constraints: const BoxConstraints(), + ), + IconButton( + onPressed: () async { + await recorderController.checkPermission(); + if (recorderController.hasPermission) { + chatState = ChatState.voiceRecordingStarted; + recorderController.record(); + setState(() {}); + } else { + "Audio permission denied. Please enable from setting".showToast; + } + // if (!isPermissionGranted) { + // "Audio permission denied. Please enable from setting".showToast; + // return; + // } + }, + style: const ButtonStyle( + tapTargetSize: MaterialTapTargetSize.shrinkWrap, // or .padded + ), + icon: "chat_mic".toSvgAsset(width: 24, height: 24), + constraints: const BoxConstraints(), + ), + ] else if (chatState == ChatState.voiceRecordingStarted) ...[ + AudioWaveforms( + size: Size(MediaQuery.of(context).size.width, 56.0), + waveStyle: const WaveStyle(waveColor: AppColor.neutral50, extendWaveform: true, showMiddleLine: false), + padding: const EdgeInsets.only(left: 16), + recorderController: recorderController, // Customize how waveforms looks. + ).expanded, + IconButton( + onPressed: () async { + isAudioRecording = false; + await recorderController.pause(); + recordedFilePath = await recorderController.stop(); + chatState = ChatState.voiceRecordingCompleted; + setState(() {}); + }, + style: const ButtonStyle( + tapTargetSize: MaterialTapTargetSize.shrinkWrap, // or .padded + ), + icon: Icon(Icons.stop_circle_rounded), + constraints: const BoxConstraints(), + ) + ] else if (chatState == ChatState.voiceRecordingCompleted) ...[ + if (playerController.playerState == PlayerState.playing) + IconButton( + onPressed: () async { + await playerController.pausePlayer(); + await playerController.stopPlayer(); + setState(() {}); + }, + style: const ButtonStyle( + tapTargetSize: MaterialTapTargetSize.shrinkWrap, // or .padded + ), + icon: const Icon(Icons.stop_circle_outlined, size: 20), + constraints: const BoxConstraints(), + ) + else + IconButton( + onPressed: () async { + await playerController.preparePlayer(path: recordedFilePath!); + await playerController.startPlayer(); + setState(() {}); + }, + style: const ButtonStyle( + tapTargetSize: MaterialTapTargetSize.shrinkWrap, // or .padded + ), + icon: const Icon(Icons.play_circle_fill_rounded, size: 20), + constraints: const BoxConstraints(), + ), + AudioFileWaveforms( + playerController: playerController, + waveformData: recorderController.waveData, + enableSeekGesture: false, + continuousWaveform: false, + waveformType: WaveformType.long, + playerWaveStyle: const PlayerWaveStyle( + fixedWaveColor: AppColor.neutral50, + liveWaveColor: AppColor.primary10, + showSeekLine: true, + ), + size: Size(MediaQuery.of(context).size.width, 56.0), + ).expanded, + IconButton( + onPressed: () async { + await playerController.stopPlayer(); + recorderController.reset(); + recordedFilePath = null; + chatState = ChatState.idle; + setState(() {}); + }, + style: const ButtonStyle( + tapTargetSize: MaterialTapTargetSize.shrinkWrap, // or .padded + ), + icon: "delete_icon".toSvgAsset(width: 24, height: 24), + constraints: const BoxConstraints(), + ), + ], - // if (recordedFilePath == null) ...[ - // isAudioRecording - // ? AudioWaveforms( - // size: Size(MediaQuery.of(context).size.width, 56.0), - // - // // enableGesture: true, - // - // waveStyle: const WaveStyle(waveColor: AppColor.neutral50, extendWaveform: true, showMiddleLine: false), - // padding: const EdgeInsets.only(left: 16), - // recorderController: recorderController, // Customize how waveforms looks. - // ).expanded - // : TextFormField( - // cursorColor: AppColor.neutral50, - // style: AppTextStyles.bodyText.copyWith(color: AppColor.neutral50), - // minLines: 1, - // maxLines: 3, - // textInputAction: TextInputAction.none, - // keyboardType: TextInputType.multiline, - // decoration: InputDecoration( - // enabledBorder: InputBorder.none, - // focusedBorder: InputBorder.none, - // border: InputBorder.none, - // errorBorder: InputBorder.none, - // contentPadding: const EdgeInsets.only(left: 16, top: 8, bottom: 8), - // alignLabelWithHint: true, - // filled: true, - // constraints: const BoxConstraints(), - // suffixIconConstraints: const BoxConstraints(), - // hintText: "Type your message here...", - // hintStyle: AppTextStyles.bodyText.copyWith(color: const Color(0xffCCCCCC)), - // // suffixIcon: Row( - // // mainAxisSize: MainAxisSize.min, - // // crossAxisAlignment: CrossAxisAlignment.end, - // // mainAxisAlignment: MainAxisAlignment.end, - // // children: [ - // // - // // 8.width, - // // ], - // // ) - // ), - // ).expanded, - // IconButton( - // onPressed: () {}, - // style: const ButtonStyle( - // tapTargetSize: MaterialTapTargetSize.shrinkWrap, // or .padded - // ), - // icon: "chat_attachment".toSvgAsset(width: 24, height: 24), - // constraints: const BoxConstraints(), - // ), - // ], - // if (recordedFilePath == null) - // ...[] - // else ...[ - // IconButton( - // onPressed: () async { - // await playerController.preparePlayer(path: recordedFilePath!); - // playerController.startPlayer(); - // }, - // style: const ButtonStyle( - // tapTargetSize: MaterialTapTargetSize.shrinkWrap, // or .padded - // ), - // icon: const Icon(Icons.play_circle_fill_rounded, size: 20), - // constraints: const BoxConstraints(), - // ), - // AudioFileWaveforms( - // playerController: playerController, - // size: Size(300, 50), - // ).expanded, - // IconButton( - // onPressed: () async { - // playerController.pausePlayer(); - // }, - // style: const ButtonStyle( - // tapTargetSize: MaterialTapTargetSize.shrinkWrap, // or .padded - // ), - // icon: const Icon(Icons.pause_circle_filled_outlined, size: 20), - // constraints: const BoxConstraints(), - // ), - // IconButton( - // onPressed: () {}, - // style: const ButtonStyle( - // tapTargetSize: MaterialTapTargetSize.shrinkWrap, // or .padded - // ), - // icon: "delete".toSvgAsset(width: 24, height: 24), - // constraints: const BoxConstraints(), - // ), - // ], - // if (isAudioRecording && recorderController.isRecording) - // IconButton( - // onPressed: () {}, - // style: const ButtonStyle( - // tapTargetSize: MaterialTapTargetSize.shrinkWrap, // or .padded - // ), - // icon: "chat_msg_send".toSvgAsset(width: 24, height: 24), - // constraints: const BoxConstraints(), - // ), - // if (isAudioRecording) - // IconButton( - // onPressed: () async { - // isAudioRecording = false; - // await recorderController.pause(); - // recordedFilePath = await recorderController.stop(); - // chatState = ChatState.voiceRecordingCompleted; - // setState(() {}); - // }, - // style: const ButtonStyle( - // tapTargetSize: MaterialTapTargetSize.shrinkWrap, // or .padded - // ), - // icon: Icon(Icons.stop_circle_rounded), - // constraints: const BoxConstraints(), - // ) - // else - // IconButton( - // onPressed: () async { - // await recorderController.checkPermission(); - // if (recorderController.hasPermission) { - // setState(() { - // isAudioRecording = true; - // }); - // recorderController.record(); - // } else { - // "Audio permission denied. Please enable from setting".showToast; - // } - // // if (!isPermissionGranted) { - // // "Audio permission denied. Please enable from setting".showToast; - // // return; - // // } - // }, - // style: const ButtonStyle( - // tapTargetSize: MaterialTapTargetSize.shrinkWrap, // or .padded - // ), - // icon: "chat_mic".toSvgAsset(width: 24, height: 24), - // constraints: const BoxConstraints(), - // ), + // if (recordedFilePath == null) ...[ + // isAudioRecording + // ? AudioWaveforms( + // size: Size(MediaQuery.of(context).size.width, 56.0), + // + // // enableGesture: true, + // + // waveStyle: const WaveStyle(waveColor: AppColor.neutral50, extendWaveform: true, showMiddleLine: false), + // padding: const EdgeInsets.only(left: 16), + // recorderController: recorderController, // Customize how waveforms looks. + // ).expanded + // : TextFormField( + // cursorColor: AppColor.neutral50, + // style: AppTextStyles.bodyText.copyWith(color: AppColor.neutral50), + // minLines: 1, + // maxLines: 3, + // textInputAction: TextInputAction.none, + // keyboardType: TextInputType.multiline, + // decoration: InputDecoration( + // enabledBorder: InputBorder.none, + // focusedBorder: InputBorder.none, + // border: InputBorder.none, + // errorBorder: InputBorder.none, + // contentPadding: const EdgeInsets.only(left: 16, top: 8, bottom: 8), + // alignLabelWithHint: true, + // filled: true, + // constraints: const BoxConstraints(), + // suffixIconConstraints: const BoxConstraints(), + // hintText: "Type your message here...", + // hintStyle: AppTextStyles.bodyText.copyWith(color: const Color(0xffCCCCCC)), + // // suffixIcon: Row( + // // mainAxisSize: MainAxisSize.min, + // // crossAxisAlignment: CrossAxisAlignment.end, + // // mainAxisAlignment: MainAxisAlignment.end, + // // children: [ + // // + // // 8.width, + // // ], + // // ) + // ), + // ).expanded, + // IconButton( + // onPressed: () {}, + // style: const ButtonStyle( + // tapTargetSize: MaterialTapTargetSize.shrinkWrap, // or .padded + // ), + // icon: "chat_attachment".toSvgAsset(width: 24, height: 24), + // constraints: const BoxConstraints(), + // ), + // ], + // if (recordedFilePath == null) + // ...[] + // else ...[ + // IconButton( + // onPressed: () async { + // await playerController.preparePlayer(path: recordedFilePath!); + // playerController.startPlayer(); + // }, + // style: const ButtonStyle( + // tapTargetSize: MaterialTapTargetSize.shrinkWrap, // or .padded + // ), + // icon: const Icon(Icons.play_circle_fill_rounded, size: 20), + // constraints: const BoxConstraints(), + // ), + // AudioFileWaveforms( + // playerController: playerController, + // size: Size(300, 50), + // ).expanded, + // IconButton( + // onPressed: () async { + // playerController.pausePlayer(); + // }, + // style: const ButtonStyle( + // tapTargetSize: MaterialTapTargetSize.shrinkWrap, // or .padded + // ), + // icon: const Icon(Icons.pause_circle_filled_outlined, size: 20), + // constraints: const BoxConstraints(), + // ), + // IconButton( + // onPressed: () {}, + // style: const ButtonStyle( + // tapTargetSize: MaterialTapTargetSize.shrinkWrap, // or .padded + // ), + // icon: "delete".toSvgAsset(width: 24, height: 24), + // constraints: const BoxConstraints(), + // ), + // ], + // if (isAudioRecording && recorderController.isRecording) + // IconButton( + // onPressed: () {}, + // style: const ButtonStyle( + // tapTargetSize: MaterialTapTargetSize.shrinkWrap, // or .padded + // ), + // icon: "chat_msg_send".toSvgAsset(width: 24, height: 24), + // constraints: const BoxConstraints(), + // ), + // if (isAudioRecording) + // IconButton( + // onPressed: () async { + // isAudioRecording = false; + // await recorderController.pause(); + // recordedFilePath = await recorderController.stop(); + // chatState = ChatState.voiceRecordingCompleted; + // setState(() {}); + // }, + // style: const ButtonStyle( + // tapTargetSize: MaterialTapTargetSize.shrinkWrap, // or .padded + // ), + // icon: Icon(Icons.stop_circle_rounded), + // constraints: const BoxConstraints(), + // ) + // else + // IconButton( + // onPressed: () async { + // await recorderController.checkPermission(); + // if (recorderController.hasPermission) { + // setState(() { + // isAudioRecording = true; + // }); + // recorderController.record(); + // } else { + // "Audio permission denied. Please enable from setting".showToast; + // } + // // if (!isPermissionGranted) { + // // "Audio permission denied. Please enable from setting".showToast; + // // return; + // // } + // }, + // style: const ButtonStyle( + // tapTargetSize: MaterialTapTargetSize.shrinkWrap, // or .padded + // ), + // icon: "chat_mic".toSvgAsset(width: 24, height: 24), + // constraints: const BoxConstraints(), + // ), - IconButton( - onPressed: () {}, - style: const ButtonStyle( - tapTargetSize: MaterialTapTargetSize.shrinkWrap, // or .padded + IconButton( + onPressed: () { + chatProvider.sendTextMessage(textEditingController.text).then((success) { + if (success) { + textEditingController.clear(); + } + }); + }, + style: const ButtonStyle( + tapTargetSize: MaterialTapTargetSize.shrinkWrap, // or .padded + ), + icon: chatProvider.messageIsSending + ? const SizedBox( + height: 24, + width: 24, + child: CircularProgressIndicator(color: AppColor.primary10, strokeWidth: 2), + ) + : "chat_msg_send".toSvgAsset(width: 24, height: 24), + constraints: const BoxConstraints(), + ), + 8.width, + ], ), - icon: "chat_msg_send".toSvgAsset(width: 24, height: 24), - constraints: const BoxConstraints(), ), - 8.width, - ], - ), - ), - ) - ], - ), - ); + ) + ] + ], + ); + })); } Widget dateCard(String date) { @@ -400,7 +470,7 @@ class _ChatPageState extends State { .center; } - Widget senderMsgCard(bool showHeader, String msg) { + Widget senderMsgCard(bool showHeader, String msg, {bool loading = false}) { Widget senderHeader = Row( mainAxisSize: MainAxisSize.min, children: [ @@ -409,13 +479,13 @@ class _ChatPageState extends State { overflow: TextOverflow.ellipsis, maxLines: 1, style: AppTextStyles.bodyText.copyWith(color: AppColor.neutral50, fontWeight: FontWeight.w600), - ), + ).toShimmer(context: context, isShow: loading), 8.width, Container( height: 26, width: 26, decoration: BoxDecoration(shape: BoxShape.circle, color: Colors.grey), - ), + ).toShimmer(context: context, isShow: loading), ], ); @@ -440,11 +510,11 @@ class _ChatPageState extends State { Text( msg, style: AppTextStyles.bodyText2.copyWith(color: AppColor.neutral120), - ), + ).toShimmer(context: context, isShow: loading), Text( "2:00 PM", style: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.neutral50.withOpacity(0.5)), - ), + ).toShimmer(context: context, isShow: loading), ], )), ], @@ -452,7 +522,7 @@ class _ChatPageState extends State { ); } - Widget recipientMsgCard(bool showHeader, String msg) { + Widget recipientMsgCard(bool showHeader, String msg, {bool loading = false}) { Widget recipientHeader = Row( mainAxisSize: MainAxisSize.min, children: [ @@ -460,14 +530,14 @@ class _ChatPageState extends State { height: 26, width: 26, decoration: BoxDecoration(shape: BoxShape.circle, color: Colors.grey), - ), + ).toShimmer(context: context, isShow: loading), 8.width, Text( "Mahmoud Shrouf", overflow: TextOverflow.ellipsis, maxLines: 1, style: AppTextStyles.bodyText.copyWith(color: AppColor.neutral50, fontWeight: FontWeight.w600), - ) + ).toShimmer(context: context, isShow: loading) ], ); @@ -492,7 +562,7 @@ class _ChatPageState extends State { Text( msg, style: AppTextStyles.bodyText2.copyWith(color: AppColor.white10), - ), + ).toShimmer(context: context, isShow: loading), Align( alignment: Alignment.centerRight, widthFactor: 1, @@ -502,7 +572,7 @@ class _ChatPageState extends State { ), ), ], - )), + ).toShimmer(context: context, isShow: loading)), ], ), ); diff --git a/lib/modules/cx_module/chat/chat_provider.dart b/lib/modules/cx_module/chat/chat_provider.dart index a22545ae..48438375 100644 --- a/lib/modules/cx_module/chat/chat_provider.dart +++ b/lib/modules/cx_module/chat/chat_provider.dart @@ -3,11 +3,13 @@ import 'dart:convert'; import 'dart:io'; import 'dart:typed_data'; import 'package:audio_waveforms/audio_waveforms.dart'; + // import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'package:http/http.dart'; +import 'package:intl/intl.dart'; import 'package:just_audio/just_audio.dart' as JustAudio; import 'package:just_audio/just_audio.dart'; @@ -40,224 +42,296 @@ import 'package:signalr_netcore/hub_connection.dart'; import 'package:signalr_netcore/signalr_client.dart'; import 'package:test_sa/controllers/api_routes/urls.dart'; import 'package:test_sa/extensions/string_extensions.dart'; +import 'package:test_sa/modules/cx_module/chat/model/chat_login_response_model.dart'; import 'package:uuid/uuid.dart'; import 'package:flutter/material.dart' as Material; +import 'chat_api_client.dart'; +import 'model/chat_participant_model.dart'; import 'model/get_search_user_chat_model.dart'; -import 'get_single_user_chat_list_model.dart'; +import 'model/get_single_user_chat_list_model.dart'; +import 'model/user_chat_history_model.dart'; +// import 'get_single_user_chat_list_model.dart'; late HubConnection chatHubConnection; class ChatProvider with ChangeNotifier, DiagnosticableTreeMixin { - ScrollController scrollController = ScrollController(); - - TextEditingController message = TextEditingController(); - TextEditingController search = TextEditingController(); - TextEditingController searchGroup = TextEditingController(); - - List userChatHistory = [], repliedMsg = []; - List? pChatHistory, searchedChats; - String chatCID = ''; - bool isLoading = true; - bool isChatScreenActive = false; - int receiverID = 0; - late File selectedFile; - String sFileType = ""; - - List favUsersList = []; - int paginationVal = 0; - int? cTypingUserId = 0; - bool isTextMsg = false, isReplyMsg = false, isAttachmentMsg = false, isVoiceMsg = false; - - // Audio Recoding Work - Timer? _timer; - int _recodeDuration = 0; - bool isRecoding = false; - bool isPause = false; - bool isPlaying = false; - String? path; - String? musicFile; - late Directory appDirectory; - late RecorderController recorderController; - late PlayerController playerController; - - // List getEmployeeSubordinatesList = []; - List teamMembersList = []; - - // groups.GetUserGroups userGroups = groups.GetUserGroups(); - Material.TextDirection textDirection = Material.TextDirection.ltr; - bool isRTL = false; - String msgText = ""; - - //Chat Home Page Counter - int chatUConvCounter = 0; - - // late List groupChatHistory, groupChatReplyData; - - /// Search Provider - List? chatUsersList = []; - int pageNo = 1; - - bool disbaleChatForThisUser = false; + // ScrollController scrollController = ScrollController(); + // + // TextEditingController message = TextEditingController(); + // TextEditingController search = TextEditingController(); + // TextEditingController searchGroup = TextEditingController(); + // + // List? pChatHistory, searchedChats; + // String chatCID = ''; + // bool isLoading = true; + // bool isChatScreenActive = false; + // int receiverID = 0; + // late File selectedFile; + // String sFileType = ""; + // + // List favUsersList = []; + // int paginationVal = 0; + // int? cTypingUserId = 0; + // bool isTextMsg = false, isReplyMsg = false, isAttachmentMsg = false, isVoiceMsg = false; + // + // // Audio Recoding Work + // Timer? _timer; + // int _recodeDuration = 0; + // bool isRecoding = false; + // bool isPause = false; + // bool isPlaying = false; + // String? path; + // String? musicFile; + // late Directory appDirectory; + // late RecorderController recorderController; + // late PlayerController playerController; + // + // // List getEmployeeSubordinatesList = []; + // List teamMembersList = []; + // + // // groups.GetUserGroups userGroups = groups.GetUserGroups(); + // Material.TextDirection textDirection = Material.TextDirection.ltr; + // bool isRTL = false; + // String msgText = ""; + // + // //Chat Home Page Counter + // int chatUConvCounter = 0; + // + // // late List groupChatHistory, groupChatReplyData; + // + // /// Search Provider + // List? chatUsersList = []; + // int pageNo = 1; + // + // bool disbaleChatForThisUser = false; + + bool chatLoginTokenLoading = false; + ChatLoginResponse? chatLoginResponse; + + bool chatParticipantLoading = false; + ChatParticipantModel? chatParticipantModel; + + bool userChatHistoryLoading = false; + UserChatHistoryModel? userChatHistory; + + bool messageIsSending = false; + + List chatResponseList = []; + + void reset() { + chatLoginTokenLoading = false; + chatParticipantLoading = false; + userChatHistoryLoading = false; + chatLoginResponse = null; + chatParticipantModel = null; + userChatHistory = null; + ChatApiClient().chatLoginResponse = null; + } + + Future getUserAutoLoginToken(int moduleId, int requestId, String title, String employeeNumber, String? assigneeEmployeeNumber) async { + reset(); + chatLoginTokenLoading = true; + notifyListeners(); + chatLoginResponse = await ChatApiClient().getChatLoginToken(moduleId, requestId, title, employeeNumber); + chatLoginTokenLoading = false; + chatParticipantLoading = true; + notifyListeners(); + // loadParticipants(moduleId, requestId); + loadChatHistory(moduleId, requestId, employeeNumber, assigneeEmployeeNumber); + } - // List? uGroups = [], searchGroups = []; + // Future loadParticipants(int moduleId, int requestId) async { + // // loadChatHistoryLoading = true; + // // notifyListeners(); + // chatParticipantModel = await ChatApiClient().loadParticipants(moduleId, requestId); + // chatParticipantLoading = false; + // notifyListeners(); + // } - Future getUserAutoLoginToken() async { - userLoginToken.UserAutoLoginModel userLoginResponse = await ChatApiClient().getUserLoginToken(); + Future loadChatHistory(int moduleId, int requestId, String myId, String? assigneeEmployeeNumber) async { + userChatHistoryLoading = true; + notifyListeners(); + chatParticipantModel = await ChatApiClient().loadParticipants(moduleId, requestId, assigneeEmployeeNumber); + userChatHistory = await ChatApiClient().loadChatHistory(moduleId, requestId, myId, "12"); + chatResponseList = userChatHistory?.response ?? []; - if (userLoginResponse.StatusCode == 500) { - disbaleChatForThisUser = true; - notifyListeners(); - } + userChatHistoryLoading = false; + notifyListeners(); + } - if (userLoginResponse.response != null) { - // AppState().setchatUserDetails = userLoginResponse; - } else { - // AppState().setchatUserDetails = userLoginResponse; - userLoginResponse.errorResponses!.first.fieldName.toString() + " Erorr".showToast; - disbaleChatForThisUser = true; - notifyListeners(); + Future sendTextMessage(String message) async { + messageIsSending = true; + notifyListeners(); + bool returnStatus = false; + ChatResponse? chatResponse = await ChatApiClient().sendTextMessage(message, chatParticipantModel!.id!); + if (chatResponse != null) { + returnStatus = true; + chatResponseList.add(chatResponse); } + messageIsSending = false; + notifyListeners(); + return returnStatus; } + // List? uGroups = [], searchGroups = []; + + // Future getUserAutoLoginToken() async { + // userLoginToken.UserAutoLoginModel userLoginResponse = await ChatApiClient().getUserLoginToken(); + // + // if (userLoginResponse.StatusCode == 500) { + // disbaleChatForThisUser = true; + // notifyListeners(); + // } + // + // if (userLoginResponse.response != null) { + // // AppState().setchatUserDetails = userLoginResponse; + // } else { + // // AppState().setchatUserDetails = userLoginResponse; + // userLoginResponse.errorResponses!.first.fieldName.toString() + " Erorr".showToast; + // disbaleChatForThisUser = true; + // notifyListeners(); + // } + // } + Future buildHubConnection() async { chatHubConnection = await getHubConnection(); await chatHubConnection.start(); if (kDebugMode) { // logger.i("Hub Conn: Startedddddddd"); } - chatHubConnection.on("OnDeliveredChatUserAsync", onMsgReceived); - chatHubConnection.on("OnGetChatConversationCount", onNewChatConversion); + // chatHubConnection.on("OnDeliveredChatUserAsync", onMsgReceived); + // chatHubConnection.on("OnGetChatConversationCount", onNewChatConversion); //group On message - chatHubConnection.on("OnDeliveredGroupChatHistoryAsync", onGroupMsgReceived); + // chatHubConnection.on("OnDeliveredGroupChatHistoryAsync", onGroupMsgReceived); } Future getHubConnection() async { HubConnection hub; HttpConnectionOptions httpOp = HttpConnectionOptions(skipNegotiation: false, logMessageContent: true); hub = HubConnectionBuilder() - .withUrl(URLs.chatHubUrl + "?UserId=${AppState().chatDetails!.response!.id}&source=Desktop&access_token=${AppState().chatDetails!.response!.token}", options: httpOp) + .withUrl(URLs.chatHubUrlChat + "?UserId=AppState().chatDetails!.response!.id&source=Desktop&access_token=AppState().chatDetails!.response!.token", options: httpOp) .withAutomaticReconnect(retryDelays: [2000, 5000, 10000, 20000]).build(); return hub; } void registerEvents() { - chatHubConnection.on("OnUpdateUserStatusAsync", changeStatus); + // chatHubConnection.on("OnUpdateUserStatusAsync", changeStatus); // chatHubConnection.on("OnDeliveredChatUserAsync", onMsgReceived); - chatHubConnection.on("OnSubmitChatAsync", OnSubmitChatAsync); - chatHubConnection.on("OnUserTypingAsync", onUserTyping); + // chatHubConnection.on("OnSubmitChatAsync", OnSubmitChatAsync); + // chatHubConnection.on("OnUserTypingAsync", onUserTyping); chatHubConnection.on("OnUserCountAsync", userCountAsync); // chatHubConnection.on("OnUpdateUserChatHistoryWindowsAsync", updateChatHistoryWindow); - chatHubConnection.on("OnGetUserChatHistoryNotDeliveredAsync", chatNotDelivered); - chatHubConnection.on("OnUpdateUserChatHistoryStatusAsync", updateUserChatStatus); + // chatHubConnection.on("OnGetUserChatHistoryNotDeliveredAsync", chatNotDelivered); + // chatHubConnection.on("OnUpdateUserChatHistoryStatusAsync", updateUserChatStatus); chatHubConnection.on("OnGetGroupUserStatusAsync", getGroupUserStatus); // // {"type":1,"target":"","arguments":[[{"id":217869,"userName":"Sultan.Khan","email":"Sultan.Khan@cloudsolutions.com.sa","phone":null,"title":"Sultan.Khan","userStatus":1,"image":null,"unreadMessageCount":0,"userAction":3,"isPin":false,"isFav":false,"isAdmin":false,"rKey":null,"totalCount":0,"isHuaweiDevice":false,"deviceToken":null},{"id":15153,"userName":"Tamer.Fanasheh","email":"Tamer.F@cloudsolutions.com.sa","phone":null,"title":"Tamer Fanasheh","userStatus":2,"image":null,"unreadMessageCount":0,"userAction":3,"isPin":false,"isFav":false,"isAdmin":true,"rKey":null,"totalCount":0,"isHuaweiDevice":false,"deviceToken":null}]]} if (kDebugMode) { - logger.i("All listeners registered"); - } - } - - Future getUserRecentChats() async { - ChatUserModel recentChat = await ChatApiClient().getRecentChats(); - ChatUserModel favUList = await ChatApiClient().getFavUsers(); - // userGroups = await ChatApiClient().getGroupsByUserId(); - if (favUList.response != null && recentChat.response != null) { - favUsersList = favUList.response!; - favUsersList.sort((ChatUser a, ChatUser b) => a.userName!.toLowerCase().compareTo(b.userName!.toLowerCase())); - for (dynamic user in recentChat.response!) { - for (dynamic favUser in favUList.response!) { - if (user.id == favUser.id) { - user.isFav = favUser.isFav; - } - } - } - } - pChatHistory = recentChat.response ?? []; - uGroups = userGroups.groupresponse ?? []; - pChatHistory!.sort((ChatUser a, ChatUser b) => a.userName!.toLowerCase().compareTo(b.userName!.toLowerCase())); - searchedChats = pChatHistory; - isLoading = false; - await invokeUserChatHistoryNotDeliveredAsync(userId: int.parse(AppState().chatDetails!.response!.id.toString())); - sort(); - notifyListeners(); - if (searchedChats!.isNotEmpty || favUsersList.isNotEmpty) { - getUserImages(); - } - } + // logger.i("All listeners registered"); + } + } + + // Future getUserRecentChats() async { + // ChatUserModel recentChat = await ChatApiClient().getRecentChats(); + // ChatUserModel favUList = await ChatApiClient().getFavUsers(); + // // userGroups = await ChatApiClient().getGroupsByUserId(); + // if (favUList.response != null && recentChat.response != null) { + // favUsersList = favUList.response!; + // favUsersList.sort((ChatUser a, ChatUser b) => a.userName!.toLowerCase().compareTo(b.userName!.toLowerCase())); + // for (dynamic user in recentChat.response!) { + // for (dynamic favUser in favUList.response!) { + // if (user.id == favUser.id) { + // user.isFav = favUser.isFav; + // } + // } + // } + // } + // pChatHistory = recentChat.response ?? []; + // uGroups = userGroups.groupresponse ?? []; + // pChatHistory!.sort((ChatUser a, ChatUser b) => a.userName!.toLowerCase().compareTo(b.userName!.toLowerCase())); + // searchedChats = pChatHistory; + // isLoading = false; + // await invokeUserChatHistoryNotDeliveredAsync(userId: int.parse(AppState().chatDetails!.response!.id.toString())); + // sort(); + // notifyListeners(); + // if (searchedChats!.isNotEmpty || favUsersList.isNotEmpty) { + // getUserImages(); + // } + // } Future invokeUserChatHistoryNotDeliveredAsync({required int userId}) async { await chatHubConnection.invoke("GetUserChatHistoryNotDeliveredAsync", args: [userId]); return ""; } - void getSingleUserChatHistory({required int senderUID, required int receiverUID, required bool loadMore, bool isNewChat = false}) async { - isLoading = true; - if (isNewChat) userChatHistory = []; - if (!loadMore) paginationVal = 0; - isChatScreenActive = true; - receiverID = receiverUID; - Response response = await ChatApiClient().getSingleUserChatHistory(senderUID: senderUID, receiverUID: receiverUID, loadMore: loadMore, paginationVal: paginationVal); - if (response.statusCode == 204) { - if (isNewChat) { - userChatHistory = []; - } else if (loadMore) {} - } else { - if (loadMore) { - List temp = getSingleUserChatModel(response.body).reversed.toList(); - userChatHistory.addAll(temp); - } else { - userChatHistory = getSingleUserChatModel(response.body).reversed.toList(); - } - } - isLoading = false; - notifyListeners(); - - if (isChatScreenActive && receiverUID == receiverID) { - markRead(userChatHistory, receiverUID); - } - - generateConvId(); - } - - void generateConvId() async { - Uuid uuid = const Uuid(); - chatCID = uuid.v4(); - } - - void markRead(List data, int receiverID) { - for (SingleUserChatModel element in data!) { - if (AppState().chatDetails!.response!.id! == element.targetUserId) { - if (element.isSeen != null) { - if (!element.isSeen!) { - element.isSeen = true; - dynamic data = [ - { - "userChatHistoryId": element.userChatHistoryId, - "TargetUserId": element.currentUserId == receiverID ? element.currentUserId : element.targetUserId, - "isDelivered": true, - "isSeen": true, - } - ]; - updateUserChatHistoryStatusAsync(data); - notifyListeners(); - } - } - for (ChatUser element in searchedChats!) { - if (element.id == receiverID) { - element.unreadMessageCount = 0; - chatUConvCounter = 0; - } - } - } - } - notifyListeners(); - } + // void getSingleUserChatHistory({required int senderUID, required int receiverUID, required bool loadMore, bool isNewChat = false}) async { + // isLoading = true; + // if (isNewChat) userChatHistory = []; + // if (!loadMore) paginationVal = 0; + // isChatScreenActive = true; + // receiverID = receiverUID; + // Response response = await ChatApiClient().getSingleUserChatHistory(senderUID: senderUID, receiverUID: receiverUID, loadMore: loadMore, paginationVal: paginationVal); + // if (response.statusCode == 204) { + // if (isNewChat) { + // userChatHistory = []; + // } else if (loadMore) {} + // } else { + // if (loadMore) { + // List temp = getSingleUserChatModel(response.body).reversed.toList(); + // userChatHistory.addAll(temp); + // } else { + // userChatHistory = getSingleUserChatModel(response.body).reversed.toList(); + // } + // } + // isLoading = false; + // notifyListeners(); + // + // if (isChatScreenActive && receiverUID == receiverID) { + // markRead(userChatHistory, receiverUID); + // } + // + // generateConvId(); + // } + // + // void generateConvId() async { + // Uuid uuid = const Uuid(); + // chatCID = uuid.v4(); + // } + + // void markRead(List data, int receiverID) { + // for (SingleUserChatModel element in data!) { + // if (AppState().chatDetails!.response!.id! == element.targetUserId) { + // if (element.isSeen != null) { + // if (!element.isSeen!) { + // element.isSeen = true; + // dynamic data = [ + // { + // "userChatHistoryId": element.userChatHistoryId, + // "TargetUserId": element.currentUserId == receiverID ? element.currentUserId : element.targetUserId, + // "isDelivered": true, + // "isSeen": true, + // } + // ]; + // updateUserChatHistoryStatusAsync(data); + // notifyListeners(); + // } + // } + // for (ChatUser element in searchedChats!) { + // if (element.id == receiverID) { + // element.unreadMessageCount = 0; + // chatUConvCounter = 0; + // } + // } + // } + // } + // notifyListeners(); + // } void updateUserChatHistoryStatusAsync(List data) { try { @@ -277,36 +351,36 @@ class ChatProvider with ChangeNotifier, DiagnosticableTreeMixin { List getSingleUserChatModel(String str) => List.from(json.decode(str).map((x) => SingleUserChatModel.fromJson(x))); - List getGroupChatHistoryAsync(String str) => - List.from(json.decode(str).map((x) => groupchathistory.GetGroupChatHistoryAsync.fromJson(x))); - - Future uploadAttachments(String userId, File file, String fileSource) async { - dynamic result; - try { - Object? response = await ChatApiClient().uploadMedia(userId, file, fileSource); - if (response != null) { - result = response; - } else { - result = []; - } - } catch (e) { - throw e; - } - return result; - } - - void updateUserChatStatus(List? args) { - dynamic items = args!.toList(); - for (var cItem in items[0]) { - for (SingleUserChatModel chat in userChatHistory) { - if (cItem["contantNo"].toString() == chat.contantNo.toString()) { - chat.isSeen = cItem["isSeen"]; - chat.isDelivered = cItem["isDelivered"]; - } - } - } - notifyListeners(); - } + // List getGroupChatHistoryAsync(String str) => + // List.from(json.decode(str).map((x) => groupchathistory.GetGroupChatHistoryAsync.fromJson(x))); + // + // Future uploadAttachments(String userId, File file, String fileSource) async { + // dynamic result; + // try { + // Object? response = await ChatApiClient().uploadMedia(userId, file, fileSource); + // if (response != null) { + // result = response; + // } else { + // result = []; + // } + // } catch (e) { + // throw e; + // } + // return result; + // } + + // void updateUserChatStatus(List? args) { + // dynamic items = args!.toList(); + // for (var cItem in items[0]) { + // for (SingleUserChatModel chat in userChatHistory) { + // if (cItem["contantNo"].toString() == chat.contantNo.toString()) { + // chat.isSeen = cItem["isSeen"]; + // chat.isDelivered = cItem["isDelivered"]; + // } + // } + // } + // notifyListeners(); + // } void getGroupUserStatus(List? args) { //note: need to implement this function... @@ -336,273 +410,273 @@ class ChatProvider with ChangeNotifier, DiagnosticableTreeMixin { // notifyListeners(); } - void updateChatHistoryWindow(List? args) { - dynamic items = args!.toList(); - if (kDebugMode) { - logger.i("---------------------------------Update Chat History Windows Async -------------------------------------"); - } - logger.d(items); - // for (var user in searchedChats!) { - // if (user.id == items.first["id"]) { - // user.userStatus = items.first["userStatus"]; - // } - // } - // notifyListeners(); - } - - void chatNotDelivered(List? args) { - dynamic items = args!.toList(); - for (dynamic item in items[0]) { - for (ChatUser element in searchedChats!) { - if (element.id == item["currentUserId"]) { - int? val = element.unreadMessageCount ?? 0; - element.unreadMessageCount = val! + 1; - } - } - } - notifyListeners(); - } - - void changeStatus(List? args) { - dynamic items = args!.toList(); - for (ChatUser user in searchedChats!) { - if (user.id == items.first["id"]) { - user.userStatus = items.first["userStatus"]; - } - } - if (teamMembersList.isNotEmpty) { - for (ChatUser user in teamMembersList!) { - if (user.id == items.first["id"]) { - user.userStatus = items.first["userStatus"]; - } - } - } - - notifyListeners(); - } - - void filter(String value) async { - List? tmp = []; - if (value.isEmpty || value == "") { - tmp = pChatHistory; - } else { - for (ChatUser element in pChatHistory!) { - if (element.userName!.toLowerCase().contains(value.toLowerCase())) { - tmp.add(element); - } - } - } - searchedChats = tmp; - notifyListeners(); - } - - Future onMsgReceived(List? parameters) async { - List data = [], temp = []; - for (dynamic msg in parameters!) { - data = getSingleUserChatModel(jsonEncode(msg)); - temp = getSingleUserChatModel(jsonEncode(msg)); - data.first.targetUserId = temp.first.currentUserId; - data.first.targetUserName = temp.first.currentUserName; - data.first.targetUserEmail = temp.first.currentUserEmail; - data.first.currentUserId = temp.first.targetUserId; - data.first.currentUserName = temp.first.targetUserName; - data.first.currentUserEmail = temp.first.targetUserEmail; - - if (data.first.fileTypeId == 12 || data.first.fileTypeId == 4 || data.first.fileTypeId == 3) { - data.first.image = await ChatApiClient().downloadURL(fileName: data.first.contant!, fileTypeDescription: data.first.fileTypeResponse!.fileTypeDescription ?? "image/jpg", fileSource: 1); - } - if (data.first.userChatReplyResponse != null) { - if (data.first.fileTypeResponse != null) { - if (data.first.userChatReplyResponse!.fileTypeId == 12 || data.first.userChatReplyResponse!.fileTypeId == 4 || data.first.userChatReplyResponse!.fileTypeId == 3) { - data.first.userChatReplyResponse!.image = await ChatApiClient() - .downloadURL(fileName: data.first.userChatReplyResponse!.contant!, fileTypeDescription: data.first.fileTypeResponse!.fileTypeDescription ?? "image/jpg", fileSource: 1); - data.first.userChatReplyResponse!.isImageLoaded = true; - } - } - } - } - - if (searchedChats != null) { - dynamic contain = searchedChats!.where((ChatUser element) => element.id == data.first.currentUserId); - if (contain.isEmpty) { - List emails = []; - emails.add(await EmailImageEncryption().encrypt(val: data.first.currentUserEmail!)); - List chatImages = await ChatApiClient().getUsersImages(encryptedEmails: emails); - searchedChats!.add( - ChatUser( - id: data.first.currentUserId, - userName: data.first.currentUserName, - email: data.first.currentUserEmail, - unreadMessageCount: 0, - isImageLoading: false, - image: chatImages!.first.profilePicture ?? "", - isImageLoaded: true, - userStatus: 1, - isTyping: false, - userLocalDownlaodedImage: await downloadImageLocal(chatImages.first.profilePicture, data.first.currentUserId.toString()), - ), - ); - } - } - setMsgTune(); - if (isChatScreenActive && data.first.currentUserId == receiverID) { - userChatHistory.insert(0, data.first); - } else { - if (searchedChats != null) { - for (ChatUser user in searchedChats!) { - if (user.id == data.first.currentUserId) { - int tempCount = user.unreadMessageCount ?? 0; - user.unreadMessageCount = tempCount + 1; - } - } - sort(); - } - } - - List list = [ - { - "userChatHistoryId": data.first.userChatHistoryId, - "TargetUserId": temp.first.targetUserId, - "isDelivered": true, - "isSeen": isChatScreenActive && data.first.currentUserId == receiverID ? true : false - } - ]; - updateUserChatHistoryOnMsg(list); - invokeChatCounter(userId: AppState().chatDetails!.response!.id!); - notifyListeners(); - } - - Future onGroupMsgReceived(List? parameters) async { - List data = [], temp = []; - - for (dynamic msg in parameters!) { - // groupChatHistory.add(groupchathistory.GetGroupChatHistoryAsync.fromJson(msg)); - data.add(groupchathistory.GetGroupChatHistoryAsync.fromJson(msg)); - temp = data; - // data.first.currentUserId = temp.first.currentUserId; - // data.first.currentUserName = temp.first.currentUserName; - // - // data.first.currentUserId = temp.first.currentUserId; - // data.first.currentUserName = temp.first.currentUserName; - - if (data.first.fileTypeId == 12 || data.first.fileTypeId == 4 || data.first.fileTypeId == 3) { - data.first.image = await ChatApiClient().downloadURL(fileName: data.first.contant!, fileTypeDescription: data.first.fileTypeResponse!.fileTypeDescription ?? "image/jpg", fileSource: 2); - } - if (data.first.groupChatReplyResponse != null) { - if (data.first.fileTypeResponse != null) { - if (data.first.groupChatReplyResponse!.fileTypeId == 12 || data.first.groupChatReplyResponse!.fileTypeId == 4 || data.first.groupChatReplyResponse!.fileTypeId == 3) { - data.first.groupChatReplyResponse!.image = await ChatApiClient() - .downloadURL(fileName: data.first.groupChatReplyResponse!.contant!, fileTypeDescription: data.first.fileTypeResponse!.fileTypeDescription ?? "image/jpg", fileSource: 2); - data.first.groupChatReplyResponse!.isImageLoaded = true; - } - } - } - } - - // if (searchedChats != null) { - // dynamic contain = searchedChats! - // .where((ChatUser element) => element.id == data.first.currentUserId); - // if (contain.isEmpty) { - // List emails = []; - // emails.add(await EmailImageEncryption() - // .encrypt(val: data.first.currentUserEmail!)); - // List chatImages = - // await ChatApiClient().getUsersImages(encryptedEmails: emails); - // searchedChats!.add( - // ChatUser( - // id: data.first.currentUserId, - // userName: data.first.currentUserName, - // email: data.first.currentUserEmail, - // unreadMessageCount: 0, - // isImageLoading: false, - // image: chatImages!.first.profilePicture ?? "", - // isImageLoaded: true, - // userStatus: 1, - // isTyping: false, - // userLocalDownlaodedImage: await downloadImageLocal( - // chatImages.first.profilePicture, - // data.first.currentUserId.toString()), - // ), - // ); - // } - // } - groupChatHistory.insert(0, data.first); - setMsgTune(); - // if (isChatScreenActive && data.first.currentUserId == receiverID) { - - // } else { - // if (searchedChats != null) { - // for (ChatUser user in searchedChats!) { - // if (user.id == data.first.currentUserId) { - // int tempCount = user.unreadMessageCount ?? 0; - // user.unreadMessageCount = tempCount + 1; - // } - // } - sort(); - //} - //} - // - // List list = [ - // { - // "userChatHistoryId": data.first.groupId, - // "TargetUserId": temp.first.currentUserId, - // "isDelivered": true, - // "isSeen": isChatScreenActive && data.first.currentUserId == receiverID - // ? true - // : false - // } - // ]; - // updateUserChatHistoryOnMsg(list); - // invokeChatCounter(userId: AppState().chatDetails!.response!.id!); - notifyListeners(); - } - - void OnSubmitChatAsync(List? parameters) { - print(isChatScreenActive); - print(receiverID); - print(isChatScreenActive); - logger.i(parameters); - List data = [], temp = []; - for (dynamic msg in parameters!) { - data = getSingleUserChatModel(jsonEncode(msg)); - temp = getSingleUserChatModel(jsonEncode(msg)); - data.first.targetUserId = temp.first.currentUserId; - data.first.targetUserName = temp.first.currentUserName; - data.first.targetUserEmail = temp.first.currentUserEmail; - data.first.currentUserId = temp.first.targetUserId; - data.first.currentUserName = temp.first.targetUserName; - data.first.currentUserEmail = temp.first.targetUserEmail; - } - if (isChatScreenActive && data.first.currentUserId == receiverID) { - int index = userChatHistory.indexWhere((SingleUserChatModel element) => element.userChatHistoryId == 0); - logger.d(index); - userChatHistory[index] = data.first; - } - - notifyListeners(); - } - - void sort() { - searchedChats!.sort( - (ChatUser a, ChatUser b) => b.unreadMessageCount!.compareTo(a.unreadMessageCount!), - ); - } - - void onUserTyping(List? parameters) { - for (ChatUser user in searchedChats!) { - if (user.id == parameters![1] && parameters[0] == true) { - user.isTyping = parameters[0] as bool?; - Future.delayed( - const Duration(seconds: 2), - () { - user.isTyping = false; - notifyListeners(); - }, - ); - } - } - notifyListeners(); - } + // void updateChatHistoryWindow(List? args) { + // dynamic items = args!.toList(); + // if (kDebugMode) { + // logger.i("---------------------------------Update Chat History Windows Async -------------------------------------"); + // } + // logger.d(items); + // // for (var user in searchedChats!) { + // // if (user.id == items.first["id"]) { + // // user.userStatus = items.first["userStatus"]; + // // } + // // } + // // notifyListeners(); + // } + + // void chatNotDelivered(List? args) { + // dynamic items = args!.toList(); + // for (dynamic item in items[0]) { + // for (ChatUser element in searchedChats!) { + // if (element.id == item["currentUserId"]) { + // int? val = element.unreadMessageCount ?? 0; + // element.unreadMessageCount = val! + 1; + // } + // } + // } + // notifyListeners(); + // } + // + // void changeStatus(List? args) { + // dynamic items = args!.toList(); + // for (ChatUser user in searchedChats!) { + // if (user.id == items.first["id"]) { + // user.userStatus = items.first["userStatus"]; + // } + // } + // if (teamMembersList.isNotEmpty) { + // for (ChatUser user in teamMembersList!) { + // if (user.id == items.first["id"]) { + // user.userStatus = items.first["userStatus"]; + // } + // } + // } + // + // notifyListeners(); + // } + // + // void filter(String value) async { + // List? tmp = []; + // if (value.isEmpty || value == "") { + // tmp = pChatHistory; + // } else { + // for (ChatUser element in pChatHistory!) { + // if (element.userName!.toLowerCase().contains(value.toLowerCase())) { + // tmp.add(element); + // } + // } + // } + // searchedChats = tmp; + // notifyListeners(); + // } + + // Future onMsgReceived(List? parameters) async { + // List data = [], temp = []; + // for (dynamic msg in parameters!) { + // data = getSingleUserChatModel(jsonEncode(msg)); + // temp = getSingleUserChatModel(jsonEncode(msg)); + // data.first.targetUserId = temp.first.currentUserId; + // data.first.targetUserName = temp.first.currentUserName; + // data.first.targetUserEmail = temp.first.currentUserEmail; + // data.first.currentUserId = temp.first.targetUserId; + // data.first.currentUserName = temp.first.targetUserName; + // data.first.currentUserEmail = temp.first.targetUserEmail; + // + // if (data.first.fileTypeId == 12 || data.first.fileTypeId == 4 || data.first.fileTypeId == 3) { + // data.first.image = await ChatApiClient().downloadURL(fileName: data.first.contant!, fileTypeDescription: data.first.fileTypeResponse!.fileTypeDescription ?? "image/jpg", fileSource: 1); + // } + // if (data.first.userChatReplyResponse != null) { + // if (data.first.fileTypeResponse != null) { + // if (data.first.userChatReplyResponse!.fileTypeId == 12 || data.first.userChatReplyResponse!.fileTypeId == 4 || data.first.userChatReplyResponse!.fileTypeId == 3) { + // data.first.userChatReplyResponse!.image = await ChatApiClient() + // .downloadURL(fileName: data.first.userChatReplyResponse!.contant!, fileTypeDescription: data.first.fileTypeResponse!.fileTypeDescription ?? "image/jpg", fileSource: 1); + // data.first.userChatReplyResponse!.isImageLoaded = true; + // } + // } + // } + // } + // + // if (searchedChats != null) { + // dynamic contain = searchedChats!.where((ChatUser element) => element.id == data.first.currentUserId); + // if (contain.isEmpty) { + // List emails = []; + // emails.add(await EmailImageEncryption().encrypt(val: data.first.currentUserEmail!)); + // List chatImages = await ChatApiClient().getUsersImages(encryptedEmails: emails); + // searchedChats!.add( + // ChatUser( + // id: data.first.currentUserId, + // userName: data.first.currentUserName, + // email: data.first.currentUserEmail, + // unreadMessageCount: 0, + // isImageLoading: false, + // image: chatImages!.first.profilePicture ?? "", + // isImageLoaded: true, + // userStatus: 1, + // isTyping: false, + // userLocalDownlaodedImage: await downloadImageLocal(chatImages.first.profilePicture, data.first.currentUserId.toString()), + // ), + // ); + // } + // } + // setMsgTune(); + // if (isChatScreenActive && data.first.currentUserId == receiverID) { + // userChatHistory.insert(0, data.first); + // } else { + // if (searchedChats != null) { + // for (ChatUser user in searchedChats!) { + // if (user.id == data.first.currentUserId) { + // int tempCount = user.unreadMessageCount ?? 0; + // user.unreadMessageCount = tempCount + 1; + // } + // } + // sort(); + // } + // } + // + // List list = [ + // { + // "userChatHistoryId": data.first.userChatHistoryId, + // "TargetUserId": temp.first.targetUserId, + // "isDelivered": true, + // "isSeen": isChatScreenActive && data.first.currentUserId == receiverID ? true : false + // } + // ]; + // updateUserChatHistoryOnMsg(list); + // invokeChatCounter(userId: AppState().chatDetails!.response!.id!); + // notifyListeners(); + // } + + // Future onGroupMsgReceived(List? parameters) async { + // List data = [], temp = []; + // + // for (dynamic msg in parameters!) { + // // groupChatHistory.add(groupchathistory.GetGroupChatHistoryAsync.fromJson(msg)); + // data.add(groupchathistory.GetGroupChatHistoryAsync.fromJson(msg)); + // temp = data; + // // data.first.currentUserId = temp.first.currentUserId; + // // data.first.currentUserName = temp.first.currentUserName; + // // + // // data.first.currentUserId = temp.first.currentUserId; + // // data.first.currentUserName = temp.first.currentUserName; + // + // if (data.first.fileTypeId == 12 || data.first.fileTypeId == 4 || data.first.fileTypeId == 3) { + // data.first.image = await ChatApiClient().downloadURL(fileName: data.first.contant!, fileTypeDescription: data.first.fileTypeResponse!.fileTypeDescription ?? "image/jpg", fileSource: 2); + // } + // if (data.first.groupChatReplyResponse != null) { + // if (data.first.fileTypeResponse != null) { + // if (data.first.groupChatReplyResponse!.fileTypeId == 12 || data.first.groupChatReplyResponse!.fileTypeId == 4 || data.first.groupChatReplyResponse!.fileTypeId == 3) { + // data.first.groupChatReplyResponse!.image = await ChatApiClient() + // .downloadURL(fileName: data.first.groupChatReplyResponse!.contant!, fileTypeDescription: data.first.fileTypeResponse!.fileTypeDescription ?? "image/jpg", fileSource: 2); + // data.first.groupChatReplyResponse!.isImageLoaded = true; + // } + // } + // } + // } + // + // // if (searchedChats != null) { + // // dynamic contain = searchedChats! + // // .where((ChatUser element) => element.id == data.first.currentUserId); + // // if (contain.isEmpty) { + // // List emails = []; + // // emails.add(await EmailImageEncryption() + // // .encrypt(val: data.first.currentUserEmail!)); + // // List chatImages = + // // await ChatApiClient().getUsersImages(encryptedEmails: emails); + // // searchedChats!.add( + // // ChatUser( + // // id: data.first.currentUserId, + // // userName: data.first.currentUserName, + // // email: data.first.currentUserEmail, + // // unreadMessageCount: 0, + // // isImageLoading: false, + // // image: chatImages!.first.profilePicture ?? "", + // // isImageLoaded: true, + // // userStatus: 1, + // // isTyping: false, + // // userLocalDownlaodedImage: await downloadImageLocal( + // // chatImages.first.profilePicture, + // // data.first.currentUserId.toString()), + // // ), + // // ); + // // } + // // } + // groupChatHistory.insert(0, data.first); + // setMsgTune(); + // // if (isChatScreenActive && data.first.currentUserId == receiverID) { + // + // // } else { + // // if (searchedChats != null) { + // // for (ChatUser user in searchedChats!) { + // // if (user.id == data.first.currentUserId) { + // // int tempCount = user.unreadMessageCount ?? 0; + // // user.unreadMessageCount = tempCount + 1; + // // } + // // } + // sort(); + // //} + // //} + // // + // // List list = [ + // // { + // // "userChatHistoryId": data.first.groupId, + // // "TargetUserId": temp.first.currentUserId, + // // "isDelivered": true, + // // "isSeen": isChatScreenActive && data.first.currentUserId == receiverID + // // ? true + // // : false + // // } + // // ]; + // // updateUserChatHistoryOnMsg(list); + // // invokeChatCounter(userId: AppState().chatDetails!.response!.id!); + // notifyListeners(); + // } + + // void OnSubmitChatAsync(List? parameters) { + // print(isChatScreenActive); + // print(receiverID); + // print(isChatScreenActive); + // logger.i(parameters); + // List data = [], temp = []; + // for (dynamic msg in parameters!) { + // data = getSingleUserChatModel(jsonEncode(msg)); + // temp = getSingleUserChatModel(jsonEncode(msg)); + // data.first.targetUserId = temp.first.currentUserId; + // data.first.targetUserName = temp.first.currentUserName; + // data.first.targetUserEmail = temp.first.currentUserEmail; + // data.first.currentUserId = temp.first.targetUserId; + // data.first.currentUserName = temp.first.targetUserName; + // data.first.currentUserEmail = temp.first.targetUserEmail; + // } + // if (isChatScreenActive && data.first.currentUserId == receiverID) { + // int index = userChatHistory.indexWhere((SingleUserChatModel element) => element.userChatHistoryId == 0); + // logger.d(index); + // userChatHistory[index] = data.first; + // } + // + // notifyListeners(); + // } + + // void sort() { + // searchedChats!.sort( + // (ChatUser a, ChatUser b) => b.unreadMessageCount!.compareTo(a.unreadMessageCount!), + // ); + // } + + // void onUserTyping(List? parameters) { + // for (ChatUser user in searchedChats!) { + // if (user.id == parameters![1] && parameters[0] == true) { + // user.isTyping = parameters[0] as bool?; + // Future.delayed( + // const Duration(seconds: 2), + // () { + // user.isTyping = false; + // notifyListeners(); + // }, + // ); + // } + // } + // notifyListeners(); + // } int getFileType(String value) { switch (value) { @@ -696,577 +770,577 @@ class ChatProvider with ChangeNotifier, DiagnosticableTreeMixin { } } - Future sendChatToServer( - {required int chatEventId, - required fileTypeId, - required int targetUserId, - required String targetUserName, - required chatReplyId, - required bool isAttachment, - required bool isReply, - Uint8List? image, - required bool isImageLoaded, - String? userEmail, - int? userStatus, - File? voiceFile, - required bool isVoiceAttached}) async { - Uuid uuid = const Uuid(); - String contentNo = uuid.v4(); - String msg; - if (isVoiceAttached) { - msg = voiceFile!.path.split("/").last; - } else { - msg = message.text; - logger.w(msg); - } - SingleUserChatModel data = SingleUserChatModel( - userChatHistoryId: 0, - chatEventId: chatEventId, - chatSource: 1, - contant: msg, - contantNo: contentNo, - conversationId: chatCID, - createdDate: DateTime.now(), - currentUserId: AppState().chatDetails!.response!.id, - currentUserName: AppState().chatDetails!.response!.userName, - targetUserId: targetUserId, - targetUserName: targetUserName, - isReplied: false, - fileTypeId: fileTypeId, - userChatReplyResponse: isReply ? UserChatReplyResponse.fromJson(repliedMsg.first.toJson()) : null, - fileTypeResponse: isAttachment - ? FileTypeResponse( - fileTypeId: fileTypeId, - fileTypeName: isVoiceMsg ? getFileExtension(voiceFile!.path).toString() : getFileExtension(selectedFile.path).toString(), - fileKind: "file", - fileName: isVoiceMsg ? msg : selectedFile.path.split("/").last, - fileTypeDescription: isVoiceMsg ? getFileTypeDescription(getFileExtension(voiceFile!.path).toString()) : getFileTypeDescription(getFileExtension(selectedFile.path).toString()), - ) - : null, - image: image, - isImageLoaded: isImageLoaded, - voice: isVoiceMsg ? voiceFile! : null, - voiceController: isVoiceMsg ? AudioPlayer() : null); - if (kDebugMode) { - logger.i("model data: " + jsonEncode(data)); - } - userChatHistory.insert(0, data); - isTextMsg = false; - isReplyMsg = false; - isAttachmentMsg = false; - isVoiceMsg = false; - sFileType = ""; - message.clear(); - notifyListeners(); - - String chatData = - '{"contant":"$msg","contantNo":"$contentNo","chatEventId":$chatEventId,"fileTypeId": $fileTypeId,"currentUserId":${AppState().chatDetails!.response!.id},"chatSource":1,"userChatHistoryLineRequestList":[{"isSeen":false,"isDelivered":false,"targetUserId":$targetUserId,"targetUserStatus":1}],"chatReplyId":$chatReplyId,"conversationId":"$chatCID"}'; - - await chatHubConnection.invoke("AddChatUserAsync", args: [json.decode(chatData)]); - } + // Future sendChatToServer( + // {required int chatEventId, + // required fileTypeId, + // required int targetUserId, + // required String targetUserName, + // required chatReplyId, + // required bool isAttachment, + // required bool isReply, + // Uint8List? image, + // required bool isImageLoaded, + // String? userEmail, + // int? userStatus, + // File? voiceFile, + // required bool isVoiceAttached}) async { + // Uuid uuid = const Uuid(); + // String contentNo = uuid.v4(); + // String msg; + // if (isVoiceAttached) { + // msg = voiceFile!.path.split("/").last; + // } else { + // msg = message.text; + // logger.w(msg); + // } + // SingleUserChatModel data = SingleUserChatModel( + // userChatHistoryId: 0, + // chatEventId: chatEventId, + // chatSource: 1, + // contant: msg, + // contantNo: contentNo, + // conversationId: chatCID, + // createdDate: DateTime.now(), + // currentUserId: AppState().chatDetails!.response!.id, + // currentUserName: AppState().chatDetails!.response!.userName, + // targetUserId: targetUserId, + // targetUserName: targetUserName, + // isReplied: false, + // fileTypeId: fileTypeId, + // userChatReplyResponse: isReply ? UserChatReplyResponse.fromJson(repliedMsg.first.toJson()) : null, + // fileTypeResponse: isAttachment + // ? FileTypeResponse( + // fileTypeId: fileTypeId, + // fileTypeName: isVoiceMsg ? getFileExtension(voiceFile!.path).toString() : getFileExtension(selectedFile.path).toString(), + // fileKind: "file", + // fileName: isVoiceMsg ? msg : selectedFile.path.split("/").last, + // fileTypeDescription: isVoiceMsg ? getFileTypeDescription(getFileExtension(voiceFile!.path).toString()) : getFileTypeDescription(getFileExtension(selectedFile.path).toString()), + // ) + // : null, + // image: image, + // isImageLoaded: isImageLoaded, + // voice: isVoiceMsg ? voiceFile! : null, + // voiceController: isVoiceMsg ? AudioPlayer() : null); + // if (kDebugMode) { + // logger.i("model data: " + jsonEncode(data)); + // } + // userChatHistory.insert(0, data); + // isTextMsg = false; + // isReplyMsg = false; + // isAttachmentMsg = false; + // isVoiceMsg = false; + // sFileType = ""; + // message.clear(); + // notifyListeners(); + // + // String chatData = + // '{"contant":"$msg","contantNo":"$contentNo","chatEventId":$chatEventId,"fileTypeId": $fileTypeId,"currentUserId":${AppState().chatDetails!.response!.id},"chatSource":1,"userChatHistoryLineRequestList":[{"isSeen":false,"isDelivered":false,"targetUserId":$targetUserId,"targetUserStatus":1}],"chatReplyId":$chatReplyId,"conversationId":"$chatCID"}'; + // + // await chatHubConnection.invoke("AddChatUserAsync", args: [json.decode(chatData)]); + // } //groupChatMessage - Future sendGroupChatToServer( - {required int chatEventId, - required fileTypeId, - required int targetGroupId, - required String targetUserName, - required chatReplyId, - required bool isAttachment, - required bool isReply, - Uint8List? image, - required bool isImageLoaded, - String? userEmail, - int? userStatus, - File? voiceFile, - required bool isVoiceAttached, - required List userList}) async { - Uuid uuid = const Uuid(); - String contentNo = uuid.v4(); - String msg; - if (isVoiceAttached) { - msg = voiceFile!.path.split("/").last; - } else { - msg = message.text; - logger.w(msg); - } - groupchathistory.GetGroupChatHistoryAsync data = groupchathistory.GetGroupChatHistoryAsync( - //userChatHistoryId: 0, - chatEventId: chatEventId, - chatSource: 1, - contant: msg, - contantNo: contentNo, - conversationId: chatCID, - createdDate: DateTime.now().toString(), - currentUserId: AppState().chatDetails!.response!.id, - currentUserName: AppState().chatDetails!.response!.userName, - groupId: targetGroupId, - groupName: targetUserName, - isReplied: false, - fileTypeId: fileTypeId, - fileTypeResponse: isAttachment - ? groupchathistory.FileTypeResponse( - fileTypeId: fileTypeId, - fileTypeName: isVoiceMsg ? getFileExtension(voiceFile!.path).toString() : getFileExtension(selectedFile.path).toString(), - fileKind: "file", - fileName: isVoiceMsg ? msg : selectedFile.path.split("/").last, - fileTypeDescription: isVoiceMsg ? getFileTypeDescription(getFileExtension(voiceFile!.path).toString()) : getFileTypeDescription(getFileExtension(selectedFile.path).toString())) - : null, - image: image, - isImageLoaded: isImageLoaded, - voice: isVoiceMsg ? voiceFile! : null, - voiceController: isVoiceMsg ? AudioPlayer() : null); - if (kDebugMode) { - logger.i("model data: " + jsonEncode(data)); - } - groupChatHistory.insert(0, data); - isTextMsg = false; - isReplyMsg = false; - isAttachmentMsg = false; - isVoiceMsg = false; - sFileType = ""; - message.clear(); - notifyListeners(); - - List targetUsers = []; - - for (GroupUserList element in userList) { - targetUsers.add(TargetUsers(isDelivered: false, isSeen: false, targetUserId: element.id, userAction: element.userAction, userStatus: element.userStatus)); - } - - String chatData = - '{"contant":"$msg","contantNo":"$contentNo","chatEventId":$chatEventId,"fileTypeId":$fileTypeId,"currentUserId":${AppState().chatDetails!.response!.id},"chatSource":1,"groupId":$targetGroupId,"groupChatHistoryLineRequestList":${json.encode(targetUsers)},"chatReplyId": $chatReplyId,"conversationId":"${uuid.v4()}"}'; - - await chatHubConnection.invoke("AddGroupChatHistoryAsync", args: [json.decode(chatData)]); - } - - void sendGroupChatMessage( - BuildContext context, { - required int targetUserId, - required int userStatus, - required String userEmail, - required String targetUserName, - required List userList, - }) async { - if (isTextMsg && !isAttachmentMsg && !isVoiceMsg && !isReplyMsg) { - logger.d("// Normal Text Message"); - if (message.text.isEmpty) { - return; - } - sendGroupChatToServer( - chatEventId: 1, - fileTypeId: null, - targetGroupId: targetUserId, - targetUserName: targetUserName, - isAttachment: false, - chatReplyId: null, - isReply: false, - isImageLoaded: false, - image: null, - isVoiceAttached: false, - userEmail: userEmail, - userStatus: userStatus, - userList: userList); - } else if (isTextMsg && !isAttachmentMsg && !isVoiceMsg && isReplyMsg) { - logger.d("// Text Message as Reply"); - if (message.text.isEmpty) { - return; - } - sendGroupChatToServer( - chatEventId: 1, - fileTypeId: null, - targetGroupId: targetUserId, - targetUserName: targetUserName, - chatReplyId: groupChatReplyData.first.groupChatHistoryId, - isAttachment: false, - isReply: true, - isImageLoaded: groupChatReplyData.first.isImageLoaded!, - image: groupChatReplyData.first.image, - isVoiceAttached: false, - voiceFile: null, - userEmail: userEmail, - userStatus: userStatus, - userList: userList); - } - // Attachment - else if (!isTextMsg && isAttachmentMsg && !isVoiceMsg && !isReplyMsg) { - logger.d("// Normal Image Message"); - Utils.showLoading(context); - dynamic value = await uploadAttachments(AppState().chatDetails!.response!.id.toString(), selectedFile, "2"); - String? ext = getFileExtension(selectedFile.path); - Utils.hideLoading(context); - sendGroupChatToServer( - chatEventId: 2, - fileTypeId: getFileType(ext.toString()), - targetGroupId: targetUserId, - targetUserName: targetUserName, - isAttachment: true, - chatReplyId: null, - isReply: false, - isImageLoaded: true, - image: selectedFile.readAsBytesSync(), - isVoiceAttached: false, - userEmail: userEmail, - userStatus: userStatus, - userList: userList); - } else if (!isTextMsg && isAttachmentMsg && !isVoiceMsg && isReplyMsg) { - logger.d("// Image as Reply Msg"); - Utils.showLoading(context); - dynamic value = await uploadAttachments(AppState().chatDetails!.response!.id.toString(), selectedFile, "2"); - String? ext = getFileExtension(selectedFile.path); - Utils.hideLoading(context); - sendGroupChatToServer( - chatEventId: 2, - fileTypeId: getFileType(ext.toString()), - targetGroupId: targetUserId, - targetUserName: targetUserName, - isAttachment: true, - chatReplyId: repliedMsg.first.userChatHistoryId, - isReply: true, - isImageLoaded: true, - image: selectedFile.readAsBytesSync(), - isVoiceAttached: false, - userEmail: userEmail, - userStatus: userStatus, - userList: userList); - } - //Voice - - else if (!isTextMsg && !isAttachmentMsg && isVoiceMsg && !isReplyMsg) { - logger.d("// Normal Voice Message"); - - if (!isPause) { - path = await recorderController.stop(false); - } - if (kDebugMode) { - logger.i("path:" + path!); - } - File voiceFile = File(path!); - voiceFile.readAsBytesSync(); - _timer?.cancel(); - isPause = false; - isPlaying = false; - isRecoding = false; - Utils.showLoading(context); - dynamic value = await uploadAttachments(AppState().chatDetails!.response!.id.toString(), voiceFile, "2"); - String? ext = getFileExtension(voiceFile.path); - Utils.hideLoading(context); - sendGroupChatToServer( - chatEventId: 2, - fileTypeId: getFileType(ext.toString()), - //, - targetGroupId: targetUserId, - targetUserName: targetUserName, - chatReplyId: null, - isAttachment: true, - isReply: isReplyMsg, - isImageLoaded: false, - voiceFile: voiceFile, - isVoiceAttached: true, - userEmail: userEmail, - userStatus: userStatus, - userList: userList); - notifyListeners(); - } else if (!isTextMsg && !isAttachmentMsg && isVoiceMsg && isReplyMsg) { - logger.d("// Voice as Reply Msg"); - - if (!isPause) { - path = await recorderController.stop(false); - } - if (kDebugMode) { - logger.i("path:" + path!); - } - File voiceFile = File(path!); - voiceFile.readAsBytesSync(); - _timer?.cancel(); - isPause = false; - isPlaying = false; - isRecoding = false; - - Utils.showLoading(context); - dynamic value = await uploadAttachments(AppState().chatDetails!.response!.id.toString(), voiceFile, "2"); - String? ext = getFileExtension(voiceFile.path); - Utils.hideLoading(context); - sendGroupChatToServer( - chatEventId: 2, - fileTypeId: getFileType(ext.toString()), - targetGroupId: targetUserId, - targetUserName: targetUserName, - chatReplyId: null, - isAttachment: true, - isReply: isReplyMsg, - isImageLoaded: false, - voiceFile: voiceFile, - isVoiceAttached: true, - userEmail: userEmail, - userStatus: userStatus, - userList: userList); - notifyListeners(); - } - if (searchedChats != null) { - dynamic contain = searchedChats!.where((ChatUser element) => element.id == targetUserId); - if (contain.isEmpty) { - List emails = []; - emails.add(await EmailImageEncryption().encrypt(val: userEmail)); - List chatImages = await ChatApiClient().getUsersImages(encryptedEmails: emails); - searchedChats!.add( - ChatUser( - id: targetUserId, - userName: targetUserName, - unreadMessageCount: 0, - email: userEmail, - isImageLoading: false, - image: chatImages.first.profilePicture ?? "", - isImageLoaded: true, - isTyping: false, - isFav: false, - userStatus: userStatus, - // userLocalDownlaodedImage: await downloadImageLocal(chatImages.first.profilePicture, targetUserId.toString()), - ), - ); - notifyListeners(); - } - } - } - - void sendChatMessage( - BuildContext context, { - required int targetUserId, - required int userStatus, - required String userEmail, - required String targetUserName, - }) async { - if (kDebugMode) { - print("====================== Values ============================"); - print("Is Text " + isTextMsg.toString()); - print("isReply " + isReplyMsg.toString()); - print("isAttachment " + isAttachmentMsg.toString()); - print("isVoice " + isVoiceMsg.toString()); - } - //Text - if (isTextMsg && !isAttachmentMsg && !isVoiceMsg && !isReplyMsg) { - logger.d("// Normal Text Message"); - if (message.text.isEmpty) { - return; - } - sendChatToServer( - chatEventId: 1, - fileTypeId: null, - targetUserId: targetUserId, - targetUserName: targetUserName, - isAttachment: false, - chatReplyId: null, - isReply: false, - isImageLoaded: false, - image: null, - isVoiceAttached: false, - userEmail: userEmail, - userStatus: userStatus); - } else if (isTextMsg && !isAttachmentMsg && !isVoiceMsg && isReplyMsg) { - logger.d("// Text Message as Reply"); - if (message.text.isEmpty) { - return; - } - sendChatToServer( - chatEventId: 1, - fileTypeId: null, - targetUserId: targetUserId, - targetUserName: targetUserName, - chatReplyId: repliedMsg.first.userChatHistoryId, - isAttachment: false, - isReply: true, - isImageLoaded: repliedMsg.first.isImageLoaded!, - image: repliedMsg.first.image, - isVoiceAttached: false, - voiceFile: null, - userEmail: userEmail, - userStatus: userStatus); - } - // Attachment - else if (!isTextMsg && isAttachmentMsg && !isVoiceMsg && !isReplyMsg) { - logger.d("// Normal Image Message"); - Utils.showLoading(context); - dynamic value = await uploadAttachments(AppState().chatDetails!.response!.id.toString(), selectedFile, "1"); - String? ext = getFileExtension(selectedFile.path); - Utils.hideLoading(context); - sendChatToServer( - chatEventId: 2, - fileTypeId: getFileType(ext.toString()), - targetUserId: targetUserId, - targetUserName: targetUserName, - isAttachment: true, - chatReplyId: null, - isReply: false, - isImageLoaded: true, - image: selectedFile.readAsBytesSync(), - isVoiceAttached: false, - userEmail: userEmail, - userStatus: userStatus); - } else if (!isTextMsg && isAttachmentMsg && !isVoiceMsg && isReplyMsg) { - logger.d("// Image as Reply Msg"); - Utils.showLoading(context); - dynamic value = await uploadAttachments(AppState().chatDetails!.response!.id.toString(), selectedFile, "1"); - String? ext = getFileExtension(selectedFile.path); - Utils.hideLoading(context); - sendChatToServer( - chatEventId: 2, - fileTypeId: getFileType(ext.toString()), - targetUserId: targetUserId, - targetUserName: targetUserName, - isAttachment: true, - chatReplyId: repliedMsg.first.userChatHistoryId, - isReply: true, - isImageLoaded: true, - image: selectedFile.readAsBytesSync(), - isVoiceAttached: false, - userEmail: userEmail, - userStatus: userStatus); - } - //Voice - - else if (!isTextMsg && !isAttachmentMsg && isVoiceMsg && !isReplyMsg) { - logger.d("// Normal Voice Message"); - - if (!isPause) { - path = await recorderController.stop(false); - } - if (kDebugMode) { - logger.i("path:" + path!); - } - File voiceFile = File(path!); - voiceFile.readAsBytesSync(); - _timer?.cancel(); - isPause = false; - isPlaying = false; - isRecoding = false; - Utils.showLoading(context); - dynamic value = await uploadAttachments(AppState().chatDetails!.response!.id.toString(), voiceFile, "1"); - String? ext = getFileExtension(voiceFile.path); - Utils.hideLoading(context); - sendChatToServer( - chatEventId: 2, - fileTypeId: getFileType(ext.toString()), - targetUserId: targetUserId, - targetUserName: targetUserName, - chatReplyId: null, - isAttachment: true, - isReply: isReplyMsg, - isImageLoaded: false, - voiceFile: voiceFile, - isVoiceAttached: true, - userEmail: userEmail, - userStatus: userStatus); - notifyListeners(); - } else if (!isTextMsg && !isAttachmentMsg && isVoiceMsg && isReplyMsg) { - logger.d("// Voice as Reply Msg"); - - if (!isPause) { - path = await recorderController.stop(false); - } - if (kDebugMode) { - logger.i("path:" + path!); - } - File voiceFile = File(path!); - voiceFile.readAsBytesSync(); - _timer?.cancel(); - isPause = false; - isPlaying = false; - isRecoding = false; - - Utils.showLoading(context); - dynamic value = await uploadAttachments(AppState().chatDetails!.response!.id.toString(), voiceFile, "1"); - String? ext = getFileExtension(voiceFile.path); - Utils.hideLoading(context); - sendChatToServer( - chatEventId: 2, - fileTypeId: getFileType(ext.toString()), - targetUserId: targetUserId, - targetUserName: targetUserName, - chatReplyId: null, - isAttachment: true, - isReply: isReplyMsg, - isImageLoaded: false, - voiceFile: voiceFile, - isVoiceAttached: true, - userEmail: userEmail, - userStatus: userStatus); - notifyListeners(); - } - if (searchedChats != null) { - dynamic contain = searchedChats!.where((ChatUser element) => element.id == targetUserId); - if (contain.isEmpty) { - List emails = []; - emails.add(await EmailImageEncryption().encrypt(val: userEmail)); - List chatImages = await ChatApiClient().getUsersImages(encryptedEmails: emails); - searchedChats!.add( - ChatUser( - id: targetUserId, - userName: targetUserName, - unreadMessageCount: 0, - email: userEmail, - isImageLoading: false, - image: chatImages.first.profilePicture ?? "", - isImageLoaded: true, - isTyping: false, - isFav: false, - userStatus: userStatus, - userLocalDownlaodedImage: await downloadImageLocal(chatImages.first.profilePicture, targetUserId.toString()), - ), - ); - notifyListeners(); - } - } - // else { - // List emails = []; - // emails.add(await EmailImageEncryption().encrypt(val: userEmail)); - // List chatImages = await ChatApiClient().getUsersImages(encryptedEmails: emails); - // searchedChats!.add( - // ChatUser( - // id: targetUserId, - // userName: targetUserName, - // unreadMessageCount: 0, - // email: userEmail, - // isImageLoading: false, - // image: chatImages.first.profilePicture ?? "", - // isImageLoaded: true, - // isTyping: false, - // isFav: false, - // userStatus: userStatus, - // userLocalDownlaodedImage: await downloadImageLocal(chatImages.first.profilePicture, targetUserId.toString()), - // ), - // ); - // notifyListeners(); - // } - } - - void selectImageToUpload(BuildContext context) { - ImageOptions.showImageOptionsNew(context, true, (String image, File file) async { - if (checkFileSize(file.path)) { - selectedFile = file; - isAttachmentMsg = true; - isTextMsg = false; - sFileType = getFileExtension(file.path)!; - message.text = file.path.split("/").last; - Navigator.of(context).pop(); - } else { - Utils.showToast("Max 1 mb size is allowed to upload"); - } - notifyListeners(); - }); - } - - void removeAttachment() { - isAttachmentMsg = false; - sFileType = ""; - message.text = ''; - notifyListeners(); - } + // Future sendGroupChatToServer( + // {required int chatEventId, + // required fileTypeId, + // required int targetGroupId, + // required String targetUserName, + // required chatReplyId, + // required bool isAttachment, + // required bool isReply, + // Uint8List? image, + // required bool isImageLoaded, + // String? userEmail, + // int? userStatus, + // File? voiceFile, + // required bool isVoiceAttached, + // required List userList}) async { + // Uuid uuid = const Uuid(); + // String contentNo = uuid.v4(); + // String msg; + // if (isVoiceAttached) { + // msg = voiceFile!.path.split("/").last; + // } else { + // msg = message.text; + // logger.w(msg); + // } + // groupchathistory.GetGroupChatHistoryAsync data = groupchathistory.GetGroupChatHistoryAsync( + // //userChatHistoryId: 0, + // chatEventId: chatEventId, + // chatSource: 1, + // contant: msg, + // contantNo: contentNo, + // conversationId: chatCID, + // createdDate: DateTime.now().toString(), + // currentUserId: AppState().chatDetails!.response!.id, + // currentUserName: AppState().chatDetails!.response!.userName, + // groupId: targetGroupId, + // groupName: targetUserName, + // isReplied: false, + // fileTypeId: fileTypeId, + // fileTypeResponse: isAttachment + // ? groupchathistory.FileTypeResponse( + // fileTypeId: fileTypeId, + // fileTypeName: isVoiceMsg ? getFileExtension(voiceFile!.path).toString() : getFileExtension(selectedFile.path).toString(), + // fileKind: "file", + // fileName: isVoiceMsg ? msg : selectedFile.path.split("/").last, + // fileTypeDescription: isVoiceMsg ? getFileTypeDescription(getFileExtension(voiceFile!.path).toString()) : getFileTypeDescription(getFileExtension(selectedFile.path).toString())) + // : null, + // image: image, + // isImageLoaded: isImageLoaded, + // voice: isVoiceMsg ? voiceFile! : null, + // voiceController: isVoiceMsg ? AudioPlayer() : null); + // if (kDebugMode) { + // logger.i("model data: " + jsonEncode(data)); + // } + // groupChatHistory.insert(0, data); + // isTextMsg = false; + // isReplyMsg = false; + // isAttachmentMsg = false; + // isVoiceMsg = false; + // sFileType = ""; + // message.clear(); + // notifyListeners(); + // + // List targetUsers = []; + // + // for (GroupUserList element in userList) { + // targetUsers.add(TargetUsers(isDelivered: false, isSeen: false, targetUserId: element.id, userAction: element.userAction, userStatus: element.userStatus)); + // } + // + // String chatData = + // '{"contant":"$msg","contantNo":"$contentNo","chatEventId":$chatEventId,"fileTypeId":$fileTypeId,"currentUserId":${AppState().chatDetails!.response!.id},"chatSource":1,"groupId":$targetGroupId,"groupChatHistoryLineRequestList":${json.encode(targetUsers)},"chatReplyId": $chatReplyId,"conversationId":"${uuid.v4()}"}'; + // + // await chatHubConnection.invoke("AddGroupChatHistoryAsync", args: [json.decode(chatData)]); + // } + + // void sendGroupChatMessage( + // BuildContext context, { + // required int targetUserId, + // required int userStatus, + // required String userEmail, + // required String targetUserName, + // required List userList, + // }) async { + // if (isTextMsg && !isAttachmentMsg && !isVoiceMsg && !isReplyMsg) { + // logger.d("// Normal Text Message"); + // if (message.text.isEmpty) { + // return; + // } + // sendGroupChatToServer( + // chatEventId: 1, + // fileTypeId: null, + // targetGroupId: targetUserId, + // targetUserName: targetUserName, + // isAttachment: false, + // chatReplyId: null, + // isReply: false, + // isImageLoaded: false, + // image: null, + // isVoiceAttached: false, + // userEmail: userEmail, + // userStatus: userStatus, + // userList: userList); + // } else if (isTextMsg && !isAttachmentMsg && !isVoiceMsg && isReplyMsg) { + // logger.d("// Text Message as Reply"); + // if (message.text.isEmpty) { + // return; + // } + // sendGroupChatToServer( + // chatEventId: 1, + // fileTypeId: null, + // targetGroupId: targetUserId, + // targetUserName: targetUserName, + // chatReplyId: groupChatReplyData.first.groupChatHistoryId, + // isAttachment: false, + // isReply: true, + // isImageLoaded: groupChatReplyData.first.isImageLoaded!, + // image: groupChatReplyData.first.image, + // isVoiceAttached: false, + // voiceFile: null, + // userEmail: userEmail, + // userStatus: userStatus, + // userList: userList); + // } + // // Attachment + // else if (!isTextMsg && isAttachmentMsg && !isVoiceMsg && !isReplyMsg) { + // logger.d("// Normal Image Message"); + // Utils.showLoading(context); + // dynamic value = await uploadAttachments(AppState().chatDetails!.response!.id.toString(), selectedFile, "2"); + // String? ext = getFileExtension(selectedFile.path); + // Utils.hideLoading(context); + // sendGroupChatToServer( + // chatEventId: 2, + // fileTypeId: getFileType(ext.toString()), + // targetGroupId: targetUserId, + // targetUserName: targetUserName, + // isAttachment: true, + // chatReplyId: null, + // isReply: false, + // isImageLoaded: true, + // image: selectedFile.readAsBytesSync(), + // isVoiceAttached: false, + // userEmail: userEmail, + // userStatus: userStatus, + // userList: userList); + // } else if (!isTextMsg && isAttachmentMsg && !isVoiceMsg && isReplyMsg) { + // logger.d("// Image as Reply Msg"); + // Utils.showLoading(context); + // dynamic value = await uploadAttachments(AppState().chatDetails!.response!.id.toString(), selectedFile, "2"); + // String? ext = getFileExtension(selectedFile.path); + // Utils.hideLoading(context); + // sendGroupChatToServer( + // chatEventId: 2, + // fileTypeId: getFileType(ext.toString()), + // targetGroupId: targetUserId, + // targetUserName: targetUserName, + // isAttachment: true, + // chatReplyId: repliedMsg.first.userChatHistoryId, + // isReply: true, + // isImageLoaded: true, + // image: selectedFile.readAsBytesSync(), + // isVoiceAttached: false, + // userEmail: userEmail, + // userStatus: userStatus, + // userList: userList); + // } + // //Voice + // + // else if (!isTextMsg && !isAttachmentMsg && isVoiceMsg && !isReplyMsg) { + // logger.d("// Normal Voice Message"); + // + // if (!isPause) { + // path = await recorderController.stop(false); + // } + // if (kDebugMode) { + // logger.i("path:" + path!); + // } + // File voiceFile = File(path!); + // voiceFile.readAsBytesSync(); + // _timer?.cancel(); + // isPause = false; + // isPlaying = false; + // isRecoding = false; + // Utils.showLoading(context); + // dynamic value = await uploadAttachments(AppState().chatDetails!.response!.id.toString(), voiceFile, "2"); + // String? ext = getFileExtension(voiceFile.path); + // Utils.hideLoading(context); + // sendGroupChatToServer( + // chatEventId: 2, + // fileTypeId: getFileType(ext.toString()), + // //, + // targetGroupId: targetUserId, + // targetUserName: targetUserName, + // chatReplyId: null, + // isAttachment: true, + // isReply: isReplyMsg, + // isImageLoaded: false, + // voiceFile: voiceFile, + // isVoiceAttached: true, + // userEmail: userEmail, + // userStatus: userStatus, + // userList: userList); + // notifyListeners(); + // } else if (!isTextMsg && !isAttachmentMsg && isVoiceMsg && isReplyMsg) { + // logger.d("// Voice as Reply Msg"); + // + // if (!isPause) { + // path = await recorderController.stop(false); + // } + // if (kDebugMode) { + // logger.i("path:" + path!); + // } + // File voiceFile = File(path!); + // voiceFile.readAsBytesSync(); + // _timer?.cancel(); + // isPause = false; + // isPlaying = false; + // isRecoding = false; + // + // Utils.showLoading(context); + // dynamic value = await uploadAttachments(AppState().chatDetails!.response!.id.toString(), voiceFile, "2"); + // String? ext = getFileExtension(voiceFile.path); + // Utils.hideLoading(context); + // sendGroupChatToServer( + // chatEventId: 2, + // fileTypeId: getFileType(ext.toString()), + // targetGroupId: targetUserId, + // targetUserName: targetUserName, + // chatReplyId: null, + // isAttachment: true, + // isReply: isReplyMsg, + // isImageLoaded: false, + // voiceFile: voiceFile, + // isVoiceAttached: true, + // userEmail: userEmail, + // userStatus: userStatus, + // userList: userList); + // notifyListeners(); + // } + // if (searchedChats != null) { + // dynamic contain = searchedChats!.where((ChatUser element) => element.id == targetUserId); + // if (contain.isEmpty) { + // List emails = []; + // emails.add(await EmailImageEncryption().encrypt(val: userEmail)); + // List chatImages = await ChatApiClient().getUsersImages(encryptedEmails: emails); + // searchedChats!.add( + // ChatUser( + // id: targetUserId, + // userName: targetUserName, + // unreadMessageCount: 0, + // email: userEmail, + // isImageLoading: false, + // image: chatImages.first.profilePicture ?? "", + // isImageLoaded: true, + // isTyping: false, + // isFav: false, + // userStatus: userStatus, + // // userLocalDownlaodedImage: await downloadImageLocal(chatImages.first.profilePicture, targetUserId.toString()), + // ), + // ); + // notifyListeners(); + // } + // } + // } + + // void sendChatMessage( + // BuildContext context, { + // required int targetUserId, + // required int userStatus, + // required String userEmail, + // required String targetUserName, + // }) async { + // if (kDebugMode) { + // print("====================== Values ============================"); + // print("Is Text " + isTextMsg.toString()); + // print("isReply " + isReplyMsg.toString()); + // print("isAttachment " + isAttachmentMsg.toString()); + // print("isVoice " + isVoiceMsg.toString()); + // } + // //Text + // if (isTextMsg && !isAttachmentMsg && !isVoiceMsg && !isReplyMsg) { + // // logger.d("// Normal Text Message"); + // if (message.text.isEmpty) { + // return; + // } + // sendChatToServer( + // chatEventId: 1, + // fileTypeId: null, + // targetUserId: targetUserId, + // targetUserName: targetUserName, + // isAttachment: false, + // chatReplyId: null, + // isReply: false, + // isImageLoaded: false, + // image: null, + // isVoiceAttached: false, + // userEmail: userEmail, + // userStatus: userStatus); + // } else if (isTextMsg && !isAttachmentMsg && !isVoiceMsg && isReplyMsg) { + // logger.d("// Text Message as Reply"); + // if (message.text.isEmpty) { + // return; + // } + // sendChatToServer( + // chatEventId: 1, + // fileTypeId: null, + // targetUserId: targetUserId, + // targetUserName: targetUserName, + // chatReplyId: repliedMsg.first.userChatHistoryId, + // isAttachment: false, + // isReply: true, + // isImageLoaded: repliedMsg.first.isImageLoaded!, + // image: repliedMsg.first.image, + // isVoiceAttached: false, + // voiceFile: null, + // userEmail: userEmail, + // userStatus: userStatus); + // } + // // Attachment + // else if (!isTextMsg && isAttachmentMsg && !isVoiceMsg && !isReplyMsg) { + // logger.d("// Normal Image Message"); + // Utils.showLoading(context); + // dynamic value = await uploadAttachments(AppState().chatDetails!.response!.id.toString(), selectedFile, "1"); + // String? ext = getFileExtension(selectedFile.path); + // Utils.hideLoading(context); + // sendChatToServer( + // chatEventId: 2, + // fileTypeId: getFileType(ext.toString()), + // targetUserId: targetUserId, + // targetUserName: targetUserName, + // isAttachment: true, + // chatReplyId: null, + // isReply: false, + // isImageLoaded: true, + // image: selectedFile.readAsBytesSync(), + // isVoiceAttached: false, + // userEmail: userEmail, + // userStatus: userStatus); + // } else if (!isTextMsg && isAttachmentMsg && !isVoiceMsg && isReplyMsg) { + // logger.d("// Image as Reply Msg"); + // Utils.showLoading(context); + // dynamic value = await uploadAttachments(AppState().chatDetails!.response!.id.toString(), selectedFile, "1"); + // String? ext = getFileExtension(selectedFile.path); + // Utils.hideLoading(context); + // sendChatToServer( + // chatEventId: 2, + // fileTypeId: getFileType(ext.toString()), + // targetUserId: targetUserId, + // targetUserName: targetUserName, + // isAttachment: true, + // chatReplyId: repliedMsg.first.userChatHistoryId, + // isReply: true, + // isImageLoaded: true, + // image: selectedFile.readAsBytesSync(), + // isVoiceAttached: false, + // userEmail: userEmail, + // userStatus: userStatus); + // } + // //Voice + // + // else if (!isTextMsg && !isAttachmentMsg && isVoiceMsg && !isReplyMsg) { + // logger.d("// Normal Voice Message"); + // + // if (!isPause) { + // path = await recorderController.stop(false); + // } + // if (kDebugMode) { + // logger.i("path:" + path!); + // } + // File voiceFile = File(path!); + // voiceFile.readAsBytesSync(); + // _timer?.cancel(); + // isPause = false; + // isPlaying = false; + // isRecoding = false; + // Utils.showLoading(context); + // dynamic value = await uploadAttachments(AppState().chatDetails!.response!.id.toString(), voiceFile, "1"); + // String? ext = getFileExtension(voiceFile.path); + // Utils.hideLoading(context); + // sendChatToServer( + // chatEventId: 2, + // fileTypeId: getFileType(ext.toString()), + // targetUserId: targetUserId, + // targetUserName: targetUserName, + // chatReplyId: null, + // isAttachment: true, + // isReply: isReplyMsg, + // isImageLoaded: false, + // voiceFile: voiceFile, + // isVoiceAttached: true, + // userEmail: userEmail, + // userStatus: userStatus); + // notifyListeners(); + // } else if (!isTextMsg && !isAttachmentMsg && isVoiceMsg && isReplyMsg) { + // logger.d("// Voice as Reply Msg"); + // + // if (!isPause) { + // path = await recorderController.stop(false); + // } + // if (kDebugMode) { + // logger.i("path:" + path!); + // } + // File voiceFile = File(path!); + // voiceFile.readAsBytesSync(); + // _timer?.cancel(); + // isPause = false; + // isPlaying = false; + // isRecoding = false; + // + // Utils.showLoading(context); + // dynamic value = await uploadAttachments(AppState().chatDetails!.response!.id.toString(), voiceFile, "1"); + // String? ext = getFileExtension(voiceFile.path); + // Utils.hideLoading(context); + // sendChatToServer( + // chatEventId: 2, + // fileTypeId: getFileType(ext.toString()), + // targetUserId: targetUserId, + // targetUserName: targetUserName, + // chatReplyId: null, + // isAttachment: true, + // isReply: isReplyMsg, + // isImageLoaded: false, + // voiceFile: voiceFile, + // isVoiceAttached: true, + // userEmail: userEmail, + // userStatus: userStatus); + // notifyListeners(); + // } + // if (searchedChats != null) { + // dynamic contain = searchedChats!.where((ChatUser element) => element.id == targetUserId); + // if (contain.isEmpty) { + // List emails = []; + // emails.add(await EmailImageEncryption().encrypt(val: userEmail)); + // List chatImages = await ChatApiClient().getUsersImages(encryptedEmails: emails); + // searchedChats!.add( + // ChatUser( + // id: targetUserId, + // userName: targetUserName, + // unreadMessageCount: 0, + // email: userEmail, + // isImageLoading: false, + // image: chatImages.first.profilePicture ?? "", + // isImageLoaded: true, + // isTyping: false, + // isFav: false, + // userStatus: userStatus, + // userLocalDownlaodedImage: await downloadImageLocal(chatImages.first.profilePicture, targetUserId.toString()), + // ), + // ); + // notifyListeners(); + // } + // } + // // else { + // // List emails = []; + // // emails.add(await EmailImageEncryption().encrypt(val: userEmail)); + // // List chatImages = await ChatApiClient().getUsersImages(encryptedEmails: emails); + // // searchedChats!.add( + // // ChatUser( + // // id: targetUserId, + // // userName: targetUserName, + // // unreadMessageCount: 0, + // // email: userEmail, + // // isImageLoading: false, + // // image: chatImages.first.profilePicture ?? "", + // // isImageLoaded: true, + // // isTyping: false, + // // isFav: false, + // // userStatus: userStatus, + // // userLocalDownlaodedImage: await downloadImageLocal(chatImages.first.profilePicture, targetUserId.toString()), + // // ), + // // ); + // // notifyListeners(); + // // } + // } + + // void selectImageToUpload(BuildContext context) { + // ImageOptions.showImageOptionsNew(context, true, (String image, File file) async { + // if (checkFileSize(file.path)) { + // selectedFile = file; + // isAttachmentMsg = true; + // isTextMsg = false; + // sFileType = getFileExtension(file.path)!; + // message.text = file.path.split("/").last; + // Navigator.of(context).pop(); + // } else { + // Utils.showToast("Max 1 mb size is allowed to upload"); + // } + // notifyListeners(); + // }); + // } + + // void removeAttachment() { + // isAttachmentMsg = false; + // sFileType = ""; + // message.text = ''; + // notifyListeners(); + // } String? getFileExtension(String fileName) { try { if (kDebugMode) { - logger.i("ext: " + "." + fileName.split('.').last); + // logger.i("ext: " + "." + fileName.split('.').last); } return "." + fileName.split('.').last; } catch (e) { @@ -1323,27 +1397,27 @@ class ChatProvider with ChangeNotifier, DiagnosticableTreeMixin { } } - void chatReply(SingleUserChatModel data) { - repliedMsg = []; - data.isReplied = true; - isReplyMsg = true; - repliedMsg.add(data); - notifyListeners(); - } + // void chatReply(SingleUserChatModel data) { + // repliedMsg = []; + // data.isReplied = true; + // isReplyMsg = true; + // repliedMsg.add(data); + // notifyListeners(); + // } - void groupChatReply(groupchathistory.GetGroupChatHistoryAsync data) { - groupChatReplyData = []; - data.isReplied = true; - isReplyMsg = true; - groupChatReplyData.add(data); - notifyListeners(); - } + // void groupChatReply(groupchathistory.GetGroupChatHistoryAsync data) { + // groupChatReplyData = []; + // data.isReplied = true; + // isReplyMsg = true; + // groupChatReplyData.add(data); + // notifyListeners(); + // } - void closeMe() { - repliedMsg = []; - isReplyMsg = false; - notifyListeners(); - } + // void closeMe() { + // repliedMsg = []; + // isReplyMsg = false; + // notifyListeners(); + // } String dateFormte(DateTime data) { DateFormat f = DateFormat('hh:mm a dd MMM yyyy', "en_US"); @@ -1351,171 +1425,171 @@ class ChatProvider with ChangeNotifier, DiagnosticableTreeMixin { return f.format(data); } - Future favoriteUser({required int userID, required int targetUserID, required bool fromSearch}) async { - fav.FavoriteChatUser favoriteChatUser = await ChatApiClient().favUser(userID: userID, targetUserID: targetUserID); - if (favoriteChatUser.response != null) { - for (ChatUser user in searchedChats!) { - if (user.id == favoriteChatUser.response!.targetUserId!) { - user.isFav = favoriteChatUser.response!.isFav; - dynamic contain = favUsersList!.where((ChatUser element) => element.id == favoriteChatUser.response!.targetUserId!); - if (contain.isEmpty) { - favUsersList.add(user); - } - } - } - - for (ChatUser user in chatUsersList!) { - if (user.id == favoriteChatUser.response!.targetUserId!) { - user.isFav = favoriteChatUser.response!.isFav; - dynamic contain = favUsersList!.where((ChatUser element) => element.id == favoriteChatUser.response!.targetUserId!); - if (contain.isEmpty) { - favUsersList.add(user); - } - } - } - } - if (fromSearch) { - for (ChatUser user in favUsersList) { - if (user.id == targetUserID) { - user.userLocalDownlaodedImage = null; - user.isImageLoading = false; - user.isImageLoaded = false; - } - } - } - notifyListeners(); - } - - Future unFavoriteUser({required int userID, required int targetUserID}) async { - fav.FavoriteChatUser favoriteChatUser = await ChatApiClient().unFavUser(userID: userID, targetUserID: targetUserID); - - if (favoriteChatUser.response != null) { - for (ChatUser user in searchedChats!) { - if (user.id == favoriteChatUser.response!.targetUserId!) { - user.isFav = favoriteChatUser.response!.isFav; - } - } - favUsersList.removeWhere( - (ChatUser element) => element.id == targetUserID, - ); - } - - for (ChatUser user in chatUsersList!) { - if (user.id == favoriteChatUser.response!.targetUserId!) { - user.isFav = favoriteChatUser.response!.isFav; - } - } - - notifyListeners(); - } - - void clearSelections() { - searchedChats = pChatHistory; - search.clear(); - isChatScreenActive = false; - receiverID = 0; - paginationVal = 0; - message.text = ''; - isAttachmentMsg = false; - repliedMsg = []; - sFileType = ""; - isReplyMsg = false; - isTextMsg = false; - isVoiceMsg = false; - notifyListeners(); - } - - void clearAll() { - searchedChats = pChatHistory; - search.clear(); - isChatScreenActive = false; - receiverID = 0; - paginationVal = 0; - message.text = ''; - isTextMsg = false; - isAttachmentMsg = false; - isVoiceMsg = false; - isReplyMsg = false; - repliedMsg = []; - sFileType = ""; - } - - void disposeData() { - if (!disbaleChatForThisUser) { - search.clear(); - isChatScreenActive = false; - receiverID = 0; - paginationVal = 0; - message.text = ''; - isTextMsg = false; - isAttachmentMsg = false; - isVoiceMsg = false; - isReplyMsg = false; - repliedMsg = []; - sFileType = ""; - deleteData(); - favUsersList.clear(); - searchedChats?.clear(); - pChatHistory?.clear(); - uGroups?.clear(); - searchGroup?.clear(); - chatHubConnection.stop(); - AppState().chatDetails = null; - } - } - - void deleteData() { - List exists = [], unique = []; - if (searchedChats != null) exists.addAll(searchedChats!); - exists.addAll(favUsersList!); - Map profileMap = {}; - for (ChatUser item in exists) { - profileMap[item.email!] = item; - } - unique = profileMap.values.toList(); - for (ChatUser element in unique!) { - deleteFile(element.id.toString()); - } - } - - void getUserImages() async { - List emails = []; - List exists = [], unique = []; - exists.addAll(searchedChats!); - exists.addAll(favUsersList!); - Map profileMap = {}; - for (ChatUser item in exists) { - profileMap[item.email!] = item; - } - unique = profileMap.values.toList(); - for (ChatUser element in unique!) { - emails.add(await EmailImageEncryption().encrypt(val: element.email!)); - } - - List chatImages = await ChatApiClient().getUsersImages(encryptedEmails: emails); - for (ChatUser user in searchedChats!) { - for (ChatUserImageModel uImage in chatImages) { - if (user.email == uImage.email) { - user.image = uImage.profilePicture ?? ""; - user.userLocalDownlaodedImage = await downloadImageLocal(uImage.profilePicture, user.id.toString()); - user.isImageLoading = false; - user.isImageLoaded = true; - } - } - } - for (ChatUser favUser in favUsersList) { - for (ChatUserImageModel uImage in chatImages) { - if (favUser.email == uImage.email) { - favUser.image = uImage.profilePicture ?? ""; - favUser.userLocalDownlaodedImage = await downloadImageLocal(uImage.profilePicture, favUser.id.toString()); - favUser.isImageLoading = false; - favUser.isImageLoaded = true; - } - } - } - - notifyListeners(); - } + // Future favoriteUser({required int userID, required int targetUserID, required bool fromSearch}) async { + // fav.FavoriteChatUser favoriteChatUser = await ChatApiClient().favUser(userID: userID, targetUserID: targetUserID); + // if (favoriteChatUser.response != null) { + // for (ChatUser user in searchedChats!) { + // if (user.id == favoriteChatUser.response!.targetUserId!) { + // user.isFav = favoriteChatUser.response!.isFav; + // dynamic contain = favUsersList!.where((ChatUser element) => element.id == favoriteChatUser.response!.targetUserId!); + // if (contain.isEmpty) { + // favUsersList.add(user); + // } + // } + // } + // + // for (ChatUser user in chatUsersList!) { + // if (user.id == favoriteChatUser.response!.targetUserId!) { + // user.isFav = favoriteChatUser.response!.isFav; + // dynamic contain = favUsersList!.where((ChatUser element) => element.id == favoriteChatUser.response!.targetUserId!); + // if (contain.isEmpty) { + // favUsersList.add(user); + // } + // } + // } + // } + // if (fromSearch) { + // for (ChatUser user in favUsersList) { + // if (user.id == targetUserID) { + // user.userLocalDownlaodedImage = null; + // user.isImageLoading = false; + // user.isImageLoaded = false; + // } + // } + // } + // notifyListeners(); + // } + // + // Future unFavoriteUser({required int userID, required int targetUserID}) async { + // fav.FavoriteChatUser favoriteChatUser = await ChatApiClient().unFavUser(userID: userID, targetUserID: targetUserID); + // + // if (favoriteChatUser.response != null) { + // for (ChatUser user in searchedChats!) { + // if (user.id == favoriteChatUser.response!.targetUserId!) { + // user.isFav = favoriteChatUser.response!.isFav; + // } + // } + // favUsersList.removeWhere( + // (ChatUser element) => element.id == targetUserID, + // ); + // } + // + // for (ChatUser user in chatUsersList!) { + // if (user.id == favoriteChatUser.response!.targetUserId!) { + // user.isFav = favoriteChatUser.response!.isFav; + // } + // } + // + // notifyListeners(); + // } + + // void clearSelections() { + // searchedChats = pChatHistory; + // search.clear(); + // isChatScreenActive = false; + // receiverID = 0; + // paginationVal = 0; + // message.text = ''; + // isAttachmentMsg = false; + // repliedMsg = []; + // sFileType = ""; + // isReplyMsg = false; + // isTextMsg = false; + // isVoiceMsg = false; + // notifyListeners(); + // } + // + // void clearAll() { + // searchedChats = pChatHistory; + // search.clear(); + // isChatScreenActive = false; + // receiverID = 0; + // paginationVal = 0; + // message.text = ''; + // isTextMsg = false; + // isAttachmentMsg = false; + // isVoiceMsg = false; + // isReplyMsg = false; + // repliedMsg = []; + // sFileType = ""; + // } + // + // void disposeData() { + // if (!disbaleChatForThisUser) { + // search.clear(); + // isChatScreenActive = false; + // receiverID = 0; + // paginationVal = 0; + // message.text = ''; + // isTextMsg = false; + // isAttachmentMsg = false; + // isVoiceMsg = false; + // isReplyMsg = false; + // repliedMsg = []; + // sFileType = ""; + // deleteData(); + // favUsersList.clear(); + // searchedChats?.clear(); + // pChatHistory?.clear(); + // // uGroups?.clear(); + // searchGroup?.clear(); + // chatHubConnection.stop(); + // // AppState().chatDetails = null; + // } + // } + // + // void deleteData() { + // List exists = [], unique = []; + // if (searchedChats != null) exists.addAll(searchedChats!); + // exists.addAll(favUsersList!); + // Map profileMap = {}; + // for (ChatUser item in exists) { + // profileMap[item.email!] = item; + // } + // unique = profileMap.values.toList(); + // for (ChatUser element in unique!) { + // deleteFile(element.id.toString()); + // } + // } + + // void getUserImages() async { + // List emails = []; + // List exists = [], unique = []; + // exists.addAll(searchedChats!); + // exists.addAll(favUsersList!); + // Map profileMap = {}; + // for (ChatUser item in exists) { + // profileMap[item.email!] = item; + // } + // unique = profileMap.values.toList(); + // for (ChatUser element in unique!) { + // emails.add(await EmailImageEncryption().encrypt(val: element.email!)); + // } + // + // List chatImages = await ChatApiClient().getUsersImages(encryptedEmails: emails); + // for (ChatUser user in searchedChats!) { + // for (ChatUserImageModel uImage in chatImages) { + // if (user.email == uImage.email) { + // user.image = uImage.profilePicture ?? ""; + // user.userLocalDownlaodedImage = await downloadImageLocal(uImage.profilePicture, user.id.toString()); + // user.isImageLoading = false; + // user.isImageLoaded = true; + // } + // } + // } + // for (ChatUser favUser in favUsersList) { + // for (ChatUserImageModel uImage in chatImages) { + // if (favUser.email == uImage.email) { + // favUser.image = uImage.profilePicture ?? ""; + // favUser.userLocalDownlaodedImage = await downloadImageLocal(uImage.profilePicture, favUser.id.toString()); + // favUser.isImageLoading = false; + // favUser.isImageLoaded = true; + // } + // } + // } + // + // notifyListeners(); + // } Future downloadImageLocal(String? encodedBytes, String userID) async { File? myfile; @@ -1570,25 +1644,25 @@ class ChatProvider with ChangeNotifier, DiagnosticableTreeMixin { } } - Future getChatMedia(BuildContext context, {required String fileName, required String fileTypeName, required int fileTypeID, required int fileSource}) async { - Utils.showLoading(context); - if (fileTypeID == 1 || fileTypeID == 5 || fileTypeID == 7 || fileTypeID == 6 || fileTypeID == 8 || fileTypeID == 2 || fileTypeID == 16) { - Uint8List encodedString = await ChatApiClient().downloadURL(fileName: fileName, fileTypeDescription: getFileTypeDescription(fileTypeName), fileSource: fileSource); - try { - String path = await downChatMedia(encodedString, fileTypeName ?? ""); - Utils.hideLoading(context); - OpenFilex.open(path); - } catch (e) { - Utils.showToast("Cannot open file."); - } - } - } + // Future getChatMedia(BuildContext context, {required String fileName, required String fileTypeName, required int fileTypeID, required int fileSource}) async { + // Utils.showLoading(context); + // if (fileTypeID == 1 || fileTypeID == 5 || fileTypeID == 7 || fileTypeID == 6 || fileTypeID == 8 || fileTypeID == 2 || fileTypeID == 16) { + // Uint8List encodedString = await ChatApiClient().downloadURL(fileName: fileName, fileTypeDescription: getFileTypeDescription(fileTypeName), fileSource: fileSource); + // try { + // String path = await downChatMedia(encodedString, fileTypeName ?? ""); + // Utils.hideLoading(context); + // OpenFilex.open(path); + // } catch (e) { + // Utils.showToast("Cannot open file."); + // } + // } + // } - void onNewChatConversion(List? params) { - dynamic items = params!.toList(); - chatUConvCounter = items[0]["singleChatCount"] ?? 0; - notifyListeners(); - } + // void onNewChatConversion(List? params) { + // dynamic items = params!.toList(); + // chatUConvCounter = items[0]["singleChatCount"] ?? 0; + // notifyListeners(); + // } Future invokeChatCounter({required int userId}) async { await chatHubConnection.invoke("GetChatCounversationCount", args: [userId]); @@ -1599,145 +1673,145 @@ class ChatProvider with ChangeNotifier, DiagnosticableTreeMixin { await chatHubConnection.invoke("UserTypingAsync", args: [reciptUser, currentUser]); } - void groupTypingInvoke({required GroupResponse groupDetails, required int groupId}) async { - var data = json.decode(json.encode(groupDetails.groupUserList)); - await chatHubConnection.invoke("GroupTypingAsync", args: ["${groupDetails.adminUser!.userName}", data, groupId]); - } + // void groupTypingInvoke({required GroupResponse groupDetails, required int groupId}) async { + // var data = json.decode(json.encode(groupDetails.groupUserList)); + // await chatHubConnection.invoke("GroupTypingAsync", args: ["${groupDetails.adminUser!.userName}", data, groupId]); + // } //////// Audio Recoding Work //////////////////// - Future initAudio({required int receiverId}) async { - // final dir = Directory((Platform.isAndroid - // ? await getExternalStorageDirectory() //FOR ANDROID - // : await getApplicationSupportDirectory() //FOR IOS - // )! - appDirectory = await getApplicationDocumentsDirectory(); - String dirPath = '${appDirectory.path}/chat_audios'; - if (!await Directory(dirPath).exists()) { - await Directory(dirPath).create(); - await File('$dirPath/.nomedia').create(); - } - path = "$dirPath/${AppState().chatDetails!.response!.id}-$receiverID-${DateTime.now().microsecondsSinceEpoch}.aac"; - recorderController = RecorderController() - ..androidEncoder = AndroidEncoder.aac - ..androidOutputFormat = AndroidOutputFormat.mpeg4 - ..iosEncoder = IosEncoder.kAudioFormatMPEG4AAC - ..sampleRate = 6000 - ..updateFrequency = const Duration(milliseconds: 100) - ..bitRate = 18000; - playerController = PlayerController(); - } - - void disposeAudio() { - isRecoding = false; - isPlaying = false; - isPause = false; - isVoiceMsg = false; - recorderController.dispose(); - playerController.dispose(); - } - - void startRecoding(BuildContext context) async { - await Permission.microphone.request().then((PermissionStatus status) { - if (status.isPermanentlyDenied) { - Utils.confirmDialog( - context, - "The app needs microphone access to be able to record audio.", - onTap: () { - Navigator.of(context).pop(); - openAppSettings(); - }, - ); - } else if (status.isDenied) { - Utils.confirmDialog( - context, - "The app needs microphone access to be able to record audio.", - onTap: () { - Navigator.of(context).pop(); - openAppSettings(); - }, - ); - } else if (status.isGranted) { - sRecoding(); - } else { - startRecoding(context); - } - }); - } - - void sRecoding() async { - isVoiceMsg = true; - recorderController.reset(); - await recorderController.record(path: path); - _recodeDuration = 0; - _startTimer(); - isRecoding = !isRecoding; - notifyListeners(); - } - - Future _startTimer() async { - _timer?.cancel(); - _timer = Timer.periodic(const Duration(seconds: 1), (Timer t) async { - _recodeDuration++; - if (_recodeDuration <= 59) { - applyCounter(); - } else { - pauseRecoding(); - } - }); - } - - void applyCounter() { - buildTimer(); - notifyListeners(); - } - - Future pauseRecoding() async { - isPause = true; - isPlaying = true; - recorderController.pause(); - path = await recorderController.stop(false); - File file = File(path!); - file.readAsBytesSync(); - path = file.path; - await playerController.preparePlayer(path: file.path, volume: 1.0); - _timer?.cancel(); - notifyListeners(); - } - - Future deleteRecoding() async { - _recodeDuration = 0; - _timer?.cancel(); - if (path == null) { - path = await recorderController.stop(true); - } else { - await recorderController.stop(true); - } - if (path != null && path!.isNotEmpty) { - File delFile = File(path!); - double fileSizeInKB = delFile.lengthSync() / 1024; - double fileSizeInMB = fileSizeInKB / 1024; - if (kDebugMode) { - debugPrint("Deleted file size: ${delFile.lengthSync()}"); - debugPrint("Deleted file size in KB: " + fileSizeInKB.toString()); - debugPrint("Deleted file size in MB: " + fileSizeInMB.toString()); - } - if (await delFile.exists()) { - delFile.delete(); - } - isPause = false; - isRecoding = false; - isPlaying = false; - isVoiceMsg = false; - notifyListeners(); - } - } - - String buildTimer() { - String minutes = _formatNum(_recodeDuration ~/ 60); - String seconds = _formatNum(_recodeDuration % 60); - return '$minutes : $seconds'; - } + // Future initAudio({required int receiverId}) async { + // // final dir = Directory((Platform.isAndroid + // // ? await getExternalStorageDirectory() //FOR ANDROID + // // : await getApplicationSupportDirectory() //FOR IOS + // // )! + // appDirectory = await getApplicationDocumentsDirectory(); + // String dirPath = '${appDirectory.path}/chat_audios'; + // if (!await Directory(dirPath).exists()) { + // await Directory(dirPath).create(); + // await File('$dirPath/.nomedia').create(); + // } + // path = "$dirPath/${AppState().chatDetails!.response!.id}-$receiverID-${DateTime.now().microsecondsSinceEpoch}.aac"; + // recorderController = RecorderController() + // ..androidEncoder = AndroidEncoder.aac + // ..androidOutputFormat = AndroidOutputFormat.mpeg4 + // ..iosEncoder = IosEncoder.kAudioFormatMPEG4AAC + // ..sampleRate = 6000 + // ..updateFrequency = const Duration(milliseconds: 100) + // ..bitRate = 18000; + // playerController = PlayerController(); + // } + + // void disposeAudio() { + // isRecoding = false; + // isPlaying = false; + // isPause = false; + // isVoiceMsg = false; + // recorderController.dispose(); + // playerController.dispose(); + // } + + // void startRecoding(BuildContext context) async { + // await Permission.microphone.request().then((PermissionStatus status) { + // if (status.isPermanentlyDenied) { + // Utils.confirmDialog( + // context, + // "The app needs microphone access to be able to record audio.", + // onTap: () { + // Navigator.of(context).pop(); + // openAppSettings(); + // }, + // ); + // } else if (status.isDenied) { + // Utils.confirmDialog( + // context, + // "The app needs microphone access to be able to record audio.", + // onTap: () { + // Navigator.of(context).pop(); + // openAppSettings(); + // }, + // ); + // } else if (status.isGranted) { + // sRecoding(); + // } else { + // startRecoding(context); + // } + // }); + // } + // + // void sRecoding() async { + // isVoiceMsg = true; + // recorderController.reset(); + // await recorderController.record(path: path); + // _recodeDuration = 0; + // _startTimer(); + // isRecoding = !isRecoding; + // notifyListeners(); + // } + // + // Future _startTimer() async { + // _timer?.cancel(); + // _timer = Timer.periodic(const Duration(seconds: 1), (Timer t) async { + // _recodeDuration++; + // if (_recodeDuration <= 59) { + // applyCounter(); + // } else { + // pauseRecoding(); + // } + // }); + // } + // + // void applyCounter() { + // buildTimer(); + // notifyListeners(); + // } + // + // Future pauseRecoding() async { + // isPause = true; + // isPlaying = true; + // recorderController.pause(); + // path = await recorderController.stop(false); + // File file = File(path!); + // file.readAsBytesSync(); + // path = file.path; + // await playerController.preparePlayer(path: file.path, volume: 1.0); + // _timer?.cancel(); + // notifyListeners(); + // } + // + // Future deleteRecoding() async { + // _recodeDuration = 0; + // _timer?.cancel(); + // if (path == null) { + // path = await recorderController.stop(true); + // } else { + // await recorderController.stop(true); + // } + // if (path != null && path!.isNotEmpty) { + // File delFile = File(path!); + // double fileSizeInKB = delFile.lengthSync() / 1024; + // double fileSizeInMB = fileSizeInKB / 1024; + // if (kDebugMode) { + // debugPrint("Deleted file size: ${delFile.lengthSync()}"); + // debugPrint("Deleted file size in KB: " + fileSizeInKB.toString()); + // debugPrint("Deleted file size in MB: " + fileSizeInMB.toString()); + // } + // if (await delFile.exists()) { + // delFile.delete(); + // } + // isPause = false; + // isRecoding = false; + // isPlaying = false; + // isVoiceMsg = false; + // notifyListeners(); + // } + // } + // + // String buildTimer() { + // String minutes = _formatNum(_recodeDuration ~/ 60); + // String seconds = _formatNum(_recodeDuration % 60); + // return '$minutes : $seconds'; + // } String _formatNum(int number) { String numberStr = number.toString(); @@ -1766,101 +1840,102 @@ class ChatProvider with ChangeNotifier, DiagnosticableTreeMixin { return file; } - void scrollToMsg(SingleUserChatModel data) { - if (data.userChatReplyResponse != null && data.userChatReplyResponse!.userChatHistoryId != null) { - int index = userChatHistory.indexWhere((SingleUserChatModel element) => element.userChatHistoryId == data.userChatReplyResponse!.userChatHistoryId); - if (index >= 1) { - double contentSize = scrollController.position.viewportDimension + scrollController.position.maxScrollExtent; - double target = contentSize * index / userChatHistory.length; - scrollController.position.animateTo( - target, - duration: const Duration(seconds: 1), - curve: Curves.easeInOut, - ); - } - } - } - - Future getTeamMembers() async { - teamMembersList = []; - isLoading = true; - if (AppState().getemployeeSubordinatesList.isNotEmpty) { - getEmployeeSubordinatesList = AppState().getemployeeSubordinatesList; - for (GetEmployeeSubordinatesList element in getEmployeeSubordinatesList) { - if (element.eMPLOYEEEMAILADDRESS != null) { - if (element.eMPLOYEEEMAILADDRESS!.isNotEmpty) { - teamMembersList.add( - ChatUser( - id: int.parse(element.eMPLOYEENUMBER!), - email: element.eMPLOYEEEMAILADDRESS, - userName: element.eMPLOYEENAME, - phone: element.eMPLOYEEMOBILENUMBER, - userStatus: 0, - unreadMessageCount: 0, - isFav: false, - isTyping: false, - isImageLoading: false, - image: element.eMPLOYEEIMAGE ?? "", - isImageLoaded: element.eMPLOYEEIMAGE == null ? false : true, - userLocalDownlaodedImage: element.eMPLOYEEIMAGE == null ? null : await downloadImageLocal(element.eMPLOYEEIMAGE ?? "", element.eMPLOYEENUMBER!), - ), - ); - } - } - } - } else { - getEmployeeSubordinatesList = await MyTeamApiClient().getEmployeeSubordinates("", "", ""); - AppState().setemployeeSubordinatesList = getEmployeeSubordinatesList; - for (GetEmployeeSubordinatesList element in getEmployeeSubordinatesList) { - if (element.eMPLOYEEEMAILADDRESS != null) { - if (element.eMPLOYEEEMAILADDRESS!.isNotEmpty) { - teamMembersList.add( - ChatUser( - id: int.parse(element.eMPLOYEENUMBER!), - email: element.eMPLOYEEEMAILADDRESS, - userName: element.eMPLOYEENAME, - phone: element.eMPLOYEEMOBILENUMBER, - userStatus: 0, - unreadMessageCount: 0, - isFav: false, - isTyping: false, - isImageLoading: false, - image: element.eMPLOYEEIMAGE ?? "", - isImageLoaded: element.eMPLOYEEIMAGE == null ? false : true, - userLocalDownlaodedImage: element.eMPLOYEEIMAGE == null ? null : await downloadImageLocal(element.eMPLOYEEIMAGE ?? "", element.eMPLOYEENUMBER!), - ), - ); - } - } - } - } - - for (ChatUser user in searchedChats!) { - for (ChatUser teamUser in teamMembersList!) { - if (user.id == teamUser.id) { - teamUser.userStatus = user.userStatus; - } - } - } - - isLoading = false; - notifyListeners(); - } - - void inputBoxDirection(String val) { - if (val.isNotEmpty) { - isTextMsg = true; - } else { - isTextMsg = false; - } - msgText = val; - notifyListeners(); - } - - void onDirectionChange(bool val) { - isRTL = val; - notifyListeners(); - } + // void scrollToMsg(SingleUserChatModel data) { + // if (data.userChatReplyResponse != null && data.userChatReplyResponse!.userChatHistoryId != null) { + // int index = userChatHistory.indexWhere((SingleUserChatModel element) => element.userChatHistoryId == data.userChatReplyResponse!.userChatHistoryId); + // if (index >= 1) { + // double contentSize = scrollController.position.viewportDimension + scrollController.position.maxScrollExtent; + // double target = contentSize * index / userChatHistory.length; + // scrollController.position.animateTo( + // target, + // duration: const Duration(seconds: 1), + // curve: Curves.easeInOut, + // ); + // } + // } + // } + + // + // Future getTeamMembers() async { + // teamMembersList = []; + // isLoading = true; + // if (AppState().getemployeeSubordinatesList.isNotEmpty) { + // getEmployeeSubordinatesList = AppState().getemployeeSubordinatesList; + // for (GetEmployeeSubordinatesList element in getEmployeeSubordinatesList) { + // if (element.eMPLOYEEEMAILADDRESS != null) { + // if (element.eMPLOYEEEMAILADDRESS!.isNotEmpty) { + // teamMembersList.add( + // ChatUser( + // id: int.parse(element.eMPLOYEENUMBER!), + // email: element.eMPLOYEEEMAILADDRESS, + // userName: element.eMPLOYEENAME, + // phone: element.eMPLOYEEMOBILENUMBER, + // userStatus: 0, + // unreadMessageCount: 0, + // isFav: false, + // isTyping: false, + // isImageLoading: false, + // image: element.eMPLOYEEIMAGE ?? "", + // isImageLoaded: element.eMPLOYEEIMAGE == null ? false : true, + // userLocalDownlaodedImage: element.eMPLOYEEIMAGE == null ? null : await downloadImageLocal(element.eMPLOYEEIMAGE ?? "", element.eMPLOYEENUMBER!), + // ), + // ); + // } + // } + // } + // } else { + // getEmployeeSubordinatesList = await MyTeamApiClient().getEmployeeSubordinates("", "", ""); + // AppState().setemployeeSubordinatesList = getEmployeeSubordinatesList; + // for (GetEmployeeSubordinatesList element in getEmployeeSubordinatesList) { + // if (element.eMPLOYEEEMAILADDRESS != null) { + // if (element.eMPLOYEEEMAILADDRESS!.isNotEmpty) { + // teamMembersList.add( + // ChatUser( + // id: int.parse(element.eMPLOYEENUMBER!), + // email: element.eMPLOYEEEMAILADDRESS, + // userName: element.eMPLOYEENAME, + // phone: element.eMPLOYEEMOBILENUMBER, + // userStatus: 0, + // unreadMessageCount: 0, + // isFav: false, + // isTyping: false, + // isImageLoading: false, + // image: element.eMPLOYEEIMAGE ?? "", + // isImageLoaded: element.eMPLOYEEIMAGE == null ? false : true, + // userLocalDownlaodedImage: element.eMPLOYEEIMAGE == null ? null : await downloadImageLocal(element.eMPLOYEEIMAGE ?? "", element.eMPLOYEENUMBER!), + // ), + // ); + // } + // } + // } + // } + // + // for (ChatUser user in searchedChats!) { + // for (ChatUser teamUser in teamMembersList!) { + // if (user.id == teamUser.id) { + // teamUser.userStatus = user.userStatus; + // } + // } + // } + // + // isLoading = false; + // notifyListeners(); + // } + + // void inputBoxDirection(String val) { + // if (val.isNotEmpty) { + // isTextMsg = true; + // } else { + // isTextMsg = false; + // } + // msgText = val; + // notifyListeners(); + // } + // + // void onDirectionChange(bool val) { + // isRTL = val; + // notifyListeners(); + // } Material.TextDirection getTextDirection(String v) { String str = v.trim(); @@ -1892,81 +1967,81 @@ class ChatProvider with ChangeNotifier, DiagnosticableTreeMixin { return Material.TextDirection.ltr; } - void openChatByNoti(BuildContext context) async { - SingleUserChatModel nUser = SingleUserChatModel(); - Utils.saveStringFromPrefs("isAppOpendByChat", "false"); - if (await Utils.getStringFromPrefs("notificationData") != "null") { - nUser = SingleUserChatModel.fromJson(jsonDecode(await Utils.getStringFromPrefs("notificationData"))); - Utils.saveStringFromPrefs("notificationData", "null"); - Future.delayed(const Duration(seconds: 2)); - for (ChatUser user in searchedChats!) { - if (user.id == nUser.targetUserId) { - Navigator.pushNamed(context, AppRoutes.chatDetailed, arguments: ChatDetailedScreenParams(user, false)); - return; - } - } - } - Utils.saveStringFromPrefs("notificationData", "null"); - } - - //group chat functions added here - - void filterGroups(String value) async { - // filter function added here. - List tmp = []; - if (value.isEmpty || value == "") { - tmp = userGroups.groupresponse!; - } else { - for (groups.GroupResponse element in uGroups!) { - if (element.groupName!.toLowerCase().contains(value.toLowerCase())) { - tmp.add(element); - } - } - } - uGroups = tmp; - notifyListeners(); - } - - Future deleteGroup(GroupResponse groupDetails) async { - isLoading = true; - await ChatApiClient().deleteGroup(groupDetails.groupId); - userGroups = await ChatApiClient().getGroupsByUserId(); - uGroups = userGroups.groupresponse; - isLoading = false; - notifyListeners(); - } - - Future getGroupChatHistory(groups.GroupResponse groupDetails) async { - isLoading = true; - groupChatHistory = await ChatApiClient().getGroupChatHistory(groupDetails.groupId, groupDetails.groupUserList as List); - - isLoading = false; - - notifyListeners(); - } - - void updateGroupAdmin(int? groupId, List groupUserList) async { - isLoading = true; - await ChatApiClient().updateGroupAdmin(groupId, groupUserList); - isLoading = false; - notifyListeners(); - } - - Future addGroupAndUsers(createGroup.CreateGroupRequest request) async { - isLoading = true; - var groups = await ChatApiClient().addGroupAndUsers(request); - userGroups.groupresponse!.add(GroupResponse.fromJson(json.decode(groups)['response'])); - - isLoading = false; - notifyListeners(); - } - - Future updateGroupAndUsers(createGroup.CreateGroupRequest request) async { - isLoading = true; - await ChatApiClient().updateGroupAndUsers(request); - userGroups = await ChatApiClient().getGroupsByUserId(); - uGroups = userGroups.groupresponse; - isLoading = false; - notifyListeners(); - } +// void openChatByNoti(BuildContext context) async { +// SingleUserChatModel nUser = SingleUserChatModel(); +// Utils.saveStringFromPrefs("isAppOpendByChat", "false"); +// if (await Utils.getStringFromPrefs("notificationData") != "null") { +// nUser = SingleUserChatModel.fromJson(jsonDecode(await Utils.getStringFromPrefs("notificationData"))); +// Utils.saveStringFromPrefs("notificationData", "null"); +// Future.delayed(const Duration(seconds: 2)); +// for (ChatUser user in searchedChats!) { +// if (user.id == nUser.targetUserId) { +// Navigator.pushNamed(context, AppRoutes.chatDetailed, arguments: ChatDetailedScreenParams(user, false)); +// return; +// } +// } +// } +// Utils.saveStringFromPrefs("notificationData", "null"); +// } + +//group chat functions added here + +// void filterGroups(String value) async { +// // filter function added here. +// List tmp = []; +// if (value.isEmpty || value == "") { +// tmp = userGroups.groupresponse!; +// } else { +// for (groups.GroupResponse element in uGroups!) { +// if (element.groupName!.toLowerCase().contains(value.toLowerCase())) { +// tmp.add(element); +// } +// } +// } +// uGroups = tmp; +// notifyListeners(); +// } + +// Future deleteGroup(GroupResponse groupDetails) async { +// isLoading = true; +// await ChatApiClient().deleteGroup(groupDetails.groupId); +// userGroups = await ChatApiClient().getGroupsByUserId(); +// uGroups = userGroups.groupresponse; +// isLoading = false; +// notifyListeners(); +// } +// +// Future getGroupChatHistory(groups.GroupResponse groupDetails) async { +// isLoading = true; +// groupChatHistory = await ChatApiClient().getGroupChatHistory(groupDetails.groupId, groupDetails.groupUserList as List); +// +// isLoading = false; +// +// notifyListeners(); +// } +// +// void updateGroupAdmin(int? groupId, List groupUserList) async { +// isLoading = true; +// await ChatApiClient().updateGroupAdmin(groupId, groupUserList); +// isLoading = false; +// notifyListeners(); +// } + +// Future addGroupAndUsers(createGroup.CreateGroupRequest request) async { +// isLoading = true; +// var groups = await ChatApiClient().addGroupAndUsers(request); +// userGroups.groupresponse!.add(GroupResponse.fromJson(json.decode(groups)['response'])); +// +// isLoading = false; +// notifyListeners(); +// } +// +// Future updateGroupAndUsers(createGroup.CreateGroupRequest request) async { +// isLoading = true; +// await ChatApiClient().updateGroupAndUsers(request); +// userGroups = await ChatApiClient().getGroupsByUserId(); +// uGroups = userGroups.groupresponse; +// isLoading = false; +// notifyListeners(); +// } } diff --git a/lib/modules/cx_module/chat/chat_rooms_page.dart b/lib/modules/cx_module/chat/chat_rooms_page.dart index 09c102ea..15540eaa 100644 --- a/lib/modules/cx_module/chat/chat_rooms_page.dart +++ b/lib/modules/cx_module/chat/chat_rooms_page.dart @@ -80,7 +80,7 @@ class _ChatPageState extends State { ), ], ).paddingOnly(top: 4, bottom: 4).onPress(() { - Navigator.push(context, CupertinoPageRoute(builder: (context) => ChatPage())); + // Navigator.push(context, CupertinoPageRoute(builder: (context) => ChatPage())); return; }), separatorBuilder: (cxt, index) => const Divider().defaultStyle(context), diff --git a/lib/modules/cx_module/chat/model/chat_login_response_model.dart b/lib/modules/cx_module/chat/model/chat_login_response_model.dart new file mode 100644 index 00000000..3fde6c54 --- /dev/null +++ b/lib/modules/cx_module/chat/model/chat_login_response_model.dart @@ -0,0 +1,30 @@ +class ChatLoginResponse { + String? token; + int? userId; + String? userName; + int? applicationId; + int? expiresIn; + String? context; + + ChatLoginResponse({this.token, this.userId, this.userName, this.applicationId, this.expiresIn, this.context}); + + ChatLoginResponse.fromJson(Map json) { + token = json['token']; + userId = json['userId']; + userName = json['userName']; + applicationId = json['applicationId']; + expiresIn = json['expiresIn']; + context = json['context']; + } + + Map toJson() { + final Map data = new Map(); + data['token'] = this.token; + data['userId'] = this.userId; + data['userName'] = this.userName; + data['applicationId'] = this.applicationId; + data['expiresIn'] = this.expiresIn; + data['context'] = this.context; + return data; + } +} diff --git a/lib/modules/cx_module/chat/model/chat_participant_model.dart b/lib/modules/cx_module/chat/model/chat_participant_model.dart new file mode 100644 index 00000000..6ef1d4e4 --- /dev/null +++ b/lib/modules/cx_module/chat/model/chat_participant_model.dart @@ -0,0 +1,65 @@ +class ChatParticipantModel { + int? id; + String? title; + String? conversationType; + List? participants; + String? lastMessage; + String? createdAt; + + ChatParticipantModel({this.id, this.title, this.conversationType, this.participants, this.lastMessage, this.createdAt}); + + ChatParticipantModel.fromJson(Map json) { + id = json['id']; + title = json['title']; + conversationType = json['conversationType']; + if (json['participants'] != null) { + participants = []; + json['participants'].forEach((v) { + participants!.add(new Participants.fromJson(v)); + }); + } + lastMessage = json['lastMessage']; + createdAt = json['createdAt']; + } + + Map toJson() { + final Map data = new Map(); + data['id'] = this.id; + data['title'] = this.title; + data['conversationType'] = this.conversationType; + if (this.participants != null) { + data['participants'] = this.participants!.map((v) => v.toJson()).toList(); + } + data['lastMessage'] = this.lastMessage; + data['createdAt'] = this.createdAt; + return data; + } +} + +class Participants { + String? userId; + String? userName; + String? employeeNumber; + String? role; + int? userStatus; + + Participants({this.userId, this.userName, this.employeeNumber, this.role, this.userStatus}); + + Participants.fromJson(Map json) { + userId = json['userId']; + userName = json['userName']; + employeeNumber = json['employeeNumber']; + role = json['role']; + userStatus = json['userStatus']; + } + + Map toJson() { + final Map data = new Map(); + data['userId'] = this.userId; + data['userName'] = this.userName; + data['employeeNumber'] = this.employeeNumber; + data['role'] = this.role; + data['userStatus'] = this.userStatus; + return data; + } +} diff --git a/lib/modules/cx_module/chat/model/user_chat_history_model.dart b/lib/modules/cx_module/chat/model/user_chat_history_model.dart new file mode 100644 index 00000000..40140c77 --- /dev/null +++ b/lib/modules/cx_module/chat/model/user_chat_history_model.dart @@ -0,0 +1,65 @@ +class UserChatHistoryModel { + List? response; + bool? isSuccess; + List? onlineUserConnId; + + UserChatHistoryModel({this.response, this.isSuccess, this.onlineUserConnId}); + + UserChatHistoryModel.fromJson(Map json) { + if (json['response'] != null) { + response = []; + json['response'].forEach((v) { + response!.add(new ChatResponse.fromJson(v)); + }); + } + isSuccess = json['isSuccess']; + onlineUserConnId = json['onlineUserConnId'].cast(); + } + + Map toJson() { + final Map data = new Map(); + if (this.response != null) { + data['response'] = this.response!.map((v) => v.toJson()).toList(); + } + data['isSuccess'] = this.isSuccess; + data['onlineUserConnId'] = this.onlineUserConnId; + return data; + } +} + +class ChatResponse { + int? id; + int? conversationId; + String? userId; + int? userIdInt; + String? userName; + String? content; + String? messageType; + String? createdAt; + + ChatResponse({this.id, this.conversationId, this.userId, this.userIdInt, this.userName, this.content, this.messageType, this.createdAt}); + + ChatResponse.fromJson(Map json) { + id = json['id']; + conversationId = json['conversationId']; + userId = json['userId']; + userIdInt = json['userIdInt']; + userName = json['userName']; + content = json['content']; + messageType = json['messageType']; + createdAt = json['createdAt']; + } + + Map toJson() { + final Map data = new Map(); + data['id'] = this.id; + data['conversationId'] = this.conversationId; + data['userId'] = this.userId; + data['userIdInt'] = this.userIdInt; + data['userName'] = this.userName; + data['content'] = this.content; + data['messageType'] = this.messageType; + data['createdAt'] = this.createdAt; + return data; + } +} diff --git a/lib/modules/cx_module/survey_page.dart b/lib/modules/cx_module/survey/survey_page.dart similarity index 97% rename from lib/modules/cx_module/survey_page.dart rename to lib/modules/cx_module/survey/survey_page.dart index ad8c0d28..fc67441c 100644 --- a/lib/modules/cx_module/survey_page.dart +++ b/lib/modules/cx_module/survey/survey_page.dart @@ -13,7 +13,10 @@ import 'package:test_sa/new_views/common_widgets/app_text_form_field.dart'; import 'package:test_sa/new_views/common_widgets/default_app_bar.dart'; class SurveyPage extends StatefulWidget { - SurveyPage({Key? key}) : super(key: key); + int moduleId; + int requestId; + + SurveyPage({Key? key, required this.moduleId, required this.requestId}) : super(key: key); @override _SurveyPageState createState() { @@ -29,6 +32,11 @@ class _SurveyPageState extends State { @override void initState() { super.initState(); + getSurveyQuestion(); + } + + void getSurveyQuestion(){ + } @override diff --git a/lib/modules/cx_module/survey/survey_provider.dart b/lib/modules/cx_module/survey/survey_provider.dart new file mode 100644 index 00000000..f9674c7c --- /dev/null +++ b/lib/modules/cx_module/survey/survey_provider.dart @@ -0,0 +1,34 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/foundation.dart'; +import 'package:test_sa/controllers/api_routes/api_manager.dart'; +import 'package:test_sa/controllers/api_routes/urls.dart'; + +class SurveyProvider with ChangeNotifier { + bool loading = false; + + void reset() { + loading = false; + // ChatApiClient().chatLoginResponse = null; + } + + Future getQuestionnaire(int surveySubmissionId) async { + reset(); + loading = true; + notifyListeners(); + final response = await ApiManager.instance.get(URLs.getQuestionnaire + "?surveySubmissionId=$surveySubmissionId"); + + loading = false; + + notifyListeners(); + } + +// Future loadChatHistory(int moduleId, int requestId) async { +// // loadChatHistoryLoading = true; +// // notifyListeners(); +// chatLoginResponse = await ChatApiClient().loadChatHistory(moduleId, requestId); +// loadChatHistoryLoading = false; +// notifyListeners(); +// } +} diff --git a/lib/new_views/pages/login_page.dart b/lib/new_views/pages/login_page.dart index 8d36d425..946eda54 100644 --- a/lib/new_views/pages/login_page.dart +++ b/lib/new_views/pages/login_page.dart @@ -1,3 +1,4 @@ +import 'package:flutter/cupertino.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:fluttertoast/fluttertoast.dart'; @@ -12,7 +13,8 @@ import 'package:test_sa/extensions/string_extensions.dart'; import 'package:test_sa/extensions/text_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; import 'package:test_sa/models/new_models/general_response_model.dart'; -import 'package:test_sa/modules/cx_module/survey_page.dart'; +import 'package:test_sa/modules/cx_module/chat/chat_page.dart'; +import 'package:test_sa/modules/cx_module/survey/survey_page.dart'; import 'package:test_sa/new_views/app_style/app_color.dart'; import 'package:test_sa/new_views/forget_password_module/forget_passwod_verify_otp.dart'; import 'package:test_sa/new_views/pages/land_page/land_page.dart'; @@ -226,9 +228,8 @@ class _LoginPageState extends State { } Future _login() async { - Navigator.push(context, MaterialPageRoute(builder: (context) => SurveyPage())); - - return; + // Navigator.push(context, CupertinoPageRoute(builder: (context) => ChatPage(moduleId: 1, requestId: 1845972))); + // return; if (!_formKey.currentState!.validate()) return; if (privacyPolicyChecked == false) {