import 'dart:async'; import 'dart:convert'; import 'dart:developer' as log1; import 'dart:io'; import 'dart:math'; import 'package:signalr_netcore/ihub_protocol.dart'; import 'package:signalr_netcore/signalr_client.dart'; import 'package:audioplayers/audioplayers.dart' as audioplayers; import 'package:flutter/foundation.dart'; import 'package:flutter_sound/flutter_sound.dart' as sound; import 'package:http/http.dart'; import 'package:permission_handler/permission_handler.dart'; import 'package:test_sa/controllers/api_routes/api_manager.dart'; import 'package:test_sa/controllers/api_routes/urls.dart'; import '../model/copilot_message_model.dart'; enum PttStatus { idle, connecting, recording, thinking, playingAudio, error } class CopilotProvider extends ChangeNotifier { List history = []; bool historyLoading = false; List messages = []; bool conversationLoading = false; bool isStreaming = false; bool isTranscribing = false; String? sessionId; String? errorMessage; StreamSubscription? _streamSub; HubConnection? _pttHub; PttStatus pttStatus = PttStatus.idle; String? pttErrorMessage; List pttMessages = []; String? pttSessionId; bool _pttButtonHeld = false; final sound.FlutterSoundRecorder _pttRecorder = sound.FlutterSoundRecorder(); bool _pttRecorderOpen = false; StreamController? _pttMicStreamController; StreamSubscription? _pttMicSub; Future _pttSendQueue = Future.value(); int _pttChunkCount = 0; final audioplayers.AudioPlayer _pttAudioPlayer = audioplayers.AudioPlayer(); final List _pttAudioQueue = []; bool _pttIsPlayingAudio = false; CopilotMessage? _pttCurrentAssistantMsg; void _pttLog(String message) => log1.log('[PTT] $message'); Future loadHistory() async { historyLoading = true; errorMessage = null; notifyListeners(); try { final res = await ApiManager.instance.get( URLs.copilotGetQueryHistory, enableToastMessage: false, ); final decoded = jsonDecode(res.body); if (decoded is Map && decoded['isSuccess'] == true) { final List threads = decoded['data']?['threads'] ?? []; history = threads.map((e) => CopilotHistoryItem.fromJson(e)).toList(); } else { errorMessage = (decoded is Map ? decoded['message'] : null) ?? "Failed to load history"; } } catch (e) { errorMessage = "Failed to load history"; } finally { historyLoading = false; notifyListeners(); } } Future deleteHistory(String threadId) async { final prevList = List.from(history); try { final res = await ApiManager.instance.delete(URLs.copilotDeleteQueryHistory(threadId), body: const {}); final decoded = jsonDecode(res.body); final success = decoded is Map && decoded['isSuccess'] == true && decoded['data'] == true; if (success) { history.removeWhere((h) => h.threadId == threadId); notifyListeners(); } else { history = prevList; errorMessage = (decoded is Map ? decoded['message'] : null) ?? "Failed to delete"; notifyListeners(); } } catch (e) { history = prevList; errorMessage = "Failed to delete"; notifyListeners(); } } Future loadConversation(String threadId) async { conversationLoading = true; errorMessage = null; messages = []; sessionId = threadId; notifyListeners(); try { final res = await ApiManager.instance.get( URLs.copilotGetConversationByThreadId(threadId), enableToastMessage: false, ); final decoded = jsonDecode(res.body); if (decoded is Map && decoded['isSuccess'] == true) { final List rawMessages = decoded['data']?['messages'] ?? []; messages = rawMessages.map((e) => CopilotMessage.fromHistoryJson(e)).toList(); } else { errorMessage = (decoded is Map ? decoded['message'] : null) ?? "Failed to load conversation"; } } catch (e) { errorMessage = "Failed to load conversation"; } finally { conversationLoading = false; notifyListeners(); } } void startNewConversation() { _streamSub?.cancel(); sessionId = null; messages = []; errorMessage = null; isStreaming = false; notifyListeners(); } Future sendText(String query, String language) async { if (isStreaming || query.trim().isEmpty) return; sessionId ??= _generateSessionId(); messages.add(CopilotMessage(id: UniqueKey().toString(), role: CopilotRole.user, content: query, timestamp: DateTime.now())); final assistantMsg = CopilotMessage(id: UniqueKey().toString(), role: CopilotRole.assistant, isStreaming: true, timestamp: DateTime.now()); messages.add(assistantMsg); isStreaming = true; errorMessage = null; notifyListeners(); try { final streamedResponse = await ApiManager.instance.postFormDataStreaming( URLs.copilotQueryStream, body: { "sessionId": sessionId!, "isAudio": "false", "langId": "$language", 'isFromMobile': 'true', "query": query, }, ); await _consumeStream(streamedResponse, assistantMsg, null); } catch (e) { _onStreamError(assistantMsg, e); } } Future sendAudio(File audioFile, String language) async { if (isStreaming) return; sessionId ??= _generateSessionId(); final humanAudioMsg = CopilotMessage(id: UniqueKey().toString(), role: CopilotRole.user, localAudioPath: audioFile.path, timestamp: DateTime.now()); messages.add(humanAudioMsg); final assistantMsg = CopilotMessage(id: UniqueKey().toString(), role: CopilotRole.assistant, isStreaming: true, timestamp: DateTime.now()); messages.add(assistantMsg); isStreaming = true; errorMessage = null; notifyListeners(); try { final streamedResponse = await ApiManager.instance.postFormDataStreamingWithFile( URLs.copilotQueryStream, fields: { "sessionId": sessionId!, "isAudio": "true", "langId": "$language", 'isFromMobile': 'true', }, fileFieldName: "AudioFile", file: audioFile, filename: audioFile.path.split('/').last, ); await _consumeStream(streamedResponse, assistantMsg, humanAudioMsg); } catch (e) { _onStreamError(assistantMsg, e); } } Future transcribeAudio(File audioFile, String language) async { isTranscribing = true; errorMessage = null; notifyListeners(); final exists = await audioFile.exists(); final sizeBytes = exists ? await audioFile.length() : 0; if (!exists || sizeBytes == 0) { errorMessage = "Recording file is empty or missing"; isTranscribing = false; notifyListeners(); return null; } try { final response = await ApiManager.instance.multiPart( URLs.copilotAudioTranscription, body: { "langId": language, }, showToast: false, files: [ MultipartFile.fromPath("AudioFile", audioFile.path, filename: audioFile.path.split('/').last), ], ); if (response.statusCode < 200 || response.statusCode >= 300) { errorMessage = "Failed to transcribe audio"; return null; } return _extractTranscriptionText(response.body); } catch (e) { errorMessage = "Failed to transcribe audio"; return null; } finally { isTranscribing = false; notifyListeners(); } } String? _extractTranscriptionText(String rawBody) { final trimmedRaw = rawBody.trim(); if (trimmedRaw.isEmpty) return null; try { final decoded = jsonDecode(trimmedRaw); if (decoded is String) { return decoded.trim(); } else if (decoded is Map) { final map = Map.from(decoded); final lowerKeyMap = {for (final entry in map.entries) entry.key.toLowerCase(): entry.value}; final text = lowerKeyMap['transcription'] ?? lowerKeyMap['data'] ?? lowerKeyMap['text'] ?? lowerKeyMap['result']; if (text is Map) { return _extractTranscriptionText(jsonEncode(text)); } if (text != null) return text.toString().trim(); } } catch (_) {} return trimmedRaw; } String _generateSessionId() { final rand = Random(); final bytes = List.generate(16, (_) => rand.nextInt(256)); bytes[6] = (bytes[6] & 0x0F) | 0x40; bytes[8] = (bytes[8] & 0x3F) | 0x80; String byteHex(int i) => bytes[i].toRadixString(16).padLeft(2, '0'); final hex = List.generate(16, byteHex).join(); return '${hex.substring(0, 8)}-${hex.substring(8, 12)}-${hex.substring(12, 16)}-${hex.substring(16, 20)}-${hex.substring(20, 32)}'; } Future _consumeStream(dynamic streamedResponse, CopilotMessage assistantMsg, CopilotMessage? humanAudioMsg) async { if (streamedResponse.statusCode < 200 || streamedResponse.statusCode >= 300) { _onStreamError(assistantMsg, "Server error ${streamedResponse.statusCode}"); return; } String buffer = ''; _streamSub = streamedResponse.stream.transform(utf8.decoder).listen( (rawChunk) { buffer += rawChunk; while (buffer.contains('\n\n')) { final idx = buffer.indexOf('\n\n'); final rawEvent = buffer.substring(0, idx); buffer = buffer.substring(idx + 2); _handleSseEvent(rawEvent, assistantMsg, humanAudioMsg); } }, onDone: () { if (buffer.trim().isNotEmpty) { _handleSseEvent(buffer, assistantMsg, humanAudioMsg); } assistantMsg.isStreaming = false; isStreaming = false; notifyListeners(); }, onError: (e) => _onStreamError(assistantMsg, e), cancelOnError: true, ); } void _handleSseEvent(String rawEvent, CopilotMessage assistantMsg, CopilotMessage? humanAudioMsg) { final dataLines = rawEvent.split('\n').where((line) => line.startsWith('data:')).map((line) => line.substring(5).trim()).toList(); if (dataLines.isEmpty) return; final payload = dataLines.join('\n'); if (payload == '[DONE]') { assistantMsg.isStreaming = false; isStreaming = false; notifyListeners(); return; } try { final json = jsonDecode(payload); final event = CopilotStreamEvent.fromJson(json); if (event.type == 'response' && event.content != null) { assistantMsg.content = event.content!.answer ?? ''; assistantMsg.documentAnswer = event.content!.documentAnswer; assistantMsg.websiteAnswer = event.content!.websiteAnswer; assistantMsg.images = event.content!.images; } else if (event.type == 'error') { _onStreamError(assistantMsg, event.content?.answer ?? 'Something went wrong'); return; } if (event.type == 'transcription' && event.transcriptionContent != null) { humanAudioMsg?.content = event.transcriptionContent ?? ''; humanAudioMsg?.localAudioPath = null; } notifyListeners(); } catch (_) {} } void _onStreamError(CopilotMessage assistantMsg, Object e) { assistantMsg.isStreaming = false; assistantMsg.isError = true; if (assistantMsg.content.isEmpty) { assistantMsg.content = "Something went wrong. Please try again."; } isStreaming = false; errorMessage = "Failed to get a response"; notifyListeners(); } void cancelStreaming() { _streamSub?.cancel(); isStreaming = false; if (messages.isNotEmpty && messages.last.role == CopilotRole.assistant) { messages.last.isStreaming = false; } } Future connectPushToTalkHub() async { if (_pttHub != null && _pttHub!.state == HubConnectionState.Connected) { _pttLog('connectPushToTalkHub: already connected, skipping'); return; } await disconnectPushToTalkHub(); // final token = URLs.chatApiKey; final token = ApiManager.instance.user?.token ?? ''; final userId = ApiManager.instance.user?.id ?? ''; // final url = "${URLs.copilotHubUrl}?access_token=$token"; final url = "https://atomsmuat.hmg.com/VoiceWebSocket?access_token=$token"; // final url = "${URLs.copilotHubUrl}?id=$userId&access_token=$token"; _pttLog('connectPushToTalkHub: building connection url=$url'); final httpOp = HttpConnectionOptions(skipNegotiation: false, logMessageContent: true,headers: MessageHeaders()..setHeaderValue('Authorization', 'Bearer $token')); _pttHub = HubConnectionBuilder().withUrl(url,transportType:HttpTransportType.LongPolling ).withAutomaticReconnect(retryDelays: [2000, 5000, 10000, 20000]).build(); _pttHub!.on("RecordingStarted", _onRecordingStarted); _pttHub!.on("RecordingStopped", _onRecordingStopped); _pttHub!.on("RecordingCancelled", _onRecordingCancelled); _pttHub!.on("TranscriptionReceived", _onTranscriptionReceived); _pttHub!.on("ResponseReceived", _onResponseReceived); _pttHub!.on("AudioReceived", _onAudioReceived); _pttHub!.on("RecordingError", _onRecordingError); try { await _pttHub!.start(); _pttLog('connectPushToTalkHub: connected, state=${_pttHub!.state}'); } catch (e) { _pttLog('connectPushToTalkHub: failed error=$e'); pttErrorMessage = "Failed to connect to push-to-talk service"; pttStatus = PttStatus.error; _pttHub = null; notifyListeners(); rethrow; } } Future disconnectPushToTalkHub() async { _pttLog('disconnectPushToTalkHub: stopping'); try { await _abortMicStreaming(); if (_pttHub != null) { await _pttHub!.stop(); } } catch (e) { _pttLog('disconnectPushToTalkHub: error=$e'); } finally { _pttHub = null; pttStatus = PttStatus.idle; } } void startNewPttConversation() { pttSessionId = null; pttMessages = []; pttErrorMessage = null; pttStatus = PttStatus.idle; notifyListeners(); } Future beginPushToTalk(String language) async { if (pttStatus != PttStatus.idle && pttStatus != PttStatus.error) return; pttSessionId ??= _generateSessionId(); _pttButtonHeld = true; pttErrorMessage = null; pttStatus = PttStatus.connecting; notifyListeners(); try { if (_pttHub == null || _pttHub!.state != HubConnectionState.Connected) { await connectPushToTalkHub(); } final args = [ // pttSessionId ?? '', sessionId ?? '', ApiManager.instance.user?.id ?? '', (ApiManager.instance.assetGroup?.id ?? '').toString(), // language, "1", false, ]; _pttLog('beginPushToTalk: invoking StartRecording args=$args'); await _pttHub!.invoke("StartRecording", args: args); _pttLog('beginPushToTalk: StartRecording invoked, waiting for RecordingStarted event'); } catch (e) { _pttLog('beginPushToTalk: failed error=$e'); pttStatus = PttStatus.error; pttErrorMessage = "Failed to start recording"; _pttButtonHeld = false; notifyListeners(); } } Future endPushToTalk() async { _pttButtonHeld = false; if (pttStatus != PttStatus.recording) { notifyListeners(); return; } _pttLog('endPushToTalk: stopping mic and flushing $_pttChunkCount chunks sent so far'); try { await _stopMicStreamingAndFlush(); pttStatus = PttStatus.thinking; notifyListeners(); _pttLog('endPushToTalk: invoking StopRecording'); await _pttHub?.invoke("StopRecording"); } catch (e) { _pttLog('endPushToTalk: failed error=$e'); pttStatus = PttStatus.error; pttErrorMessage = "Failed to stop recording"; notifyListeners(); } } Future cancelPushToTalk() async { _pttButtonHeld = false; _pttLog('cancelPushToTalk: invoking CancelRecording'); try { await _abortMicStreaming(); await _pttHub?.invoke("CancelRecording"); } catch (e) { _pttLog('cancelPushToTalk: error=$e'); } pttStatus = PttStatus.idle; notifyListeners(); } Future _startMicStreaming() async { final micStatus = await Permission.microphone.request(); if (!micStatus.isGranted) { _pttLog('_startMicStreaming: microphone permission denied'); pttStatus = PttStatus.error; pttErrorMessage = "Microphone permission denied"; notifyListeners(); await cancelPushToTalk(); return; } if (!_pttRecorderOpen) { await _pttRecorder.openRecorder(); _pttRecorderOpen = true; } await _pttRecorder.setSubscriptionDuration(const Duration(milliseconds: 100)); _pttMicStreamController = StreamController(); _pttSendQueue = Future.value(); _pttChunkCount = 0; _pttMicSub = _pttMicStreamController!.stream.listen((chunk) { _pttChunkCount++; _pttLog('mic chunk #$_pttChunkCount captured bytes=${chunk.length}'); _enqueueChunkSend(chunk); }); await _pttRecorder.startRecorder( toStream: _pttMicStreamController!.sink, codec: sound.Codec.pcm16, numChannels: 1, sampleRate: 48000, ); _pttLog('_startMicStreaming: recorder started'); pttStatus = PttStatus.recording; notifyListeners(); } Future _stopMicStreamingAndFlush() async { try { if (_pttRecorderOpen) { await _pttRecorder.stopRecorder(); } } catch (e) { _pttLog('_stopMicStreamingAndFlush: stopRecorder error=$e'); } await Future.delayed(const Duration(milliseconds: 50)); await _pttMicSub?.cancel(); _pttMicSub = null; await _pttMicStreamController?.close(); _pttMicStreamController = null; await _pttSendQueue; _pttLog('_stopMicStreamingAndFlush: done, total chunks sent=$_pttChunkCount'); } Future _abortMicStreaming() async { try { if (_pttRecorderOpen) { await _pttRecorder.stopRecorder(); } } catch (e) { _pttLog('_abortMicStreaming: stopRecorder error=$e'); } await _pttMicSub?.cancel(); _pttMicSub = null; await _pttMicStreamController?.close(); _pttMicStreamController = null; _pttSendQueue = Future.value(); } void _enqueueChunkSend(Uint8List chunk) { _pttSendQueue = _pttSendQueue.then((_) => _sendAudioChunk(chunk)); } Future _sendAudioChunk(Uint8List chunk) async { try { await _pttHub?.invoke("SendAudioChunk", args: [base64Encode(chunk)]); } catch (e) { _pttLog('_sendAudioChunk: failed error=$e'); } } void _onRecordingStarted(List? params) async { _pttLog('event RecordingStarted params=$params'); try { if (!_pttButtonHeld) { _pttLog('RecordingStarted received but button already released, cancelling'); try { await _pttHub?.invoke("CancelRecording"); } catch (_) {} pttStatus = PttStatus.idle; notifyListeners(); return; } await _startMicStreaming(); } catch (e) { _pttLog('_onRecordingStarted: failed error=$e'); pttStatus = PttStatus.error; pttErrorMessage = "Failed to start recording"; notifyListeners(); } } void _onRecordingStopped(List? params) { _pttLog('event RecordingStopped params=$params'); } void _onRecordingCancelled(List? params) { _pttLog('event RecordingCancelled params=$params'); pttStatus = PttStatus.idle; notifyListeners(); } void _onTranscriptionReceived(List? params) { _pttLog('event TranscriptionReceived params=$params'); final data = _firstArgAsMap(params); final text = data?['text']?.toString() ?? ''; if (text.isEmpty) return; pttMessages.add(CopilotMessage(id: UniqueKey().toString(), role: CopilotRole.user, content: text, timestamp: DateTime.now())); notifyListeners(); } void _onResponseReceived(List? params) { _pttLog('event ResponseReceived params=$params'); final data = _firstArgAsMap(params); final text = data?['voiceAnswer']?.toString() ?? ''; _pttCurrentAssistantMsg = CopilotMessage(id: UniqueKey().toString(), role: CopilotRole.assistant, content: text, timestamp: DateTime.now()); pttMessages.add(_pttCurrentAssistantMsg!); notifyListeners(); } void _onAudioReceived(List? params) { if (params == null || params.isEmpty || params.first == null) return; try { final bytes = base64Decode(params.first.toString()); _pttLog('event AudioReceived bytes=${bytes.length}'); _pttCurrentAssistantMsg?.ttsAudioClips.add(bytes); _pttAudioQueue.add(bytes); notifyListeners(); _playNextTtsClipIfIdle(); } catch (e) { _pttLog('_onAudioReceived: failed to decode error=$e'); } } void _onRecordingError(List? params) { final msg = (params != null && params.isNotEmpty) ? params.first?.toString() : null; _pttLog('event RecordingError message=$msg'); pttErrorMessage = msg ?? "Recording error occurred"; pttStatus = PttStatus.error; _abortMicStreaming(); notifyListeners(); } Map? _firstArgAsMap(List? params) { if (params == null || params.isEmpty || params.first == null) return null; final first = params.first; if (first is Map) return Map.from(first); try { final decoded = jsonDecode(jsonEncode(first)); if (decoded is Map) return Map.from(decoded); } catch (_) {} return null; } Future _playNextTtsClipIfIdle() async { if (_pttIsPlayingAudio) return; if (_pttAudioQueue.isEmpty) return; _pttIsPlayingAudio = true; pttStatus = PttStatus.playingAudio; notifyListeners(); while (_pttAudioQueue.isNotEmpty) { final clip = _pttAudioQueue.removeAt(0); final completer = Completer(); late StreamSubscription sub; sub = _pttAudioPlayer.onPlayerComplete.listen((_) { sub.cancel(); if (!completer.isCompleted) completer.complete(); }); try { await _pttAudioPlayer.play(audioplayers.BytesSource(clip, mimeType: 'audio/wav')); await completer.future; } catch (_) { sub.cancel(); } } _pttIsPlayingAudio = false; pttStatus = PttStatus.idle; notifyListeners(); } @override void dispose() { _streamSub?.cancel(); _abortMicStreaming(); if (_pttRecorderOpen) { _pttRecorder.closeRecorder(); } _pttAudioPlayer.dispose(); _pttHub?.stop(); super.dispose(); } }