- Added chat history persistence for active rooms with auto-cleanup on stream end. - Overhauled Settings page with user profile, theme color picker, and password change. - Added backend API for user password updates. - Integrated flutter_launcher_icons and updated app icon to 'H' logo. - Fixed 'Duplicate keys' bug in danmaku by using UniqueKey and filtering historical messages. - Updated version to 1.0.0-beta3.5 and author info.
71 lines
1.9 KiB
Dart
71 lines
1.9 KiB
Dart
import 'dart:async';
|
|
import 'dart:convert';
|
|
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) {
|
|
print("[WS ERROR] $err");
|
|
}, onDone: () {
|
|
print("[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();
|
|
}
|
|
}
|