Solian/lib/screens/channel/channel_chat.dart

398 lines
12 KiB
Dart
Raw Normal View History

2024-05-26 05:39:21 +00:00
import 'dart:async';
2024-06-02 14:45:54 +00:00
import 'dart:math' as math;
2024-05-26 05:39:21 +00:00
2024-05-25 17:21:08 +00:00
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:infinite_scroll_pagination/infinite_scroll_pagination.dart';
import 'package:solian/exts.dart';
2024-05-31 17:25:45 +00:00
import 'package:solian/models/call.dart';
2024-05-25 17:21:08 +00:00
import 'package:solian/models/channel.dart';
import 'package:solian/models/message.dart';
2024-05-26 05:39:21 +00:00
import 'package:solian/models/packet.dart';
2024-05-25 17:21:08 +00:00
import 'package:solian/models/pagination.dart';
import 'package:solian/providers/auth.dart';
2024-05-26 05:39:21 +00:00
import 'package:solian/providers/chat.dart';
2024-06-01 12:18:25 +00:00
import 'package:solian/providers/content/call.dart';
2024-05-25 17:21:08 +00:00
import 'package:solian/providers/content/channel.dart';
2024-05-26 15:13:43 +00:00
import 'package:solian/router.dart';
2024-05-25 17:21:08 +00:00
import 'package:solian/services.dart';
import 'package:solian/theme.dart';
2024-06-01 12:18:25 +00:00
import 'package:solian/widgets/chat/call/call_prejoin.dart';
2024-05-31 17:25:45 +00:00
import 'package:solian/widgets/chat/call/chat_call_action.dart';
2024-05-25 17:21:08 +00:00
import 'package:solian/widgets/chat/chat_message.dart';
import 'package:solian/widgets/chat/chat_message_action.dart';
2024-05-26 05:39:21 +00:00
import 'package:solian/widgets/chat/chat_message_input.dart';
2024-05-25 17:21:08 +00:00
class ChannelChatScreen extends StatefulWidget {
final String alias;
final String realm;
const ChannelChatScreen({
super.key,
required this.alias,
this.realm = 'global',
});
@override
State<ChannelChatScreen> createState() => _ChannelChatScreenState();
}
class _ChannelChatScreenState extends State<ChannelChatScreen> {
bool _isBusy = false;
2024-05-30 14:02:54 +00:00
int? _accountId;
2024-05-26 15:13:43 +00:00
String? _overrideAlias;
2024-05-25 17:21:08 +00:00
Channel? _channel;
2024-05-31 17:25:45 +00:00
Call? _ongoingCall;
2024-05-26 05:39:21 +00:00
StreamSubscription<NetworkPackage>? _subscription;
2024-05-25 17:21:08 +00:00
final PagingController<int, Message> _pagingController =
PagingController(firstPageKey: 0);
2024-05-30 14:02:54 +00:00
getProfile() async {
final AuthProvider auth = Get.find();
final prof = await auth.getProfile();
_accountId = prof.body['id'];
}
2024-05-26 15:13:43 +00:00
getChannel({String? overrideAlias}) async {
2024-05-25 17:21:08 +00:00
final ChannelProvider provider = Get.find();
setState(() => _isBusy = true);
2024-05-26 15:13:43 +00:00
if (overrideAlias != null) {
_overrideAlias = overrideAlias;
}
2024-05-25 17:21:08 +00:00
try {
2024-05-26 15:13:43 +00:00
final resp = await provider.getChannel(
_overrideAlias ?? widget.alias,
realm: widget.realm,
);
2024-05-25 17:21:08 +00:00
setState(() => _channel = Channel.fromJson(resp.body));
} catch (e) {
context.showErrorDialog(e);
}
setState(() => _isBusy = false);
}
2024-05-31 17:25:45 +00:00
getOngoingCall() async {
final ChannelProvider provider = Get.find();
setState(() => _isBusy = true);
try {
final resp = await provider.getChannelOngoingCall(
_overrideAlias ?? widget.alias,
realm: widget.realm,
);
if (resp != null) {
setState(() => _ongoingCall = Call.fromJson(resp.body));
}
} catch (e) {
context.showErrorDialog(e);
}
setState(() => _isBusy = false);
}
2024-05-25 17:21:08 +00:00
Future<void> getMessages(int pageKey) async {
final AuthProvider auth = Get.find();
if (!await auth.isAuthorized) return;
2024-05-26 05:39:21 +00:00
final client = GetConnect(maxAuthRetries: 3);
2024-05-25 17:21:08 +00:00
client.httpClient.baseUrl = ServiceFinder.services['messaging'];
client.httpClient.addAuthenticator(auth.requestAuthenticator);
final resp = await client.get(
'/api/channels/${widget.realm}/${widget.alias}/messages?take=10&offset=$pageKey');
if (resp.statusCode == 200) {
final PaginationResult result = PaginationResult.fromJson(resp.body);
final parsed = result.data?.map((e) => Message.fromJson(e)).toList();
if (parsed != null && parsed.length >= 10) {
_pagingController.appendPage(parsed, pageKey + parsed.length);
} else if (parsed != null) {
_pagingController.appendLastPage(parsed);
}
} else if (resp.statusCode == 403) {
_pagingController.appendLastPage([]);
} else {
_pagingController.error = resp.bodyString;
}
}
2024-05-26 05:39:21 +00:00
void listenMessages() {
final ChatProvider provider = Get.find();
_subscription = provider.stream.stream.listen((event) {
switch (event.method) {
case 'messages.new':
final payload = Message.fromJson(event.payload!);
if (payload.channelId == _channel?.id) {
final idx = _pagingController.itemList
?.indexWhere((e) => e.uuid == payload.uuid);
if ((idx ?? -1) >= 0) {
_pagingController.itemList?[idx!] = payload;
} else {
_pagingController.itemList?.insert(0, payload);
}
}
break;
case 'messages.update':
final payload = Message.fromJson(event.payload!);
if (payload.channelId == _channel?.id) {
final idx = _pagingController.itemList
?.indexWhere((x) => x.uuid == payload.uuid);
if (idx != null) {
_pagingController.itemList?[idx] = payload;
}
2024-05-26 05:39:21 +00:00
}
break;
case 'messages.burnt':
final payload = Message.fromJson(event.payload!);
if (payload.channelId == _channel?.id) {
final idx = _pagingController.itemList
?.indexWhere((x) => x.uuid != payload.uuid);
if (idx != null) {
_pagingController.itemList?.removeAt(idx - 1);
}
2024-05-26 05:39:21 +00:00
}
break;
2024-05-31 17:25:45 +00:00
case 'calls.new':
final payload = Call.fromJson(event.payload!);
_ongoingCall = payload;
break;
case 'calls.end':
_ongoingCall = null;
break;
2024-05-26 05:39:21 +00:00
}
setState(() {});
});
}
2024-05-25 17:21:08 +00:00
bool checkMessageMergeable(Message? a, Message? b) {
if (a?.replyTo != null) return false;
if (a == null || b == null) return false;
2024-05-26 05:39:21 +00:00
if (a.sender.account.id != b.sender.account.id) return false;
2024-05-25 17:21:08 +00:00
return a.createdAt.difference(b.createdAt).inMinutes <= 3;
}
2024-06-01 12:18:25 +00:00
void showCallPrejoin() {
showModalBottomSheet(
useRootNavigator: true,
context: context,
builder: (context) => ChatCallPrejoinPopup(
ongoingCall: _ongoingCall!,
channel: _channel!,
),
);
}
Message? _messageToReplying;
Message? _messageToEditing;
2024-05-31 17:25:45 +00:00
Widget buildHistory(context, item, index) {
2024-05-25 17:21:08 +00:00
bool isMerged = false, hasMerged = false;
if (index > 0) {
hasMerged = checkMessageMergeable(
_pagingController.itemList?[index - 1],
item,
);
}
if (index + 1 < (_pagingController.itemList?.length ?? 0)) {
isMerged = checkMessageMergeable(
item,
_pagingController.itemList?[index + 1],
);
}
return InkWell(
child: Container(
child: ChatMessage(
2024-06-02 14:45:54 +00:00
key: Key('m${item.uuid}'),
2024-05-25 17:21:08 +00:00
item: item,
2024-05-26 05:39:21 +00:00
isMerged: isMerged,
).paddingOnly(
top: !isMerged ? 8 : 0,
bottom: !hasMerged ? 8 : 0,
2024-05-25 17:21:08 +00:00
),
),
onLongPress: () {
showModalBottomSheet(
useRootNavigator: true,
context: context,
builder: (context) => ChatMessageAction(
channel: _channel!,
realm: _channel!.realm,
item: item,
onEdit: () {
setState(() => _messageToEditing = item);
},
onReply: () {
setState(() => _messageToReplying = item);
},
),
);
},
2024-05-29 14:42:11 +00:00
);
2024-05-25 17:21:08 +00:00
}
@override
void initState() {
super.initState();
2024-05-30 14:02:54 +00:00
getProfile();
2024-05-25 17:21:08 +00:00
getChannel().then((_) {
2024-05-26 05:39:21 +00:00
listenMessages();
2024-05-25 17:21:08 +00:00
_pagingController.addPageRequestListener(getMessages);
});
2024-05-31 17:25:45 +00:00
getOngoingCall();
2024-05-25 17:21:08 +00:00
}
@override
Widget build(BuildContext context) {
2024-06-01 12:18:25 +00:00
if (_isBusy || _channel == null) {
2024-05-25 17:21:08 +00:00
return const Center(
child: CircularProgressIndicator(),
);
}
2024-05-30 14:02:54 +00:00
String title = _channel?.name ?? 'loading'.tr;
String? placeholder;
if (_channel?.type == 1) {
final otherside = _channel!.members!
.where((e) => e.account.externalId != _accountId)
.first;
title = otherside.account.nick;
placeholder = 'messageInputPlaceholder'.trParams(
{'channel': '@${otherside.account.name}'},
);
}
2024-06-01 12:18:25 +00:00
final ChatCallProvider call = Get.find();
2024-05-25 17:21:08 +00:00
return Scaffold(
appBar: AppBar(
2024-05-30 14:02:54 +00:00
title: Text(title),
2024-05-25 17:21:08 +00:00
centerTitle: false,
actions: [
2024-05-31 17:25:45 +00:00
Builder(builder: (context) {
if (_isBusy) return const SizedBox();
return ChatCallButton(
realm: _channel!.realm,
channel: _channel!,
ongoingCall: _ongoingCall,
);
}),
2024-05-25 17:21:08 +00:00
IconButton(
2024-05-26 15:13:43 +00:00
icon: const Icon(Icons.more_vert),
onPressed: () {
AppRouter.instance
.pushNamed(
'channelDetail',
pathParameters: {'alias': widget.alias},
queryParameters: {'realm': widget.realm},
extra: _channel,
)
.then((value) {
if (value == false) AppRouter.instance.pop();
if (value != null) {
final resp = Channel.fromJson(value as Map<String, dynamic>);
getChannel(overrideAlias: resp.alias);
}
});
},
2024-05-25 17:21:08 +00:00
),
SizedBox(
width: SolianTheme.isLargeScreen(context) ? 8 : 16,
),
],
),
2024-05-26 05:39:21 +00:00
body: Stack(
2024-05-25 17:21:08 +00:00
children: [
2024-05-26 05:39:21 +00:00
Column(
children: [
Expanded(
child: PagedListView<int, Message>(
reverse: true,
clipBehavior: Clip.none,
pagingController: _pagingController,
builderDelegate: PagedChildBuilderDelegate<Message>(
2024-05-31 17:25:45 +00:00
itemBuilder: buildHistory,
2024-05-26 05:39:21 +00:00
noItemsFoundIndicatorBuilder: (_) => Container(),
),
).paddingOnly(bottom: 64),
2024-05-25 17:21:08 +00:00
),
2024-05-26 05:39:21 +00:00
],
),
Positioned(
2024-06-02 14:45:54 +00:00
bottom: math.max(MediaQuery.of(context).padding.bottom, 16),
2024-05-26 05:39:21 +00:00
left: 16,
right: 16,
child: ChatMessageInput(
edit: _messageToEditing,
reply: _messageToReplying,
2024-05-26 05:39:21 +00:00
realm: widget.realm,
2024-05-30 14:02:54 +00:00
placeholder: placeholder,
2024-05-26 05:39:21 +00:00
channel: _channel!,
onSent: (Message item) {
setState(() {
_pagingController.itemList?.insert(0, item);
});
},
onReset: () {
setState(() {
_messageToReplying = null;
_messageToEditing = null;
});
},
2024-05-25 17:21:08 +00:00
),
),
2024-05-31 17:25:45 +00:00
if (_ongoingCall != null)
2024-06-01 12:18:25 +00:00
Positioned(
top: 0,
left: 0,
right: 0,
child: MaterialBanner(
padding: const EdgeInsets.only(left: 16, top: 4, bottom: 4),
leading: const Icon(Icons.call_received),
backgroundColor: Theme.of(context).colorScheme.surfaceContainer,
dividerColor: Colors.transparent,
content: Text('callOngoing'.tr),
actions: [
Obx(() {
if (call.current.value == null) {
return TextButton(
onPressed: showCallPrejoin,
child: Text('callJoin'.tr),
);
} else if (call.channel.value?.id == _channel?.id) {
return TextButton(
onPressed: () => call.gotoScreen(context),
child: Text('callResume'.tr),
);
} else {
return TextButton(
onPressed: null,
child: Text('callJoin'.tr),
);
}
})
],
),
2024-05-31 17:25:45 +00:00
),
2024-05-25 17:21:08 +00:00
],
),
);
}
2024-05-26 05:39:21 +00:00
@override
void dispose() {
_subscription?.cancel();
super.dispose();
}
2024-05-25 17:21:08 +00:00
}