Solian/lib/providers/message/helper.dart

109 lines
2.8 KiB
Dart
Raw Normal View History

2024-06-23 04:29:07 +00:00
import 'package:get/get.dart';
import 'package:solian/models/channel.dart';
import 'package:solian/models/message.dart';
import 'package:solian/models/pagination.dart';
import 'package:solian/providers/auth.dart';
import 'package:solian/providers/message/history.dart';
Future<MessageHistoryDb> createHistoryDb() async {
return await $FloorMessageHistoryDb
.databaseBuilder('messaging_data.dart')
.build();
}
extension MessageHistoryHelper on MessageHistoryDb {
receiveMessage(Message remote) async {
final entry = LocalMessage(
2024-06-23 04:29:07 +00:00
remote.id,
remote,
remote.channelId,
);
await localMessages.insert(entry);
return entry;
2024-06-23 04:29:07 +00:00
}
replaceMessage(Message remote) async {
final entry = LocalMessage(
remote.id,
remote,
remote.channelId,
);
await localMessages.update(entry);
return entry;
}
burnMessage(int id) async {
await localMessages.delete(id);
}
syncMessages(Channel channel, {String scope = 'global', breath = 10, offset = 0}) async {
final lastOne = await localMessages.findLastByChannel(channel.id);
final data = await _getRemoteMessages(
channel,
scope,
remainBreath: breath,
2024-06-23 10:03:46 +00:00
offset: offset,
onBrake: (items) {
return items.any((x) => x.id == lastOne?.id);
},
);
if (data != null) {
await localMessages.insertBulk(
data.$1.map((x) => LocalMessage(x.id, x, x.channelId)).toList(),
);
}
return data?.$2 ?? 0;
}
Future<(List<Message>, int)?> _getRemoteMessages(
Channel channel,
String scope, {
required int remainBreath,
bool Function(List<Message> items)? onBrake,
take = 10,
offset = 0,
}) async {
if (remainBreath <= 0) {
return null;
}
2024-06-23 04:29:07 +00:00
final AuthProvider auth = Get.find();
if (!await auth.isAuthorized) return null;
2024-06-23 04:29:07 +00:00
final client = auth.configureClient('messaging');
final resp = await client.get(
'/api/channels/$scope/${channel.alias}/messages?take=$take&offset=$offset');
2024-06-23 04:29:07 +00:00
if (resp.statusCode != 200) {
throw Exception(resp.bodyString);
}
final PaginationResult response = PaginationResult.fromJson(resp.body);
final result =
response.data?.map((e) => Message.fromJson(e)).toList() ?? List.empty();
2024-06-23 04:29:07 +00:00
if (onBrake != null && onBrake(result)) {
return (result, response.count);
2024-06-23 04:29:07 +00:00
}
final expandResult = (await _getRemoteMessages(
channel,
scope,
remainBreath: remainBreath - 1,
take: take,
offset: offset + result.length,
))
?.$1 ??
List.empty();
return ([...result, ...expandResult], response.count);
2024-06-23 04:29:07 +00:00
}
Future<List<LocalMessage>> listMessages(Channel channel) async {
return await localMessages.findAllByChannel(channel.id);
}
}