chat voice message implementation

development_mirza
Aamir Muhammad 2 years ago
parent abd1fa9375
commit 5d93451c13

@ -57,6 +57,7 @@ class ChatApiClient {
return List<ChatUser>.from(json.decode(response.body).map((x) => ChatUser.fromJson(x))); return List<ChatUser>.from(json.decode(response.body).map((x) => ChatUser.fromJson(x)));
} }
//Get User Recent Chats
Future<ChatUserModel> getRecentChats() async { Future<ChatUserModel> getRecentChats() async {
try { try {
Response response = await ApiClient().getJsonForResponse( Response response = await ApiClient().getJsonForResponse(
@ -74,6 +75,7 @@ class ChatApiClient {
} }
} }
// Get Favorite Users
Future<ChatUserModel> getFavUsers() async { Future<ChatUserModel> getFavUsers() async {
Response favRes = await ApiClient().getJsonForResponse( Response favRes = await ApiClient().getJsonForResponse(
"${ApiConsts.chatFavUser}getFavUserById/${AppState().chatDetails!.response!.id}", "${ApiConsts.chatFavUser}getFavUserById/${AppState().chatDetails!.response!.id}",
@ -85,6 +87,7 @@ class ChatApiClient {
return ChatUserModel.fromJson(json.decode(favRes.body)); return ChatUserModel.fromJson(json.decode(favRes.body));
} }
//Get User Chat History
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 { try {
Response response = await ApiClient().getJsonForResponse( Response response = await ApiClient().getJsonForResponse(
@ -101,6 +104,7 @@ class ChatApiClient {
} }
} }
//Favorite Users
Future<fav.FavoriteChatUser> favUser({required int userID, required int targetUserID}) async { Future<fav.FavoriteChatUser> 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); Response response = await ApiClient().postJsonForResponse("${ApiConsts.chatFavUser}addFavUser", {"targetUserId": targetUserID, "userId": userID}, token: AppState().chatDetails!.response!.token);
if (!kReleaseMode) { if (!kReleaseMode) {
@ -110,6 +114,7 @@ class ChatApiClient {
return favoriteChatUser; return favoriteChatUser;
} }
//UnFavorite Users
Future<fav.FavoriteChatUser> unFavUser({required int userID, required int targetUserID}) async { Future<fav.FavoriteChatUser> unFavUser({required int userID, required int targetUserID}) async {
try { try {
Response response = await ApiClient().postJsonForResponse( Response response = await ApiClient().postJsonForResponse(
@ -128,9 +133,13 @@ class ChatApiClient {
} }
} }
// Upload Chat Media
Future<Object?> uploadMedia(String userId, File file) async { Future<Object?> uploadMedia(String userId, File file) async {
print("${ApiConsts.chatMediaImageUploadUrl}upload"); if (kDebugMode) {
print(AppState().chatDetails!.response!.token); print("${ApiConsts.chatMediaImageUploadUrl}upload");
print(AppState().chatDetails!.response!.token);
}
dynamic request = MultipartRequest('POST', Uri.parse('${ApiConsts.chatMediaImageUploadUrl}upload')); dynamic request = MultipartRequest('POST', Uri.parse('${ApiConsts.chatMediaImageUploadUrl}upload'));
request.fields.addAll({'userId': userId, 'fileSource': '1'}); request.fields.addAll({'userId': userId, 'fileSource': '1'});
request.files.add(await MultipartFile.fromPath('files', file.path)); request.files.add(await MultipartFile.fromPath('files', file.path));
@ -154,6 +163,7 @@ class ChatApiClient {
return data; return data;
} }
//Get Chat Users & Favorite Images
Future<List<ChatUserImageModel>> getUsersImages({required List<String> encryptedEmails}) async { Future<List<ChatUserImageModel>> getUsersImages({required List<String> encryptedEmails}) async {
List<ChatUserImageModel> imagesData = []; List<ChatUserImageModel> imagesData = [];
Response response = await ApiClient().postJsonForResponse( Response response = await ApiClient().postJsonForResponse(

@ -68,7 +68,9 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin {
Future<void> buildHubConnection() async { Future<void> buildHubConnection() async {
chatHubConnection = await getHubConnection(); chatHubConnection = await getHubConnection();
await chatHubConnection.start(); await chatHubConnection.start();
print("Startedddddddd"); if (kDebugMode) {
logger.i("Hub Conn: Startedddddddd");
}
chatHubConnection.on("OnDeliveredChatUserAsync", onMsgReceived); chatHubConnection.on("OnDeliveredChatUserAsync", onMsgReceived);
chatHubConnection.on("OnGetChatConversationCount", onNewChatConversion); chatHubConnection.on("OnGetChatConversationCount", onNewChatConversion);
} }
@ -91,7 +93,9 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin {
// chatHubConnection.on("OnUpdateUserChatHistoryWindowsAsync", updateChatHistoryWindow); // chatHubConnection.on("OnUpdateUserChatHistoryWindowsAsync", updateChatHistoryWindow);
chatHubConnection.on("OnGetUserChatHistoryNotDeliveredAsync", chatNotDelivered); chatHubConnection.on("OnGetUserChatHistoryNotDeliveredAsync", chatNotDelivered);
chatHubConnection.on("OnUpdateUserChatHistoryStatusAsync", updateUserChatStatus); chatHubConnection.on("OnUpdateUserChatHistoryStatusAsync", updateUserChatStatus);
print("Alll Registered"); if (kDebugMode) {
logger.i("All listeners registered");
}
} }
void getUserRecentChats() async { void getUserRecentChats() async {
@ -279,7 +283,9 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin {
void updateChatHistoryWindow(List<Object?>? args) { void updateChatHistoryWindow(List<Object?>? args) {
dynamic items = args!.toList(); dynamic items = args!.toList();
print("---------------------------------Update Chat History Windows Async -------------------------------------"); if (kDebugMode) {
logger.i("---------------------------------Update Chat History Windows Async -------------------------------------");
}
logger.d(items); logger.d(items);
// for (var user in searchedChats!) { // for (var user in searchedChats!) {
// if (user.id == items.first["id"]) { // if (user.id == items.first["id"]) {
@ -404,7 +410,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin {
} }
void OnSubmitChatAsync(List<Object?>? parameters) { void OnSubmitChatAsync(List<Object?>? parameters) {
logger.d(parameters); logger.i(parameters);
List<SingleUserChatModel> data = [], temp = []; List<SingleUserChatModel> data = [], temp = [];
for (dynamic msg in parameters!) { for (dynamic msg in parameters!) {
data = getSingleUserChatModel(jsonEncode(msg)); data = getSingleUserChatModel(jsonEncode(msg));
@ -563,8 +569,9 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin {
isImageLoaded: isImageLoaded, isImageLoaded: isImageLoaded,
voice: voice, voice: voice,
); );
print("Model data---------------------------"); if (kDebugMode) {
logger.d(data.toJson()); logger.i("model data: " + jsonEncode(data));
}
userChatHistory.insert(0, data); userChatHistory.insert(0, data);
isFileSelected = false; isFileSelected = false;
isMsgReply = false; isMsgReply = false;
@ -579,16 +586,19 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin {
void sendChatMessage(BuildContext context, {required int targetUserId, required int userStatus, required String userEmail, required String targetUserName}) async { void sendChatMessage(BuildContext context, {required int targetUserId, required int userStatus, required String userEmail, required String targetUserName}) async {
if (!isFileSelected && !isMsgReply) { if (!isFileSelected && !isMsgReply) {
print("Normal Text Msg"); if (kDebugMode) {
print("Normal Text Msg");
}
if (message.text == null || message.text.isEmpty) { if (message.text == null || message.text.isEmpty) {
return; return;
} }
sendChatToServer( sendChatToServer(
chatEventId: 1, fileTypeId: null, targetUserId: targetUserId, targetUserName: targetUserName, isAttachment: false, chatReplyId: null, isReply: false, isImageLoaded: false, image: null); chatEventId: 1, fileTypeId: null, targetUserId: targetUserId, targetUserName: targetUserName, isAttachment: false, chatReplyId: null, isReply: false, isImageLoaded: false, image: null);
} // normal Text msg }
if (isFileSelected && !isMsgReply) { if (isFileSelected && !isMsgReply) {
bool isImage = false; if (kDebugMode) {
print("Normal Attachment Msg"); logger.i("Normal Attachment Msg");
}
Utils.showLoading(context); Utils.showLoading(context);
dynamic value = await uploadAttachments(AppState().chatDetails!.response!.id.toString(), selectedFile); dynamic value = await uploadAttachments(AppState().chatDetails!.response!.id.toString(), selectedFile);
String? ext = getFileExtension(selectedFile.path); String? ext = getFileExtension(selectedFile.path);
@ -623,7 +633,9 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin {
image: repliedMsg.first.image); image: repliedMsg.first.image);
} // reply msg over image && normal } // reply msg over image && normal
if (isFileSelected && isMsgReply) { if (isFileSelected && isMsgReply) {
print("Reply With File"); if (kDebugMode) {
print("Reply With File");
}
Utils.showLoading(context); Utils.showLoading(context);
dynamic value = await uploadAttachments(AppState().chatDetails!.response!.id.toString(), selectedFile); dynamic value = await uploadAttachments(AppState().chatDetails!.response!.id.toString(), selectedFile);
String? ext = getFileExtension(selectedFile.path); String? ext = getFileExtension(selectedFile.path);
@ -711,7 +723,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin {
String? getFileExtension(String fileName) { String? getFileExtension(String fileName) {
try { try {
if (kDebugMode) { if (kDebugMode) {
print("ext: " + "." + fileName.split('.').last); logger.i("ext: " + "." + fileName.split('.').last);
} }
return "." + fileName.split('.').last; return "." + fileName.split('.').last;
} catch (e) { } catch (e) {
@ -836,7 +848,6 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin {
} }
void clearAll() { void clearAll() {
print("----------------- Disposed ---------------------------");
searchedChats = pChatHistory; searchedChats = pChatHistory;
search.clear(); search.clear();
isChatScreenActive = false; isChatScreenActive = false;
@ -1050,9 +1061,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin {
startRecoding(); startRecoding();
} else { } else {
recorderController.reset(); recorderController.reset();
logger.d(recorderController.isRecording);
await recorderController.record(path); await recorderController.record(path);
logger.d(recorderController.isRecording);
_recodeDuration = 0; _recodeDuration = 0;
_startTimer(); _startTimer();
isRecoding = !isRecoding; isRecoding = !isRecoding;
@ -1142,7 +1151,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin {
path = await recorderController.stop(false); path = await recorderController.stop(false);
} }
if (kDebugMode) { if (kDebugMode) {
print(path); logger.i("path:" + path!);
} }
File voiceFile = File(path!); File voiceFile = File(path!);
voiceFile.readAsBytesSync(); voiceFile.readAsBytesSync();
@ -1152,9 +1161,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin {
isRecoding = false; isRecoding = false;
Utils.showLoading(context); Utils.showLoading(context);
dynamic value = await uploadAttachments(AppState().chatDetails!.response!.id.toString(), voiceFile); dynamic value = await uploadAttachments(AppState().chatDetails!.response!.id.toString(), voiceFile);
logger.d(value);
String? ext = getFileExtension(voiceFile.path); String? ext = getFileExtension(voiceFile.path);
logger.d(voiceFile.path!.split("/").last);
Utils.hideLoading(context); Utils.hideLoading(context);
sendVoiceMessageToServer( sendVoiceMessageToServer(
msgText: voiceFile.path!.split("/").last, msgText: voiceFile.path!.split("/").last,
@ -1168,7 +1175,7 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin {
userStatus: userStatus, userStatus: userStatus,
chatReplyId: null, chatReplyId: null,
isAttachment: true, isAttachment: true,
isReply: false, isReply: isMsgReply,
voicFile: voiceFile, voicFile: voiceFile,
); );
notifyListeners(); notifyListeners();
@ -1278,7 +1285,6 @@ class ChatProviderModel with ChangeNotifier, DiagnosticableTreeMixin {
Uint8List encodedString = await ChatApiClient().downloadURL(fileName: data.contant!, fileTypeDescription: getFileTypeDescription(data.fileTypeResponse!.fileTypeName ?? "")); Uint8List encodedString = await ChatApiClient().downloadURL(fileName: data.contant!, fileTypeDescription: getFileTypeDescription(data.fileTypeResponse!.fileTypeName ?? ""));
try { try {
String path = await downChatVoice(encodedString, data.fileTypeResponse!.fileTypeName ?? "", data); String path = await downChatVoice(encodedString, data.fileTypeResponse!.fileTypeName ?? "", data);
logger.d(path);
File file = File(path!); File file = File(path!);
file.readAsBytesSync(); file.readAsBytesSync();
Utils.hideLoading(context); Utils.hideLoading(context);

@ -100,8 +100,7 @@ class ChatBubble extends StatelessWidget {
], ],
), ),
), ),
).paddingOnly(bottom: 7).onPress(() { ).paddingOnly(bottom: 7).onPress(() {}),
}),
if (fileTypeID == 12 || fileTypeID == 4 || fileTypeID == 3) if (fileTypeID == 12 || fileTypeID == 4 || fileTypeID == 3)
ClipRRect( ClipRRect(
borderRadius: BorderRadius.circular(5.0), borderRadius: BorderRadius.circular(5.0),
@ -204,8 +203,7 @@ class ChatBubble extends StatelessWidget {
], ],
), ),
), ),
).paddingOnly(bottom: 7).onPress(() { ).paddingOnly(bottom: 7).onPress(() {}),
}),
if (fileTypeID == 12 || fileTypeID == 4 || fileTypeID == 3) if (fileTypeID == 12 || fileTypeID == 4 || fileTypeID == 3)
ClipRRect( ClipRRect(
borderRadius: BorderRadius.circular(5.0), borderRadius: BorderRadius.circular(5.0),

@ -130,7 +130,7 @@ class _ChatDetailScreenState extends State<ChatDetailScreen> {
reverse: true, reverse: true,
itemCount: m.userChatHistory.length, itemCount: m.userChatHistory.length,
padding: const EdgeInsets.all(21), padding: const EdgeInsets.all(21),
separatorBuilder: (cxt, index) => 8.height, separatorBuilder: (BuildContext cxt, int index) => 8.height,
itemBuilder: (BuildContext context, int i) { itemBuilder: (BuildContext context, int i) {
return SwipeTo( return SwipeTo(
iconColor: MyColors.lightGreenColor, iconColor: MyColors.lightGreenColor,
@ -145,14 +145,17 @@ class _ChatDetailScreenState extends State<ChatDetailScreen> {
}, },
).onPress(() async { ).onPress(() async {
logger.d(m.userChatHistory[i].toJson()); logger.d(m.userChatHistory[i].toJson());
if (m.userChatHistory[i].fileTypeResponse != null && m.userChatHistory[i].fileTypeId! == 1 || if (m.userChatHistory[i].fileTypeResponse != null && m.userChatHistory[i].fileTypeId != null) {
m.userChatHistory[i].fileTypeId! == 5 || if (m.userChatHistory[i].fileTypeId! == 1 ||
m.userChatHistory[i].fileTypeId! == 7 || m.userChatHistory[i].fileTypeId! == 5 ||
m.userChatHistory[i].fileTypeId! == 6 || m.userChatHistory[i].fileTypeId! == 7 ||
m.userChatHistory[i].fileTypeId! == 8 || m.userChatHistory[i].fileTypeId! == 6 ||
m.userChatHistory[i].fileTypeId! == 2) { m.userChatHistory[i].fileTypeId! == 8
m.getChatMedia(context, // || m.userChatHistory[i].fileTypeId! == 2
fileTypeName: m.userChatHistory[i].fileTypeResponse!.fileTypeName ?? "", fileTypeID: m.userChatHistory[i].fileTypeId!, fileName: m.userChatHistory[i].contant!); ) {
m.getChatMedia(context,
fileTypeName: m.userChatHistory[i].fileTypeResponse!.fileTypeName ?? "", fileTypeID: m.userChatHistory[i].fileTypeId!, fileName: m.userChatHistory[i].contant!);
}
} }
}); });
}, },
@ -312,7 +315,7 @@ class _ChatDetailScreenState extends State<ChatDetailScreen> {
() => m.selectImageToUpload(context), () => m.selectImageToUpload(context),
), ),
).paddingOnly(right: 15), ).paddingOnly(right: 15),
Icon( const Icon(
Icons.mic, Icons.mic,
color: MyColors.lightGreenColor, color: MyColors.lightGreenColor,
).paddingOnly(right: 15).onPress(() { ).paddingOnly(right: 15).onPress(() {

Loading…
Cancel
Save