Files
Hightube/frontend/lib/services/chat_service.dart

91 lines
2.1 KiB
Dart

import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
class ChatMessage {
final String type;
final String username;
final String content;
final String roomId;
final bool isHistory;
ChatMessage({
required this.type,
required this.username,
required this.content,
required this.roomId,
this.isHistory = false,
});
factory ChatMessage.fromJson(Map<String, dynamic> json) {
return ChatMessage(
type: json['type'] ?? 'chat',
username: json['username'] ?? 'Anonymous',
content: json['content'] ?? '',
roomId: json['room_id'] ?? '',
isHistory: json['is_history'] ?? false,
);
}
Map<String, dynamic> toJson() => {
'type': type,
'username': username,
'content': content,
'room_id': roomId,
'is_history': isHistory,
};
}
class ChatService {
WebSocketChannel? _channel;
final StreamController<ChatMessage> _messageController =
StreamController<ChatMessage>.broadcast();
Stream<ChatMessage> get messages => _messageController.stream;
void connect(String baseUrl, String roomId, String username) {
final wsUri = Uri.parse(baseUrl).replace(
scheme: 'ws',
path: '/api/ws/room/$roomId',
queryParameters: {'username': username},
);
_channel = WebSocketChannel.connect(wsUri);
_channel!.stream.listen(
(data) {
final json = jsonDecode(data);
_messageController.add(ChatMessage.fromJson(json));
},
onError: (err) {
debugPrint("[WS ERROR] $err");
},
onDone: () {
debugPrint("[WS DONE] Connection closed");
},
);
}
void sendMessage(
String content,
String username,
String roomId, {
String type = 'chat',
}) {
if (_channel != null) {
final msg = ChatMessage(
type: type,
username: username,
content: content,
roomId: roomId,
);
_channel!.sink.add(jsonEncode(msg.toJson()));
}
}
void dispose() {
_channel?.sink.close();
_messageController.close();
}
}