Отображение чатов
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
import 'dart:async';
|
||||
import 'package:signalr_netcore/signalr_client.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import '../../features/chat/domain/entities/message.dart';
|
||||
|
||||
class SignalRService {
|
||||
final SharedPreferences prefs;
|
||||
HubConnection? _hubConnection;
|
||||
final _messageController = StreamController<Message>.broadcast();
|
||||
|
||||
Stream<Message> get messages => _messageController.stream;
|
||||
|
||||
SignalRService(this.prefs);
|
||||
|
||||
Future<void> init() async {
|
||||
final apiUrl = prefs.getString('api_url') ?? 'https://api.messenger.app';
|
||||
final token = prefs.getString('access_token');
|
||||
|
||||
if (token == null) return;
|
||||
|
||||
final hubUrl = '${apiUrl.replaceAll(RegExp(r'/+$'), '')}/hubs/chat';
|
||||
|
||||
_hubConnection = HubConnectionBuilder()
|
||||
.withUrl(hubUrl, options: HttpConnectionOptions(
|
||||
accessTokenFactory: () async => token,
|
||||
// logging: (level, message) => print('[SignalR] $level: $message'),
|
||||
))
|
||||
.withAutomaticReconnect()
|
||||
.build();
|
||||
|
||||
_hubConnection?.onclose(({error}) {
|
||||
// print('[SignalR] Connection closed: $error');
|
||||
});
|
||||
|
||||
_hubConnection?.on('ReceiveMessage', _handleReceiveMessage);
|
||||
|
||||
try {
|
||||
await _hubConnection?.start();
|
||||
// print('[SignalR] Connection started');
|
||||
} catch (e) {
|
||||
// print('[SignalR] Error starting connection: $e');
|
||||
}
|
||||
}
|
||||
|
||||
void _handleReceiveMessage(List<dynamic>? arguments) {
|
||||
if (arguments != null && arguments.isNotEmpty) {
|
||||
final data = arguments[0] as Map<String, dynamic>;
|
||||
// Map JSON to Message entity and add to stream
|
||||
// I'll need a Message.fromJson mapper
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> stop() async {
|
||||
await _hubConnection?.stop();
|
||||
_hubConnection = null;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user