Merge branch 'master' into development_haroon

# Conflicts:
#	lib/ui/chat/chat_home_screen.dart
merge-requests/73/head
haroon amjad 3 years ago
commit 0ca002d9be

@ -18,8 +18,7 @@ class APIError {
APIError(this.errorCode, this.errorMessage); APIError(this.errorCode, this.errorMessage);
Map<String, dynamic> toJson() => Map<String, dynamic> toJson() => {'errorCode': errorCode, 'errorMessage': errorMessage};
{'errorCode': errorCode, 'errorMessage': errorMessage};
@override @override
String toString() { String toString() {
@ -54,8 +53,7 @@ APIException _throwAPIException(Response response) {
return APIException(APIException.INTERNAL_SERVER_ERROR); return APIException(APIException.INTERNAL_SERVER_ERROR);
case 444: case 444:
var downloadUrl = response.headers["location"]; var downloadUrl = response.headers["location"];
return APIException(APIException.UPGRADE_REQUIRED, return APIException(APIException.UPGRADE_REQUIRED, arguments: downloadUrl);
arguments: downloadUrl);
default: default:
return APIException(APIException.OTHER); return APIException(APIException.OTHER);
} }
@ -68,13 +66,8 @@ class ApiClient {
factory ApiClient() => _instance; factory ApiClient() => _instance;
Future<U> postJsonForObject<T, U>( Future<U> postJsonForObject<T, U>(FactoryConstructor<U> factoryConstructor, String url, T jsonObject,
FactoryConstructor<U> factoryConstructor, String url, T jsonObject, {String? token, Map<String, dynamic>? queryParameters, Map<String, String>? headers, int retryTimes = 0, bool isFormData = false}) async {
{String? token,
Map<String, dynamic>? queryParameters,
Map<String, String>? headers,
int retryTimes = 0,
bool isFormData = false}) async {
var _headers = {'Accept': 'application/json'}; var _headers = {'Accept': 'application/json'};
if (headers != null && headers.isNotEmpty) { if (headers != null && headers.isNotEmpty) {
_headers.addAll(headers); _headers.addAll(headers);
@ -84,12 +77,7 @@ class ApiClient {
var bodyJson = json.encode(jsonObject); var bodyJson = json.encode(jsonObject);
print("body:$bodyJson"); print("body:$bodyJson");
} }
var response = await postJsonForResponse(url, jsonObject, var response = await postJsonForResponse(url, jsonObject, token: token, queryParameters: queryParameters, headers: _headers, retryTimes: retryTimes, isFormData: isFormData);
token: token,
queryParameters: queryParameters,
headers: _headers,
retryTimes: retryTimes,
isFormData: isFormData);
// try { // try {
if (!kReleaseMode) { if (!kReleaseMode) {
logger.i("res: " + response.body); logger.i("res: " + response.body);
@ -102,8 +90,7 @@ class ApiClient {
return factoryConstructor(jsonData); return factoryConstructor(jsonData);
} else { } else {
APIError? apiError; APIError? apiError;
apiError = apiError = APIError(jsonData['ErrorCode'], jsonData['ErrorEndUserMessage']);
APIError(jsonData['ErrorCode'], jsonData['ErrorEndUserMessage']);
throw APIException(APIException.BAD_REQUEST, error: apiError); throw APIException(APIException.BAD_REQUEST, error: apiError);
} }
// } catch (ex) { // } catch (ex) {
@ -116,11 +103,7 @@ class ApiClient {
} }
Future<Response> postJsonForResponse<T>(String url, T jsonObject, Future<Response> postJsonForResponse<T>(String url, T jsonObject,
{String? token, {String? token, Map<String, dynamic>? queryParameters, Map<String, String>? headers, int retryTimes = 0, bool isFormData = false}) async {
Map<String, dynamic>? queryParameters,
Map<String, String>? headers,
int retryTimes = 0,
bool isFormData = false}) async {
String? requestBody; String? requestBody;
late Map<String, String> stringObj; late Map<String, String> stringObj;
if (jsonObject != null) { if (jsonObject != null) {
@ -134,22 +117,13 @@ class ApiClient {
if (isFormData) { if (isFormData) {
headers = {'Content-Type': 'application/x-www-form-urlencoded'}; headers = {'Content-Type': 'application/x-www-form-urlencoded'};
stringObj = ((jsonObject ?? {}) as Map<String, dynamic>) stringObj = ((jsonObject ?? {}) as Map<String, dynamic>).map((key, value) => MapEntry(key, value?.toString() ?? ""));
.map((key, value) => MapEntry(key, value?.toString() ?? ""));
} }
return await _postForResponse(url, isFormData ? stringObj : requestBody, return await _postForResponse(url, isFormData ? stringObj : requestBody, token: token, queryParameters: queryParameters, headers: headers, retryTimes: retryTimes);
token: token,
queryParameters: queryParameters,
headers: headers,
retryTimes: retryTimes);
} }
Future<Response> _postForResponse(String url, requestBody, Future<Response> _postForResponse(String url, requestBody, {String? token, Map<String, dynamic>? queryParameters, Map<String, String>? headers, int retryTimes = 0}) async {
{String? token,
Map<String, dynamic>? queryParameters,
Map<String, String>? headers,
int retryTimes = 0}) async {
try { try {
var _headers = <String, String>{}; var _headers = <String, String>{};
if (token != null) { if (token != null) {
@ -164,9 +138,7 @@ class ApiClient {
var queryString = new Uri(queryParameters: queryParameters).query; var queryString = new Uri(queryParameters: queryParameters).query;
url = url + '?' + queryString; url = url + '?' + queryString;
} }
var response = var response = await _post(Uri.parse(url), body: requestBody, headers: _headers).timeout(Duration(seconds: 120));
await _post(Uri.parse(url), body: requestBody, headers: _headers)
.timeout(Duration(seconds: 120));
if (response.statusCode >= 200 && response.statusCode < 300) { if (response.statusCode >= 200 && response.statusCode < 300) {
return response; return response;
@ -177,11 +149,7 @@ class ApiClient {
if (retryTimes > 0) { if (retryTimes > 0) {
print('will retry after 3 seconds...'); print('will retry after 3 seconds...');
await Future.delayed(Duration(seconds: 3)); await Future.delayed(Duration(seconds: 3));
return await _postForResponse(url, requestBody, return await _postForResponse(url, requestBody, token: token, queryParameters: queryParameters, headers: headers, retryTimes: retryTimes - 1);
token: token,
queryParameters: queryParameters,
headers: headers,
retryTimes: retryTimes - 1);
} else { } else {
throw APIException(APIException.OTHER, arguments: e); throw APIException(APIException.OTHER, arguments: e);
} }
@ -189,11 +157,7 @@ class ApiClient {
if (retryTimes > 0) { if (retryTimes > 0) {
print('will retry after 3 seconds...'); print('will retry after 3 seconds...');
await Future.delayed(Duration(seconds: 3)); await Future.delayed(Duration(seconds: 3));
return await _postForResponse(url, requestBody, return await _postForResponse(url, requestBody, token: token, queryParameters: queryParameters, headers: headers, retryTimes: retryTimes - 1);
token: token,
queryParameters: queryParameters,
headers: headers,
retryTimes: retryTimes - 1);
} else { } else {
throw APIException(APIException.OTHER, arguments: e); throw APIException(APIException.OTHER, arguments: e);
} }
@ -203,39 +167,23 @@ class ApiClient {
if (retryTimes > 0) { if (retryTimes > 0) {
print('will retry after 3 seconds...'); print('will retry after 3 seconds...');
await Future.delayed(Duration(seconds: 3)); await Future.delayed(Duration(seconds: 3));
return await _postForResponse(url, requestBody, return await _postForResponse(url, requestBody, token: token, queryParameters: queryParameters, headers: headers, retryTimes: retryTimes - 1);
token: token,
queryParameters: queryParameters,
headers: headers,
retryTimes: retryTimes - 1);
} else { } else {
throw APIException(APIException.OTHER, arguments: e); throw APIException(APIException.OTHER, arguments: e);
} }
} }
} }
Future<Response> getJsonForResponse<T>(String url, Future<Response> getJsonForResponse<T>(String url, {String? token, Map<String, dynamic>? queryParameters, Map<String, String>? headers, int retryTimes = 0}) async {
{String? token,
Map<String, dynamic>? queryParameters,
Map<String, String>? headers,
int retryTimes = 0}) async {
if (headers == null) { if (headers == null) {
headers = {'Content-Type': 'application/json'}; headers = {'Content-Type': 'application/json'};
} else { } else {
headers['Content-Type'] = 'application/json'; headers['Content-Type'] = 'application/json';
} }
return await _getForResponse(url, return await _getForResponse(url, token: token, queryParameters: queryParameters, headers: headers, retryTimes: retryTimes);
token: token,
queryParameters: queryParameters,
headers: headers,
retryTimes: retryTimes);
} }
Future<Response> _getForResponse(String url, Future<Response> _getForResponse(String url, {String? token, Map<String, dynamic>? queryParameters, Map<String, String>? headers, int retryTimes = 0}) async {
{String? token,
Map<String, dynamic>? queryParameters,
Map<String, String>? headers,
int retryTimes = 0}) async {
try { try {
var _headers = <String, String>{}; var _headers = <String, String>{};
if (token != null) { if (token != null) {
@ -250,8 +198,7 @@ class ApiClient {
var queryString = new Uri(queryParameters: queryParameters).query; var queryString = new Uri(queryParameters: queryParameters).query;
url = url + '?' + queryString; url = url + '?' + queryString;
} }
var response = await _get(Uri.parse(url), headers: _headers) var response = await _get(Uri.parse(url), headers: _headers).timeout(Duration(seconds: 60));
.timeout(Duration(seconds: 60));
if (response.statusCode >= 200 && response.statusCode < 300) { if (response.statusCode >= 200 && response.statusCode < 300) {
return response; return response;
@ -262,11 +209,7 @@ class ApiClient {
if (retryTimes > 0) { if (retryTimes > 0) {
print('will retry after 3 seconds...'); print('will retry after 3 seconds...');
await Future.delayed(Duration(seconds: 3)); await Future.delayed(Duration(seconds: 3));
return await _getForResponse(url, return await _getForResponse(url, token: token, queryParameters: queryParameters, headers: headers, retryTimes: retryTimes - 1);
token: token,
queryParameters: queryParameters,
headers: headers,
retryTimes: retryTimes - 1);
} else { } else {
throw APIException(APIException.OTHER, arguments: e); throw APIException(APIException.OTHER, arguments: e);
} }
@ -274,11 +217,7 @@ class ApiClient {
if (retryTimes > 0) { if (retryTimes > 0) {
print('will retry after 3 seconds...'); print('will retry after 3 seconds...');
await Future.delayed(Duration(seconds: 3)); await Future.delayed(Duration(seconds: 3));
return await _getForResponse(url, return await _getForResponse(url, token: token, queryParameters: queryParameters, headers: headers, retryTimes: retryTimes - 1);
token: token,
queryParameters: queryParameters,
headers: headers,
retryTimes: retryTimes - 1);
} else { } else {
throw APIException(APIException.OTHER, arguments: e); throw APIException(APIException.OTHER, arguments: e);
} }
@ -288,19 +227,14 @@ class ApiClient {
if (retryTimes > 0) { if (retryTimes > 0) {
print('will retry after 3 seconds...'); print('will retry after 3 seconds...');
await Future.delayed(Duration(seconds: 3)); await Future.delayed(Duration(seconds: 3));
return await _getForResponse(url, return await _getForResponse(url, token: token, queryParameters: queryParameters, headers: headers, retryTimes: retryTimes - 1);
token: token,
queryParameters: queryParameters,
headers: headers,
retryTimes: retryTimes - 1);
} else { } else {
throw APIException(APIException.OTHER, arguments: e); throw APIException(APIException.OTHER, arguments: e);
} }
} }
} }
Future<Response> _get(url, {Map<String, String>? headers}) => Future<Response> _get(url, {Map<String, String>? headers}) => _withClient((client) => client.get(url, headers: headers));
_withClient((client) => client.get(url, headers: headers));
bool _certificateCheck(X509Certificate cert, String host, int port) => true; bool _certificateCheck(X509Certificate cert, String host, int port) => true;
@ -314,8 +248,5 @@ class ApiClient {
} }
} }
Future<Response> _post(url, Future<Response> _post(url, {Map<String, String>? headers, body, Encoding? encoding}) => _withClient((client) => client.post(url, headers: headers, body: body, encoding: encoding));
{Map<String, String>? headers, body, Encoding? encoding}) =>
_withClient((client) =>
client.post(url, headers: headers, body: body, encoding: encoding));
} }

@ -1,10 +1,14 @@
import 'dart:convert'; import 'dart:convert';
import 'dart:io'; import 'dart:io';
import 'dart:typed_data';
import 'package:http/http.dart'; import 'package:http/http.dart';
import 'package:mohem_flutter_app/api/api_client.dart'; import 'package:mohem_flutter_app/api/api_client.dart';
import 'package:mohem_flutter_app/app_state/app_state.dart'; import 'package:mohem_flutter_app/app_state/app_state.dart';
import 'package:mohem_flutter_app/classes/consts.dart'; import 'package:mohem_flutter_app/classes/consts.dart';
import 'package:mohem_flutter_app/classes/utils.dart';
import 'package:mohem_flutter_app/exceptions/api_exception.dart';
import 'package:mohem_flutter_app/main.dart';
import 'package:mohem_flutter_app/models/chat/get_search_user_chat_model.dart'; import 'package:mohem_flutter_app/models/chat/get_search_user_chat_model.dart';
import 'package:mohem_flutter_app/models/chat/get_user_login_token_model.dart' as user; import 'package:mohem_flutter_app/models/chat/get_user_login_token_model.dart' as user;
import 'package:mohem_flutter_app/models/chat/make_user_favotire_unfavorite_chat_model.dart' as fav; import 'package:mohem_flutter_app/models/chat/make_user_favotire_unfavorite_chat_model.dart' as fav;
@ -43,6 +47,7 @@ class ChatApiClient {
); );
Future<ChatUserModel> getRecentChats() async { Future<ChatUserModel> getRecentChats() async {
try {
Response response = await ApiClient().getJsonForResponse( Response response = await ApiClient().getJsonForResponse(
"${ApiConsts.chatRecentUrl}getchathistorybyuserid", "${ApiConsts.chatRecentUrl}getchathistorybyuserid",
token: AppState().chatDetails!.response!.token, token: AppState().chatDetails!.response!.token,
@ -50,6 +55,22 @@ class ChatApiClient {
return ChatUserModel.fromJson( return ChatUserModel.fromJson(
json.decode(response.body), json.decode(response.body),
); );
} catch (e) {
e as APIException;
if (e.message == "api_common_unauthorized") {
logger.d("Token Generated On APIIIIII");
user.UserAutoLoginModel userLoginResponse = await ChatApiClient().getUserLoginToken();
if (userLoginResponse.response != null) {
AppState().setchatUserDetails = userLoginResponse;
getRecentChats();
} else {
Utils.showToast(
userLoginResponse.errorResponses!.first.fieldName.toString() + " Erorr",
);
}
}
throw e;
}
} }
Future<ChatUserModel> getFavUsers() async { Future<ChatUserModel> getFavUsers() async {
@ -63,11 +84,27 @@ class ChatApiClient {
} }
Future<Response> getSingleUserChatHistory({required int senderUID, required int receiverUID, required bool loadMore, bool isNewChat = false, required int paginationVal}) async { Future<Response> getSingleUserChatHistory({required int senderUID, required int receiverUID, required bool loadMore, bool isNewChat = false, required int paginationVal}) async {
try {
Response response = await ApiClient().getJsonForResponse( Response response = await ApiClient().getJsonForResponse(
"${ApiConsts.chatSingleUserHistoryUrl}GetUserChatHistory/$senderUID/$receiverUID/$paginationVal", "${ApiConsts.chatSingleUserHistoryUrl}GetUserChatHistory/$senderUID/$receiverUID/$paginationVal",
token: AppState().chatDetails!.response!.token, token: AppState().chatDetails!.response!.token,
); );
return response; return response;
} catch (e) {
e as APIException;
if (e.message == "api_common_unauthorized") {
user.UserAutoLoginModel userLoginResponse = await ChatApiClient().getUserLoginToken();
if (userLoginResponse.response != null) {
AppState().setchatUserDetails = userLoginResponse;
getSingleUserChatHistory(senderUID: senderUID, receiverUID: receiverUID, loadMore: loadMore, paginationVal: paginationVal);
} else {
Utils.showToast(
userLoginResponse.errorResponses!.first.fieldName.toString() + " Erorr",
);
}
}
throw e;
}
} }
Future<fav.FavoriteChatUser> favUser({required int userID, required int targetUserID}) async { Future<fav.FavoriteChatUser> favUser({required int userID, required int targetUserID}) async {
@ -83,6 +120,7 @@ class ChatApiClient {
} }
Future<fav.FavoriteChatUser> unFavUser({required int userID, required int targetUserID}) async { Future<fav.FavoriteChatUser> unFavUser({required int userID, required int targetUserID}) async {
try {
Response response = await ApiClient().postJsonForResponse( Response response = await ApiClient().postJsonForResponse(
"${ApiConsts.chatFavUser}deleteFavUser", "${ApiConsts.chatFavUser}deleteFavUser",
{"targetUserId": targetUserID, "userId": userID}, {"targetUserId": targetUserID, "userId": userID},
@ -90,6 +128,22 @@ class ChatApiClient {
); );
fav.FavoriteChatUser favoriteChatUser = fav.FavoriteChatUser.fromRawJson(response.body); fav.FavoriteChatUser favoriteChatUser = fav.FavoriteChatUser.fromRawJson(response.body);
return favoriteChatUser; return favoriteChatUser;
} catch (e) {
e as APIException;
if (e.message == "api_common_unauthorized") {
logger.d("Token Generated On APIIIIII");
user.UserAutoLoginModel userLoginResponse = await ChatApiClient().getUserLoginToken();
if (userLoginResponse.response != null) {
AppState().setchatUserDetails = userLoginResponse;
unFavUser(userID: userID, targetUserID: targetUserID);
} else {
Utils.showToast(
userLoginResponse.errorResponses!.first.fieldName.toString() + " Erorr",
);
}
}
throw e;
}
} }
Future<StreamedResponse> uploadMedia(String userId, File file) async { Future<StreamedResponse> uploadMedia(String userId, File file) async {
@ -100,4 +154,29 @@ class ChatApiClient {
StreamedResponse response = await request.send(); StreamedResponse response = await request.send();
return response; return response;
} }
// Download File For Chat
Future<Uint8List> downloadURL({required String fileName, required String fileTypeDescription}) async {
Response response = await ApiClient().postJsonForResponse(
"${ApiConsts.chatMediaImageUploadUrl}download",
{"fileType": fileTypeDescription, "fileName": fileName, "fileSource": 1},
token: AppState().chatDetails!.response!.token,
);
Uint8List data = Uint8List.fromList(response.bodyBytes);
return data;
}
Future getUsersImages({required List encryptedEmails}) async {
Response response = await ApiClient().postJsonForResponse(
"${ApiConsts.chatUserImages}images",
{
"encryptedEmails": ["/g8Rc+s6eEOdci41PwJuV5dX+gXe51G9OTHzb9ahcVlHCmVvNhxReirudF79+hdxVSkCnQ6wC5DBFV8xnJlC74X6157PxF7mNYrAYuHRgp4="],
"fromClient": true
},
token: AppState().chatDetails!.response!.token,
);
logger.d(response.body);
// Uint8List data = Uint8List.fromList(response.body);
}
} }

@ -182,22 +182,22 @@ class DashboardApiClient {
Future<ChatUnreadCovnCountModel> getChatCount() async { Future<ChatUnreadCovnCountModel> getChatCount() async {
Response response = await ApiClient().getJsonForResponse( Response response = await ApiClient().getJsonForResponse(
"${ApiConsts.chatServerBaseApiUrl}user/unreadconversationcount/${AppState().getUserName}", "${ApiConsts.chatLoginTokenUrl}unreadconversationcount/${AppState().getUserName}",
); );
return chatUnreadCovnCountModelFromJson(response.body); return chatUnreadCovnCountModelFromJson(response.body);
} }
// Future setAdvertisementViewed(String masterID, int advertisementId) async { // Future setAdvertisementViewed(String masterID, int advertisementId) async {
// String url = "${ApiConsts.cocRest}Mohemm_ITG_UpdateAdvertisementAsViewed"; // String url = "${ApiConsts.cocRest}Mohemm_ITG_UpdateAdvertisementAsViewed";
// //
// Map<String, dynamic> postParams = { // Map<String, dynamic> postParams = {
// "ItgNotificationMasterId": masterID, // "ItgNotificationMasterId": masterID,
// "ItgAdvertisement": {"advertisementId": advertisementId, "acknowledgment": true} //Mobile Id // "ItgAdvertisement": {"advertisementId": advertisementId, "acknowledgment": true} //Mobile Id
// }; // };
// postParams.addAll(AppState().postParamsJson); // postParams.addAll(AppState().postParamsJson);
// return await ApiClient().postJsonForObject((json) { // return await ApiClient().postJsonForObject((json) {
// // ItgMainRes responseData = ItgMainRes.fromJson(json); // // ItgMainRes responseData = ItgMainRes.fromJson(json);
// return json; // return json;
// }, url, postParams); // }, url, postParams);
// } // }
} }

@ -23,6 +23,7 @@ class ApiConsts {
static String chatSingleUserHistoryUrl = chatServerBaseApiUrl + "UserChatHistory/"; static String chatSingleUserHistoryUrl = chatServerBaseApiUrl + "UserChatHistory/";
static String chatMediaImageUploadUrl = chatServerBaseApiUrl + "shared/"; static String chatMediaImageUploadUrl = chatServerBaseApiUrl + "shared/";
static String chatFavUser = chatServerBaseApiUrl + "FavUser/"; static String chatFavUser = chatServerBaseApiUrl + "FavUser/";
static String chatUserImages = chatServerBaseUrl + "empservice/api/employee/";
} }
class SharedPrefsConsts { class SharedPrefsConsts {

@ -10,6 +10,7 @@ import 'package:mohem_flutter_app/api/chat/chat_api_client.dart';
import 'package:mohem_flutter_app/app_state/app_state.dart'; import 'package:mohem_flutter_app/app_state/app_state.dart';
import 'package:mohem_flutter_app/classes/consts.dart'; import 'package:mohem_flutter_app/classes/consts.dart';
import 'package:mohem_flutter_app/classes/utils.dart'; import 'package:mohem_flutter_app/classes/utils.dart';
import 'package:mohem_flutter_app/exceptions/api_exception.dart';
import 'package:mohem_flutter_app/main.dart'; import 'package:mohem_flutter_app/main.dart';
import 'package:mohem_flutter_app/models/chat/get_search_user_chat_model.dart'; import 'package:mohem_flutter_app/models/chat/get_search_user_chat_model.dart';
import 'package:mohem_flutter_app/models/chat/get_single_user_chat_list_model.dart'; import 'package:mohem_flutter_app/models/chat/get_single_user_chat_list_model.dart';
@ -587,6 +588,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin {
Future<void> unFavoriteUser({required int userID, required int targetUserID}) async { Future<void> unFavoriteUser({required int userID, required int targetUserID}) async {
fav.FavoriteChatUser favoriteChatUser = await ChatApiClient().unFavUser(userID: userID, targetUserID: targetUserID); fav.FavoriteChatUser favoriteChatUser = await ChatApiClient().unFavUser(userID: userID, targetUserID: targetUserID);
if (favoriteChatUser.response != null) { if (favoriteChatUser.response != null) {
for (ChatUser user in searchedChats!) { for (ChatUser user in searchedChats!) {
if (user.id == favoriteChatUser.response!.targetUserId!) { if (user.id == favoriteChatUser.response!.targetUserId!) {
@ -597,6 +599,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin {
(ChatUser element) => element.id == targetUserID, (ChatUser element) => element.id == targetUserID,
); );
} }
notifyListeners(); notifyListeners();
} }
@ -650,6 +653,11 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin {
); );
} }
// Future<void> getDownLoadFile(String fileName) async {
// var data = await ChatApiClient().downloadURL(fileName: "data");
// Image.memory(data);
// }
// void getUserChatHistoryNotDeliveredAsync({required int userId}) async { // void getUserChatHistoryNotDeliveredAsync({required int userId}) async {
// try { // try {
// await hubConnection.invoke("GetUserChatHistoryNotDeliveredAsync", args: [userId]); // await hubConnection.invoke("GetUserChatHistoryNotDeliveredAsync", args: [userId]);
@ -657,4 +665,13 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin {
// hubConnection.off("GetUserChatHistoryNotDeliveredAsync", method: chatNotDelivered); // hubConnection.off("GetUserChatHistoryNotDeliveredAsync", method: chatNotDelivered);
// } // }
// } // }
} }

@ -295,7 +295,6 @@ class DashboardProviderModel with ChangeNotifier, DiagnosticableTreeMixin {
} }
Future<void> getUserAutoLoginToken() async { Future<void> getUserAutoLoginToken() async {
logger.d("Token Generated On Home");
UserAutoLoginModel userLoginResponse = await ChatApiClient().getUserLoginToken(); UserAutoLoginModel userLoginResponse = await ChatApiClient().getUserLoginToken();
if (userLoginResponse.response != null) { if (userLoginResponse.response != null) {
AppState().setchatUserDetails = userLoginResponse; AppState().setchatUserDetails = userLoginResponse;
@ -315,7 +314,6 @@ class DashboardProviderModel with ChangeNotifier, DiagnosticableTreeMixin {
isChatHubLoding = false; isChatHubLoding = false;
return hub; return hub;
} }
void notify() { void notify() {
notifyListeners(); notifyListeners();
} }

@ -1,8 +1,13 @@
import 'dart:typed_data';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:mohem_flutter_app/api/api_client.dart';
import 'package:mohem_flutter_app/api/chat/chat_api_client.dart';
import 'package:mohem_flutter_app/classes/colors.dart'; import 'package:mohem_flutter_app/classes/colors.dart';
import 'package:mohem_flutter_app/extensions/int_extensions.dart'; import 'package:mohem_flutter_app/extensions/int_extensions.dart';
import 'package:mohem_flutter_app/extensions/string_extensions.dart'; import 'package:mohem_flutter_app/extensions/string_extensions.dart';
import 'package:mohem_flutter_app/extensions/widget_extensions.dart'; import 'package:mohem_flutter_app/extensions/widget_extensions.dart';
import 'package:mohem_flutter_app/main.dart';
// todo: @aamir use extension methods, and use correct widgets. // todo: @aamir use extension methods, and use correct widgets.
@ -16,7 +21,9 @@ class ChatBubble extends StatelessWidget {
required this.isDelivered, required this.isDelivered,
required this.dateTime, required this.dateTime,
required this.isReplied, required this.isReplied,
required this.userName}) required this.userName,
this.fileTypeID,
this.fileTypeDescription})
: super(key: key); : super(key: key);
final String text; final String text;
final String replyText; final String replyText;
@ -26,6 +33,8 @@ class ChatBubble extends StatelessWidget {
final String dateTime; final String dateTime;
final bool isReplied; final bool isReplied;
final String userName; final String userName;
final int? fileTypeID;
final String? fileTypeDescription;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@ -177,7 +186,8 @@ class ChatBubble extends StatelessWidget {
).expanded, ).expanded,
), ),
).paddingOnly(right: 5, bottom: 7), ).paddingOnly(right: 5, bottom: 7),
(text).toText12(), if (fileTypeID == 12 || fileTypeID == 4 || fileTypeID == 3) showImage().paddingOnly(right: 5),
if (fileTypeID != 12 || fileTypeID != 4 || fileTypeID != 3) (text).toText12(),
Align( Align(
alignment: Alignment.centerRight, alignment: Alignment.centerRight,
child: Row( child: Row(
@ -237,7 +247,7 @@ class ChatBubble extends StatelessWidget {
).expanded, ).expanded,
), ),
).paddingOnly(right: 5, bottom: 7), ).paddingOnly(right: 5, bottom: 7),
(text).toText12(color: Colors.white), if (fileTypeID == 12 || fileTypeID == 4 || fileTypeID == 3) showImage().paddingOnly(right: 5) else (text).toText12(color: Colors.white),
Align( Align(
alignment: Alignment.centerRight, alignment: Alignment.centerRight,
child: dateTime.toText10( child: dateTime.toText10(
@ -248,4 +258,26 @@ class ChatBubble extends StatelessWidget {
), ),
).paddingOnly(right: MediaQuery.of(context).size.width * 0.3); ).paddingOnly(right: MediaQuery.of(context).size.width * 0.3);
} }
Widget showImage() {
return FutureBuilder<Uint8List>(
future: ChatApiClient().downloadURL(fileName: text, fileTypeDescription: fileTypeDescription!),
builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
if (snapshot.connectionState != ConnectionState.waiting) {
if (snapshot.data == null) {
return (text).toText12(color: Colors.white);
} else {
return Image.memory(
snapshot.data,
height: 140,
width: 227,
fit: BoxFit.cover,
);
}
} else {
return const SizedBox(height: 140, width: 227, child: Center(child: CircularProgressIndicator()));
}
},
);
}
} }

@ -1,4 +1,5 @@
import 'dart:async'; import 'dart:async';
import 'dart:convert';
import 'package:easy_localization/easy_localization.dart'; import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
@ -9,6 +10,7 @@ import 'package:mohem_flutter_app/extensions/int_extensions.dart';
import 'package:mohem_flutter_app/extensions/string_extensions.dart'; import 'package:mohem_flutter_app/extensions/string_extensions.dart';
import 'package:mohem_flutter_app/extensions/widget_extensions.dart'; import 'package:mohem_flutter_app/extensions/widget_extensions.dart';
import 'package:mohem_flutter_app/generated/locale_keys.g.dart'; import 'package:mohem_flutter_app/generated/locale_keys.g.dart';
import 'package:mohem_flutter_app/main.dart';
import 'package:mohem_flutter_app/models/chat/call.dart'; import 'package:mohem_flutter_app/models/chat/call.dart';
import 'package:mohem_flutter_app/provider/chat_provider_model.dart'; import 'package:mohem_flutter_app/provider/chat_provider_model.dart';
import 'package:mohem_flutter_app/ui/chat/call/chat_outgoing_call_screen.dart'; import 'package:mohem_flutter_app/ui/chat/call/chat_outgoing_call_screen.dart';
@ -74,21 +76,14 @@ class _ChatDetailScreenState extends State<ChatDetailScreen> {
showHomeButton: false, showHomeButton: false,
image: userDetails["targetUser"].image, image: userDetails["targetUser"].image,
actions: [ actions: [
IconButton( SvgPicture.asset("assets/icons/chat/call.svg", width: 21, height: 23).onPress(() {
constraints: const BoxConstraints(),
onPressed: () {
// makeCall(callType: "AUDIO", con: hubConnection); // makeCall(callType: "AUDIO", con: hubConnection);
}, }),
icon: SvgPicture.asset("assets/icons/chat/call.svg", width: 22, height: 22), 24.width,
), SvgPicture.asset("assets/icons/chat/video_call.svg", width: 21, height: 18).onPress(() {
IconButton( // makeCall(callType: "VIDEO", con: hubConnection);
constraints: const BoxConstraints(), }),
onPressed: () { 21.width,
//makeCall(callType: "VIDEO", con: hubConnection);
},
icon: SvgPicture.asset("assets/icons/chat/video_call.svg", width: 20, height: 20),
),
10.width,
], ],
), ),
body: Consumer<ChatProviderModel>( body: Consumer<ChatProviderModel>(
@ -128,13 +123,17 @@ class _ChatDetailScreenState extends State<ChatDetailScreen> {
dateTime: m.dateFormte(m.userChatHistory[i].createdDate!), dateTime: m.dateFormte(m.userChatHistory[i].createdDate!),
isReplied: m.userChatHistory[i].userChatReplyResponse != null ? true : false, isReplied: m.userChatHistory[i].userChatReplyResponse != null ? true : false,
userName: AppState().chatDetails!.response!.userName == m.userChatHistory[i].currentUserName.toString() ? "You" : m.userChatHistory[i].currentUserName.toString(), userName: AppState().chatDetails!.response!.userName == m.userChatHistory[i].currentUserName.toString() ? "You" : m.userChatHistory[i].currentUserName.toString(),
fileTypeID: m.userChatHistory[i].fileTypeId,
fileTypeDescription: m.userChatHistory[i].fileTypeResponse!.fileTypeDescription,
), ),
onRightSwipe: () { onRightSwipe: () {
m.chatReply( m.chatReply(
m.userChatHistory[i], m.userChatHistory[i],
); );
}, },
); ).onPress(() {
logger.d(jsonEncode(m.userChatHistory[i]));
});
}, },
), ),
).expanded, ).expanded,
@ -181,12 +180,12 @@ class _ChatDetailScreenState extends State<ChatDetailScreen> {
disabledBorder: InputBorder.none, disabledBorder: InputBorder.none,
filled: true, filled: true,
fillColor: MyColors.white, fillColor: MyColors.white,
contentPadding: EdgeInsets.only( contentPadding: const EdgeInsets.only(
left: 21, left: 21,
top: 20, top: 20,
bottom: 20, bottom: 20,
), ),
prefixIconConstraints: BoxConstraints(), prefixIconConstraints: const BoxConstraints(),
prefixIcon: m.sFileType.isNotEmpty prefixIcon: m.sFileType.isNotEmpty
? SvgPicture.asset(m.getType(m.sFileType), height: 30, width: 22, alignment: Alignment.center, fit: BoxFit.cover).paddingOnly(left: 21, right: 15) ? SvgPicture.asset(m.getType(m.sFileType), height: 30, width: 22, alignment: Alignment.center, fit: BoxFit.cover).paddingOnly(left: 21, right: 15)
: null, : null,

@ -46,14 +46,9 @@ class _ChatHomeScreenState extends State<ChatHomeScreen> {
builder: (BuildContext context, ChatProviderModel m, Widget? child) { builder: (BuildContext context, ChatProviderModel m, Widget? child) {
return m.isLoading return m.isLoading
? ChatHomeShimmer() ? ChatHomeShimmer()
: ListView( : Column(
padding: EdgeInsets.zero,
shrinkWrap: true,
physics: const AlwaysScrollableScrollPhysics(),
children: <Widget>[ children: <Widget>[
Padding( TextField(
padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 20),
child: TextField(
controller: m.search, controller: m.search,
style: const TextStyle(color: MyColors.darkTextColor, fontWeight: FontWeight.w500, fontSize: 12), style: const TextStyle(color: MyColors.darkTextColor, fontWeight: FontWeight.w500, fontSize: 12),
onChanged: (String val) { onChanged: (String val) {
@ -80,20 +75,19 @@ class _ChatHomeScreenState extends State<ChatHomeScreen> {
) )
: null, : null,
), ),
), ).paddingOnly(top: 20, bottom: 14),
),
if (m.searchedChats != null) if (m.searchedChats != null)
ListView.separated( ListView.separated(
itemCount: m.searchedChats!.length, itemCount: m.searchedChats!.length,
padding: const EdgeInsets.only(bottom: 80),
shrinkWrap: true, shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(), physics: const ClampingScrollPhysics(),
itemBuilder: (BuildContext context, int index) { itemBuilder: (BuildContext context, int index) {
// todo @aamir, remove list tile, make a custom ui instead
return SizedBox( return SizedBox(
height: 55, height: 55,
// todo @aamir, remove list tile, make a custom ui instead child: Row(
child: ListTile( children: [
leading: Stack( Stack(
children: <Widget>[ children: <Widget>[
SvgPicture.asset( SvgPicture.asset(
"assets/images/user.svg", "assets/images/user.svg",
@ -116,36 +110,23 @@ class _ChatHomeScreenState extends State<ChatHomeScreen> {
) )
], ],
), ),
title: (m.searchedChats![index].userName!.replaceFirst(".", " ").capitalizeFirstofEach ?? "").toText14(color: MyColors.darkTextColor), Column(
// subtitle: (m.searchedChats![index].isTyping == true ? "Typing ..." : "").toText11(color: MyColors.normalTextColor), mainAxisAlignment: MainAxisAlignment.start,
trailing: SizedBox( crossAxisAlignment: CrossAxisAlignment.start,
children: [
(m.searchedChats![index].userName!.replaceFirst(".", " ").capitalizeFirstofEach ?? "").toText14(color: MyColors.darkTextColor).paddingOnly(left: 11, top: 13),
],
).expanded,
SizedBox(
width: 60, width: 60,
child: Row( child: Row(
crossAxisAlignment: CrossAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.end, mainAxisAlignment: MainAxisAlignment.end,
mainAxisSize: MainAxisSize.max, mainAxisSize: MainAxisSize.max,
children: <Widget>[ children: <Widget>[
// if (m.searchedChats![index].isLoadingCounter!)
// Flexible(
// child: Container(
// padding: EdgeInsets.zero,
// alignment: Alignment.centerRight,
// width: 18,
// height: 18,
// decoration: const BoxDecoration(
// // color: MyColors.redColor,
// borderRadius: BorderRadius.all(
// Radius.circular(20),
// ),
// ),
// child: CircularProgressIndicator(),
// ),
// ),
if (m.searchedChats![index].unreadMessageCount! > 0) if (m.searchedChats![index].unreadMessageCount! > 0)
Flexible( Container(
child: Container( alignment: Alignment.center,
padding: EdgeInsets.zero,
alignment: Alignment.centerRight,
width: 18, width: 18,
height: 18, height: 18,
decoration: const BoxDecoration( decoration: const BoxDecoration(
@ -159,18 +140,12 @@ class _ChatHomeScreenState extends State<ChatHomeScreen> {
color: MyColors.white, color: MyColors.white,
) )
.center, .center,
), ).paddingOnly(right: 10).center,
), Icon(
Flexible(
child: IconButton(
constraints: BoxConstraints(),
alignment: Alignment.centerRight,
padding: EdgeInsets.zero,
icon: Icon(
m.searchedChats![index].isFav != null && m.searchedChats![index].isFav == false ? Icons.star_sharp : Icons.star_sharp, m.searchedChats![index].isFav != null && m.searchedChats![index].isFav == false ? Icons.star_sharp : Icons.star_sharp,
),
color: m.searchedChats![index].isFav != null && m.searchedChats![index].isFav == true ? MyColors.yellowColor : MyColors.grey35Color, color: m.searchedChats![index].isFav != null && m.searchedChats![index].isFav == true ? MyColors.yellowColor : MyColors.grey35Color,
onPressed: () { ).onPress(
() {
if (m.searchedChats![index].isFav == null || m.searchedChats![index].isFav == false) { if (m.searchedChats![index].isFav == null || m.searchedChats![index].isFav == false) {
m.favoriteUser( m.favoriteUser(
userID: AppState().chatDetails!.response!.id!, userID: AppState().chatDetails!.response!.id!,
@ -188,13 +163,13 @@ class _ChatHomeScreenState extends State<ChatHomeScreen> {
); );
} }
}, },
), ).center
)
], ],
), ),
), ),
minVerticalPadding: 0, ],
onTap: () { ),
).onPress(() {
Navigator.pushNamed( Navigator.pushNamed(
context, context,
AppRoutes.chatDetailed, AppRoutes.chatDetailed,
@ -204,24 +179,12 @@ class _ChatHomeScreenState extends State<ChatHomeScreen> {
m.clearSelections(); m.clearSelections();
m.notifyListeners(); m.notifyListeners();
}); });
});
}, },
), separatorBuilder: (BuildContext context, int index) => const Divider(color: MyColors.lightGreyE5Color).paddingOnly(left: 59),
); ).paddingOnly(bottom: 70).expanded,
},
separatorBuilder: (BuildContext context, int index) => const Padding(
padding: EdgeInsets.only(
right: 10,
left: 70,
),
child: Divider(
color: Color(
0xFFE5E5E5,
),
),
),
),
], ],
); ).paddingOnly(left: 21, right: 21);
}, },
), ),
floatingActionButton: FloatingActionButton( floatingActionButton: FloatingActionButton(

@ -1,6 +1,7 @@
import 'package:flutter/cupertino.dart'; import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart'; import 'package:flutter_svg/flutter_svg.dart';
import 'package:mohem_flutter_app/main.dart';
import 'package:mohem_flutter_app/provider/chat_provider_model.dart'; import 'package:mohem_flutter_app/provider/chat_provider_model.dart';
import 'package:mohem_flutter_app/app_state/app_state.dart'; import 'package:mohem_flutter_app/app_state/app_state.dart';
import 'package:mohem_flutter_app/classes/colors.dart'; import 'package:mohem_flutter_app/classes/colors.dart';
@ -26,14 +27,14 @@ class ChatFavoriteUsersScreen extends StatelessWidget {
return m.favUsersList != null && m.favUsersList.isNotEmpty return m.favUsersList != null && m.favUsersList.isNotEmpty
? ListView.separated( ? ListView.separated(
itemCount: m.favUsersList!.length, itemCount: m.favUsersList!.length,
padding: const EdgeInsets.only(top: 20),
shrinkWrap: true, shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(), physics: const NeverScrollableScrollPhysics(),
itemBuilder: (BuildContext context, int index) { itemBuilder: (BuildContext context, int index) {
return SizedBox( return SizedBox(
height: 55, height: 55,
child: ListTile( child: Row(
leading: Stack( children: [
Stack(
children: <Widget>[ children: <Widget>[
SvgPicture.asset( SvgPicture.asset(
"assets/images/user.svg", "assets/images/user.svg",
@ -56,26 +57,37 @@ class ChatFavoriteUsersScreen extends StatelessWidget {
) )
], ],
), ),
title: (m.favUsersList![index].userName!.replaceFirst(".", " ").capitalizeFirstofEach ?? "").toText14( Column(
color: MyColors.darkTextColor, mainAxisAlignment: MainAxisAlignment.start,
), crossAxisAlignment: CrossAxisAlignment.start,
trailing: IconButton( children: [
alignment: Alignment.centerRight, (m.favUsersList![index].userName!.replaceFirst(".", " ").capitalizeFirstofEach ?? "").toText14(color: MyColors.darkTextColor).paddingOnly(left: 11, top: 13),
padding: EdgeInsets.zero, ],
icon: Icon( ).expanded,
SizedBox(
width: 60,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.end,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
Icon(
m.favUsersList![index].isFav! ? Icons.star : Icons.star_border, m.favUsersList![index].isFav! ? Icons.star : Icons.star_border,
),
color: m.favUsersList![index].isFav! ? MyColors.yellowColor : MyColors.grey35Color, color: m.favUsersList![index].isFav! ? MyColors.yellowColor : MyColors.grey35Color,
onPressed: () { ).onPress(() {
if (m.favUsersList![index].isFav!) if (m.favUsersList![index].isFav!) {
m.unFavoriteUser( m.unFavoriteUser(
userID: AppState().chatDetails!.response!.id!, userID: AppState().chatDetails!.response!.id!,
targetUserID: m.favUsersList![index].id!, targetUserID: m.favUsersList![index].id!,
); );
}, }
}).center,
],
),
),
],
), ),
minVerticalPadding: 0, ).onPress(() {
onTap: () {
Navigator.pushNamed( Navigator.pushNamed(
context, context,
AppRoutes.chatDetailed, AppRoutes.chatDetailed,
@ -85,22 +97,10 @@ class ChatFavoriteUsersScreen extends StatelessWidget {
m.clearSelections(); m.clearSelections();
}, },
); );
});
}, },
), separatorBuilder: (BuildContext context, int index) => const Divider(color: MyColors.lightGreyE5Color).paddingOnly(left: 70),
); ).paddingAll(21)
},
separatorBuilder: (BuildContext context, int index) => const Padding(
padding: EdgeInsets.only(
right: 10,
left: 70,
),
child: Divider(
color: Color(
0xFFE5E5E5,
),
),
),
)
: Column( : Column(
children: <Widget>[ children: <Widget>[
Utils.getNoDataWidget(context).expanded, Utils.getNoDataWidget(context).expanded,

@ -20,7 +20,7 @@ class ImageOptions {
if (Platform.isAndroid) { if (Platform.isAndroid) {
cameraImageAndroid(image); cameraImageAndroid(image);
} else { } else {
File _image = File((await ImagePicker.platform.pickImage(source: ImageSource.camera, imageQuality: 20))?.path ?? ""); File _image = File((await ImagePicker.platform.pickImage(source: ImageSource.camera, imageQuality: 10))?.path ?? "");
String fileName = _image.path; String fileName = _image.path;
var bytes = File(fileName).readAsBytesSync(); var bytes = File(fileName).readAsBytesSync();
String base64Encode = base64.encode(bytes); String base64Encode = base64.encode(bytes);
@ -33,7 +33,7 @@ class ImageOptions {
if (Platform.isAndroid) { if (Platform.isAndroid) {
galleryImageAndroid(image); galleryImageAndroid(image);
} else { } else {
File _image = File((await ImagePicker.platform.pickImage(source: ImageSource.gallery, imageQuality: 20))?.path ?? ""); File _image = File((await ImagePicker.platform.pickImage(source: ImageSource.gallery, imageQuality: 10))?.path ?? "");
String fileName = _image.path; String fileName = _image.path;
var bytes = File(fileName).readAsBytesSync(); var bytes = File(fileName).readAsBytesSync();
String base64Encode = base64.encode(bytes); String base64Encode = base64.encode(bytes);
@ -74,7 +74,7 @@ class ImageOptions {
if (Platform.isAndroid) { if (Platform.isAndroid) {
galleryImageAndroid(image); galleryImageAndroid(image);
} else { } else {
File _image = File((await ImagePicker.platform.pickImage(source: ImageSource.gallery, imageQuality: 20))?.path ?? ""); File _image = File((await ImagePicker.platform.pickImage(source: ImageSource.gallery, imageQuality: 10))?.path ?? "");
String fileName = _image.path; String fileName = _image.path;
var bytes = File(fileName).readAsBytesSync(); var bytes = File(fileName).readAsBytesSync();
String base64Encode = base64.encode(bytes); String base64Encode = base64.encode(bytes);
@ -91,7 +91,7 @@ class ImageOptions {
if (Platform.isAndroid) { if (Platform.isAndroid) {
cameraImageAndroid(image); cameraImageAndroid(image);
} else { } else {
File _image = File((await ImagePicker.platform.pickImage(source: ImageSource.camera, imageQuality: 20))?.path ?? ""); File _image = File((await ImagePicker.platform.pickImage(source: ImageSource.camera, imageQuality: 10))?.path ?? "");
String fileName = _image.path; String fileName = _image.path;
var bytes = File(fileName).readAsBytesSync(); var bytes = File(fileName).readAsBytesSync();
String base64Encode = base64.encode(bytes); String base64Encode = base64.encode(bytes);
@ -114,7 +114,7 @@ class ImageOptions {
} }
void galleryImageAndroid(Function(String, File) image) async { void galleryImageAndroid(Function(String, File) image) async {
File _image = File((await ImagePicker.platform.pickImage(source: ImageSource.gallery, imageQuality: 20))?.path ?? ""); File _image = File((await ImagePicker.platform.pickImage(source: ImageSource.gallery, imageQuality: 10))?.path ?? "");
String fileName = _image.path; String fileName = _image.path;
var bytes = File(fileName).readAsBytesSync(); var bytes = File(fileName).readAsBytesSync();
String base64Encode = base64.encode(bytes); String base64Encode = base64.encode(bytes);
@ -124,7 +124,7 @@ void galleryImageAndroid(Function(String, File) image) async {
} }
void cameraImageAndroid(Function(String, File) image) async { void cameraImageAndroid(Function(String, File) image) async {
File _image = File((await ImagePicker.platform.pickImage(source: ImageSource.camera, imageQuality: 20))?.path ?? ""); File _image = File((await ImagePicker.platform.pickImage(source: ImageSource.camera, imageQuality: 10))?.path ?? "");
String fileName = _image.path; String fileName = _image.path;
var bytes = File(fileName).readAsBytesSync(); var bytes = File(fileName).readAsBytesSync();
String base64Encode = base64.encode(bytes); String base64Encode = base64.encode(bytes);

Loading…
Cancel
Save