Solian/lib/widgets/chat/maintainer.dart

87 lines
2.5 KiB
Dart
Raw Normal View History

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
2024-04-26 15:25:56 +00:00
import 'package:solian/models/channel.dart';
import 'package:solian/models/message.dart';
import 'package:solian/models/packet.dart';
import 'package:solian/providers/auth.dart';
import 'package:solian/providers/chat.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
class ChatMaintainer extends StatefulWidget {
final Widget child;
2024-04-26 15:25:56 +00:00
final Channel channel;
final Function(Message val) onInsertMessage;
final Function(Message val) onUpdateMessage;
final Function(Message val) onDeleteMessage;
const ChatMaintainer({
super.key,
required this.child,
2024-04-26 15:25:56 +00:00
required this.channel,
required this.onInsertMessage,
required this.onUpdateMessage,
required this.onDeleteMessage,
});
@override
State<ChatMaintainer> createState() => _ChatMaintainerState();
}
class _ChatMaintainerState extends State<ChatMaintainer> {
void connect() {
2024-04-25 13:33:53 +00:00
ScaffoldMessenger.of(context).clearSnackBars();
final notify = ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(AppLocalizations.of(context)!.connectingServer),
2024-04-24 15:19:26 +00:00
duration: const Duration(minutes: 1),
),
);
final auth = context.read<AuthProvider>();
final chat = context.read<ChatProvider>();
chat.connect(auth).then((snapshot) {
snapshot!.stream.listen(
(event) {
final result = NetworkPackage.fromJson(jsonDecode(event));
switch (result.method) {
case 'messages.new':
2024-04-26 15:25:56 +00:00
final payload = Message.fromJson(result.payload!);
if (payload.channelId == widget.channel.id) widget.onInsertMessage(payload);
break;
case 'messages.update':
2024-04-26 15:25:56 +00:00
final payload = Message.fromJson(result.payload!);
if (payload.channelId == widget.channel.id) widget.onUpdateMessage(payload);
break;
case 'messages.burnt':
2024-04-26 15:25:56 +00:00
final payload = Message.fromJson(result.payload!);
if (payload.channelId == widget.channel.id) widget.onDeleteMessage(payload);
break;
}
},
onError: (_, __) => connect(),
2024-04-24 15:19:26 +00:00
onDone: () => connect(),
);
notify.close();
});
}
@override
void initState() {
Future.delayed(Duration.zero, () {
connect();
});
super.initState();
}
@override
Widget build(BuildContext context) {
return widget.child;
}
}