local messages

This commit is contained in:
Christien Rioux 2023-08-07 00:55:57 -04:00
parent 13ddb4f22c
commit c59828df90
12 changed files with 375 additions and 201 deletions

View file

@ -99,6 +99,7 @@
"invitation": "Invitation" "invitation": "Invitation"
}, },
"chat_list": { "chat_list": {
"search": "Search",
"start_a_conversation": "Start a conversation", "start_a_conversation": "Start a conversation",
"conversations": "Conversations", "conversations": "Conversations",
"groups": "Groups" "groups": "Groups"

View file

@ -1,3 +1,5 @@
import 'dart:async';
import 'package:fast_immutable_collections/fast_immutable_collections.dart'; import 'package:fast_immutable_collections/fast_immutable_collections.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_chat_types/flutter_chat_types.dart' as types; import 'package:flutter_chat_types/flutter_chat_types.dart' as types;
@ -6,13 +8,22 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:uuid/uuid.dart'; import 'package:uuid/uuid.dart';
import '../../entities/proto.dart' as proto; import '../../entities/proto.dart' as proto;
import '../providers/chat.dart'; import '../entities/identity.dart';
import '../providers/contact.dart'; import '../providers/account.dart';
import '../providers/conversation.dart';
import '../tools/theme_service.dart'; import '../tools/theme_service.dart';
import 'empty_chat_widget.dart'; import '../veilid_support/veilid_support.dart';
class ChatComponent extends ConsumerStatefulWidget { class ChatComponent extends ConsumerStatefulWidget {
const ChatComponent({super.key}); const ChatComponent(
{required this.activeAccountInfo,
required this.activeChat,
required this.activeChatContact,
super.key});
final ActiveAccountInfo activeAccountInfo;
final TypedKey activeChat;
final proto.Contact activeChatContact;
@override @override
ChatComponentState createState() => ChatComponentState(); ChatComponentState createState() => ChatComponentState();
@ -21,11 +32,26 @@ class ChatComponent extends ConsumerStatefulWidget {
class ChatComponentState extends ConsumerState<ChatComponent> { class ChatComponentState extends ConsumerState<ChatComponent> {
List<types.Message> _messages = []; List<types.Message> _messages = [];
final _unfocusNode = FocusNode(); final _unfocusNode = FocusNode();
late final types.User _localUser;
late final types.User _remoteUser;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
_loadMessages();
_localUser = types.User(
id: widget.activeAccountInfo.localAccount.identityMaster
.identityPublicTypedKey()
.toString(),
firstName: widget.activeAccountInfo.account.profile.name,
);
_remoteUser = types.User(
id: proto.TypedKeyProto.fromProto(
widget.activeChatContact.identityPublicKey)
.toString(),
firstName: widget.activeChatContact.remoteProfile.name);
unawaited(_loadMessages());
} }
@override @override
@ -34,39 +60,76 @@ class ChatComponentState extends ConsumerState<ChatComponent> {
super.dispose(); super.dispose();
} }
void _loadMessages() { Future<void> _loadMessages() async {
final messages = <types.Message>[ final localConversationOwned = proto.OwnedDHTRecordPointerProto.fromProto(
types.TextMessage( widget.activeChatContact.localConversation);
id: "abcd", final remoteIdentityPublicKey = proto.TypedKeyProto.fromProto(
text: "Hello!", widget.activeChatContact.identityPublicKey);
author: types.User( final protoMessages = await getLocalConversationMessages(
id: "1234", activeAccountInfo: widget.activeAccountInfo,
firstName: "Foo", localConversationOwned: localConversationOwned,
lastName: "Bar", remoteIdentityPublicKey: remoteIdentityPublicKey);
role: types.Role.user)) if (protoMessages == null) {
]; return;
_messages = messages;
} }
final _user = const types.User(
id: '82091008-a484-4a89-ae75-a22bf8d6f3ac',
);
void _addMessage(types.Message message) {
setState(() { setState(() {
_messages = [];
for (final protoMessage in protoMessages) {
final message = protoMessageToMessage(protoMessage);
_messages.insert(0, message); _messages.insert(0, message);
}
}); });
} }
void _handleSendPressed(types.PartialText message) { types.Message protoMessageToMessage(proto.Message message) {
final isLocal = message.author ==
widget.activeAccountInfo.localAccount.identityMaster
.identityPublicTypedKey()
.toProto();
final textMessage = types.TextMessage( final textMessage = types.TextMessage(
author: _user, author: isLocal ? _localUser : _remoteUser,
createdAt: DateTime.now().millisecondsSinceEpoch, createdAt: DateTime.now().millisecondsSinceEpoch,
id: const Uuid().v4(), id: const Uuid().v4(),
text: message.text, text: message.text,
); );
return textMessage;
}
_addMessage(textMessage); Future<void> _addMessage(proto.Message protoMessage) async {
if (protoMessage.text.isEmpty) {
return;
}
final message = protoMessageToMessage(protoMessage);
setState(() {
_messages.insert(0, message);
});
// Now add the message to the conversation messages
final localConversationOwned = proto.OwnedDHTRecordPointerProto.fromProto(
widget.activeChatContact.localConversation);
final remoteIdentityPublicKey = proto.TypedKeyProto.fromProto(
widget.activeChatContact.identityPublicKey);
await addLocalConversationMessage(
activeAccountInfo: widget.activeAccountInfo,
localConversationOwned: localConversationOwned,
remoteIdentityPublicKey: remoteIdentityPublicKey,
message: protoMessage);
}
Future<void> _handleSendPressed(types.PartialText message) async {
final protoMessage = proto.Message()
..author = widget.activeAccountInfo.localAccount.identityMaster
.identityPublicTypedKey()
.toProto()
..timestamp = (await eventualVeilid.future).now().toInt64()
..text = message.text;
//..signature = signature;
await _addMessage(protoMessage);
} }
void _handleAttachmentPressed() { void _handleAttachmentPressed() {
@ -80,25 +143,7 @@ class ChatComponentState extends ConsumerState<ChatComponent> {
final scale = theme.extension<ScaleScheme>()!; final scale = theme.extension<ScaleScheme>()!;
final chatTheme = scale.toChatTheme(); final chatTheme = scale.toChatTheme();
final textTheme = Theme.of(context).textTheme; final textTheme = Theme.of(context).textTheme;
final contactName = widget.activeChatContact.editedProfile.name;
final contactList = ref.watch(fetchContactListProvider).asData?.value ??
const IListConst([]);
final activeChat = ref.watch(activeChatStateProvider).asData?.value;
if (activeChat == null) {
return const EmptyChatWidget();
}
final activeChatContactIdx = contactList.indexWhere(
(c) =>
proto.TypedKeyProto.fromProto(c.remoteConversationKey) == activeChat,
);
if (activeChatContactIdx == -1) {
activeChatState.add(null);
return const EmptyChatWidget();
}
final activeChatContact = contactList[activeChatContactIdx];
return DefaultTextStyle( return DefaultTextStyle(
style: textTheme.bodySmall!, style: textTheme.bodySmall!,
@ -118,7 +163,7 @@ class ChatComponentState extends ConsumerState<ChatComponent> {
child: Padding( child: Padding(
padding: padding:
const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 0), const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 0),
child: Text(activeChatContact.editedProfile.name, child: Text(contactName,
textAlign: TextAlign.start, textAlign: TextAlign.start,
style: textTheme.titleMedium), style: textTheme.titleMedium),
), ),
@ -134,10 +179,12 @@ class ChatComponentState extends ConsumerState<ChatComponent> {
//onMessageTap: _handleMessageTap, //onMessageTap: _handleMessageTap,
//onPreviewDataFetched: _handlePreviewDataFetched, //onPreviewDataFetched: _handlePreviewDataFetched,
onSendPressed: _handleSendPressed, onSendPressed: (message) {
unawaited(_handleSendPressed(message));
},
showUserAvatars: true, showUserAvatars: true,
showUserNames: true, showUserNames: true,
user: _user, user: _localUser,
), ),
), ),
), ),

View file

@ -1,92 +0,0 @@
import 'package:awesome_extensions/awesome_extensions.dart';
import 'package:fast_immutable_collections/fast_immutable_collections.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_translate/flutter_translate.dart';
import 'package:searchable_listview/searchable_listview.dart';
import '../../entities/proto.dart' as proto;
import '../tools/tools.dart';
import 'chat_single_contact_item_widget.dart';
import 'contact_item_widget.dart';
import 'empty_chat_list_widget.dart';
import 'empty_contact_list_widget.dart';
class ChatListWidget extends ConsumerWidget {
ChatListWidget(
{required IList<proto.Contact> contactList,
required this.chatList,
super.key})
: contactMap = IMap.fromIterable(contactList,
keyMapper: (c) => c.remoteConversationKey, valueMapper: (c) => c);
final IMap<proto.TypedKey, proto.Contact> contactMap;
final IList<proto.Chat> chatList;
@override
// ignore: prefer_expression_function_bodies
Widget build(BuildContext context, WidgetRef ref) {
final theme = Theme.of(context);
final textTheme = theme.textTheme;
final scale = theme.extension<ScaleScheme>()!;
return Container(
width: double.infinity,
constraints: const BoxConstraints(
minHeight: 64,
),
child: Column(children: [
Text(
'Chats',
style: textTheme.bodyLarge,
).paddingAll(8),
Container(
width: double.infinity,
decoration: ShapeDecoration(
color: scale.grayScale.appBackground,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
)),
child: (chatList.isEmpty)
? const EmptyChatListWidget().toCenter()
: SearchableList<proto.Chat>(
initialList: chatList.toList(),
builder: (c) {
final contact = contactMap[c.remoteConversationKey];
if (contact == null) {
return const Text('...');
}
return ChatSingleContactItemWidget(contact: contact);
},
filter: (value) {
final lowerValue = value.toLowerCase();
return chatList.where((c) {
final contact = contactMap[c.remoteConversationKey];
if (contact == null) {
return false;
}
return contact.editedProfile.name
.toLowerCase()
.contains(lowerValue) ||
contact.editedProfile.title
.toLowerCase()
.contains(lowerValue);
}).toList();
},
inputDecoration: InputDecoration(
labelText: translate('chat_list.search'),
fillColor: Colors.white,
focusedBorder: OutlineInputBorder(
borderSide: const BorderSide(
color: Colors.blue,
),
borderRadius: BorderRadius.circular(10),
),
),
),
).expanded()
]),
).paddingLTRB(8, 0, 8, 65);
}
}

View file

@ -74,9 +74,6 @@ class ChatSingleContactItemWidget extends ConsumerWidget {
activeChatState.add(proto.TypedKeyProto.fromProto( activeChatState.add(proto.TypedKeyProto.fromProto(
contact.remoteConversationKey)); contact.remoteConversationKey));
ref.invalidate(fetchChatListProvider); ref.invalidate(fetchChatListProvider);
// Click over to chats
await MainPager.of(context)?.pageController.animateToPage(1,
duration: 250.ms, curve: Curves.easeInOut);
}, },
title: Text(contact.editedProfile.name), title: Text(contact.editedProfile.name),

View file

@ -0,0 +1,80 @@
import 'package:awesome_extensions/awesome_extensions.dart';
import 'package:fast_immutable_collections/fast_immutable_collections.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_translate/flutter_translate.dart';
import 'package:searchable_listview/searchable_listview.dart';
import '../../entities/proto.dart' as proto;
import '../tools/tools.dart';
import 'chat_single_contact_item_widget.dart';
import 'contact_item_widget.dart';
import 'empty_chat_list_widget.dart';
import 'empty_contact_list_widget.dart';
class ChatSingleContactListWidget extends ConsumerWidget {
ChatSingleContactListWidget(
{required IList<proto.Contact> contactList,
required this.chatList,
super.key})
: contactMap = IMap.fromIterable(contactList,
keyMapper: (c) => c.remoteConversationKey, valueMapper: (c) => c);
final IMap<proto.TypedKey, proto.Contact> contactMap;
final IList<proto.Chat> chatList;
@override
// ignore: prefer_expression_function_bodies
Widget build(BuildContext context, WidgetRef ref) {
final theme = Theme.of(context);
final textTheme = theme.textTheme;
final scale = theme.extension<ScaleScheme>()!;
return Container(
width: double.infinity,
decoration: ShapeDecoration(
color: scale.grayScale.appBackground,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
)),
child: (chatList.isEmpty)
? const EmptyChatListWidget()
: SearchableList<proto.Chat>(
initialList: chatList.toList(),
builder: (c) {
final contact = contactMap[c.remoteConversationKey];
if (contact == null) {
return const Text('...');
}
return ChatSingleContactItemWidget(contact: contact);
},
filter: (value) {
final lowerValue = value.toLowerCase();
return chatList.where((c) {
final contact = contactMap[c.remoteConversationKey];
if (contact == null) {
return false;
}
return contact.editedProfile.name
.toLowerCase()
.contains(lowerValue) ||
contact.editedProfile.title
.toLowerCase()
.contains(lowerValue);
}).toList();
},
inputDecoration: InputDecoration(
labelText: translate('chat_list.search'),
fillColor: Colors.white,
focusedBorder: OutlineInputBorder(
borderSide: const BorderSide(
color: Colors.blue,
),
borderRadius: BorderRadius.circular(10),
),
),
),
).paddingLTRB(8, 8, 8, 65);
}
}

View file

@ -1,9 +1,11 @@
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_slidable/flutter_slidable.dart'; import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:flutter_translate/flutter_translate.dart'; import 'package:flutter_translate/flutter_translate.dart';
import '../../entities/proto.dart' as proto; import '../../entities/proto.dart' as proto;
import '../pages/main_pager/main_pager.dart';
import '../providers/account.dart'; import '../providers/account.dart';
import '../providers/chat.dart'; import '../providers/chat.dart';
import '../providers/contact.dart'; import '../providers/contact.dart';
@ -21,6 +23,9 @@ class ContactItemWidget extends ConsumerWidget {
final textTheme = theme.textTheme; final textTheme = theme.textTheme;
final scale = theme.extension<ScaleScheme>()!; final scale = theme.extension<ScaleScheme>()!;
final remoteConversationKey =
proto.TypedKeyProto.fromProto(contact.remoteConversationKey);
return Container( return Container(
margin: const EdgeInsets.fromLTRB(4, 4, 4, 0), margin: const EdgeInsets.fromLTRB(4, 4, 4, 0),
clipBehavior: Clip.antiAlias, clipBehavior: Clip.antiAlias,
@ -66,9 +71,19 @@ class ContactItemWidget extends ConsumerWidget {
// component is not dragged. // component is not dragged.
child: ListTile( child: ListTile(
onTap: () async { onTap: () async {
// final activeAccountInfo = final activeAccountInfo =
// await ref.read(fetchActiveAccountProvider.future); await ref.read(fetchActiveAccountProvider.future);
// if (activeAccountInfo != null) { if (activeAccountInfo != null) {
// Start a chat
await getOrCreateChatSingleContact(
activeAccountInfo: activeAccountInfo,
remoteConversationRecordKey: remoteConversationKey);
// Click over to chats
await MainPager.of(context)?.pageController.animateToPage(1,
duration: 250.ms, curve: Curves.easeInOut);
}
// // ignore: use_build_context_synchronously // // ignore: use_build_context_synchronously
// if (!context.mounted) { // if (!context.mounted) {
// return; // return;

View file

@ -30,6 +30,6 @@ class EmptyChatListWidget extends ConsumerWidget {
), ),
), ),
], ],
).expanded(); );
} }
} }

View file

@ -1,13 +1,17 @@
import 'dart:async'; import 'dart:async';
import 'package:fast_immutable_collections/fast_immutable_collections.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart'; import 'package:flutter_animate/flutter_animate.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:split_view/split_view.dart'; import 'package:split_view/split_view.dart';
import 'package:signal_strength_indicator/signal_strength_indicator.dart'; import 'package:signal_strength_indicator/signal_strength_indicator.dart';
import '../../entities/proto.dart' as proto;
import '../components/chat_component.dart'; import '../components/chat_component.dart';
import '../components/empty_chat_widget.dart';
import '../providers/account.dart'; import '../providers/account.dart';
import '../providers/chat.dart';
import '../providers/contact.dart'; import '../providers/contact.dart';
import '../providers/contact_invite.dart'; import '../providers/contact_invite.dart';
import '../providers/window_control.dart'; import '../providers/window_control.dart';
@ -24,6 +28,7 @@ class HomePage extends ConsumerStatefulWidget {
// XXX Eliminate this when we have ValueChanged // XXX Eliminate this when we have ValueChanged
const int ticksPerContactInvitationCheck = 5; const int ticksPerContactInvitationCheck = 5;
const int ticksPerNewMessageCheck = 5;
class HomePageState extends ConsumerState<HomePage> class HomePageState extends ConsumerState<HomePage>
with TickerProviderStateMixin { with TickerProviderStateMixin {
@ -32,6 +37,7 @@ class HomePageState extends ConsumerState<HomePage>
Timer? _homeTickTimer; Timer? _homeTickTimer;
bool _inHomeTick = false; bool _inHomeTick = false;
int _contactInvitationCheckTick = 0; int _contactInvitationCheckTick = 0;
int _newMessageCheckTick = 0;
@override @override
void initState() { void initState() {
@ -63,11 +69,22 @@ class HomePageState extends ConsumerState<HomePage>
Future<void> _onHomeTick() async { Future<void> _onHomeTick() async {
_inHomeTick = true; _inHomeTick = true;
try { try {
// Check extant contact invitations once every 5 seconds final unord = <Future<void>>[];
// Check extant contact invitations once every N seconds
_contactInvitationCheckTick += 1; _contactInvitationCheckTick += 1;
if (_contactInvitationCheckTick >= ticksPerContactInvitationCheck) { if (_contactInvitationCheckTick >= ticksPerContactInvitationCheck) {
_contactInvitationCheckTick = 0; _contactInvitationCheckTick = 0;
await _doContactInvitationCheck(); unord.add(_doContactInvitationCheck());
}
// Check new messages once every N seconds
_newMessageCheckTick += 1;
if (_newMessageCheckTick >= ticksPerNewMessageCheck) {
_newMessageCheckTick = 0;
unord.add(_doNewMessageCheck());
}
if (unord.isNotEmpty) {
await Future.wait(unord);
} }
} finally { } finally {
_inHomeTick = false; _inHomeTick = false;
@ -112,6 +129,26 @@ class HomePageState extends ConsumerState<HomePage>
await Future.wait(allChecks); await Future.wait(allChecks);
} }
Future<void> _doNewMessageCheck() async {
final activeChat = activeChatState.currentState;
if (activeChat == null) {
return;
}
final contactList = ref.read(fetchContactListProvider).asData?.value ??
const IListConst([]);
final activeChatContactIdx = contactList.indexWhere(
(c) =>
proto.TypedKeyProto.fromProto(c.remoteConversationKey) == activeChat,
);
if (activeChatContactIdx == -1) {
return;
}
final activeChatContact = contactList[activeChatContactIdx];
//activeChatContact.rem
}
// ignore: prefer_expression_function_bodies // ignore: prefer_expression_function_bodies
Widget buildPhone(BuildContext context) { Widget buildPhone(BuildContext context) {
// //
@ -129,7 +166,38 @@ class HomePageState extends ConsumerState<HomePage>
// ignore: prefer_expression_function_bodies // ignore: prefer_expression_function_bodies
Widget buildTabletRightPane(BuildContext context) { Widget buildTabletRightPane(BuildContext context) {
// //
return ChatComponent(); return buildChatComponent(context);
}
Widget buildChatComponent(BuildContext context) {
final contactList = ref.watch(fetchContactListProvider).asData?.value ??
const IListConst([]);
final activeChat = ref.watch(activeChatStateProvider).asData?.value;
if (activeChat == null) {
return const EmptyChatWidget();
}
final activeAccountInfo =
ref.watch(fetchActiveAccountProvider).asData?.value;
if (activeAccountInfo == null) {
return const EmptyChatWidget();
}
final activeChatContactIdx = contactList.indexWhere(
(c) =>
proto.TypedKeyProto.fromProto(c.remoteConversationKey) == activeChat,
);
if (activeChatContactIdx == -1) {
activeChatState.add(null);
return const EmptyChatWidget();
}
final activeChatContact = contactList[activeChatContactIdx];
return ChatComponent(
activeAccountInfo: activeAccountInfo,
activeChat: activeChat,
activeChatContact: activeChatContact);
} }
// ignore: prefer_expression_function_bodies // ignore: prefer_expression_function_bodies

View file

@ -1,9 +1,10 @@
import 'package:awesome_extensions/awesome_extensions.dart';
import 'package:fast_immutable_collections/fast_immutable_collections.dart'; import 'package:fast_immutable_collections/fast_immutable_collections.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_translate/flutter_translate.dart'; import 'package:flutter_translate/flutter_translate.dart';
import '../../components/chat_list_widget.dart'; import '../../components/chat_single_contact_list_widget.dart';
import '../../components/empty_chat_list_widget.dart'; import '../../components/empty_chat_list_widget.dart';
import '../../entities/local_account.dart'; import '../../entities/local_account.dart';
import '../../entities/proto.dart' as proto; import '../../entities/proto.dart' as proto;
@ -52,14 +53,10 @@ class ChatsPageState extends ConsumerState<ChatsPage> {
return Column(children: <Widget>[ return Column(children: <Widget>[
if (chatList.isNotEmpty) if (chatList.isNotEmpty)
ExpansionTile( ChatSingleContactListWidget(
title: Text(translate('chat_page.conversations')), contactList: contactList, chatList: chatList)
initiallyExpanded: true, .expanded(),
children: [ if (chatList.isEmpty) const EmptyChatListWidget().expanded(),
ChatListWidget(contactList: contactList, chatList: chatList)
],
),
if (chatList.isEmpty) const EmptyChatListWidget(),
]); ]);
} }

View file

@ -73,6 +73,11 @@ Future<void> deleteChat(
final c = Chat.fromBuffer(cbuf); final c = Chat.fromBuffer(cbuf);
if (c.remoteConversationKey == remoteConversationKey) { if (c.remoteConversationKey == remoteConversationKey) {
await chatList.tryRemoveItem(i); await chatList.tryRemoveItem(i);
if (activeChatState.currentState == remoteConversationRecordKey) {
activeChatState.add(null);
}
return; return;
} }
} }

View file

@ -123,33 +123,85 @@ Future<Conversation?> writeLocalConversation({
}); });
} }
Future<Conversation?> readLocalConversation({
required ActiveAccountInfo activeAccountInfo,
required OwnedDHTRecordPointer localConversationOwned,
required TypedKey remoteIdentityPublicKey,
}) async {
final accountRecordKey =
activeAccountInfo.userLogin.accountRecordInfo.accountRecord.recordKey;
final pool = await DHTRecordPool.instance();
/// Get most recent messages for this conversation final crypto = await getConversationCrypto(
// @riverpod activeAccountInfo: activeAccountInfo,
// Future<IList<Message>?> fetchConversationMessages(FetchContactListRef ref) async { remoteIdentityPublicKey: remoteIdentityPublicKey);
// // See if we've logged into this account or if it is locked
// final activeAccountInfo = await ref.watch(fetchActiveAccountProvider.future);
// if (activeAccountInfo == null) {
// return null;
// }
// final accountRecordKey =
// activeAccountInfo.userLogin.accountRecordInfo.accountRecord.recordKey;
// // Decode the contact list from the DHT return (await pool.openOwned(localConversationOwned,
// IList<Contact> out = const IListConst([]); parent: accountRecordKey, crypto: crypto))
// await (await DHTShortArray.openOwned( .scope((localConversation) async {
// proto.OwnedDHTRecordPointerProto.fromProto( //
// activeAccountInfo.account.contactList), final update = await localConversation.getProtobuf(Conversation.fromBuffer);
// parent: accountRecordKey)) if (update != null) {
// .scope((cList) async { return update;
// for (var i = 0; i < cList.length; i++) { }
// final cir = await cList.getItem(i); return null;
// if (cir == null) { });
// throw Exception('Failed to get contact'); }
// }
// out = out.add(Contact.fromBuffer(cir));
// }
// });
// return out; Future<void> addLocalConversationMessage(
// } {required ActiveAccountInfo activeAccountInfo,
required OwnedDHTRecordPointer localConversationOwned,
required TypedKey remoteIdentityPublicKey,
required proto.Message message}) async {
final conversation = await readLocalConversation(
activeAccountInfo: activeAccountInfo,
localConversationOwned: localConversationOwned,
remoteIdentityPublicKey: remoteIdentityPublicKey);
if (conversation == null) {
return;
}
final messagesOwned =
proto.OwnedDHTRecordPointerProto.fromProto(conversation.messages);
final crypto = await getConversationCrypto(
activeAccountInfo: activeAccountInfo,
remoteIdentityPublicKey: remoteIdentityPublicKey);
await (await DHTShortArray.openOwned(messagesOwned,
parent: localConversationOwned.recordKey, crypto: crypto))
.scope((messages) async {
await messages.tryAddItem(message.writeToBuffer());
});
}
Future<IList<proto.Message>?> getLocalConversationMessages({
required ActiveAccountInfo activeAccountInfo,
required OwnedDHTRecordPointer localConversationOwned,
required TypedKey remoteIdentityPublicKey,
}) async {
final conversation = await readLocalConversation(
activeAccountInfo: activeAccountInfo,
localConversationOwned: localConversationOwned,
remoteIdentityPublicKey: remoteIdentityPublicKey);
if (conversation == null) {
return null;
}
final messagesOwned =
proto.OwnedDHTRecordPointerProto.fromProto(conversation.messages);
final crypto = await getConversationCrypto(
activeAccountInfo: activeAccountInfo,
remoteIdentityPublicKey: remoteIdentityPublicKey);
return (await DHTShortArray.openOwned(messagesOwned,
parent: localConversationOwned.recordKey, crypto: crypto))
.scope((messages) async {
var out = IList<proto.Message>();
for (var i = 0; i < messages.length; i++) {
final msg = await messages.getItemProtobuf(proto.Message.fromBuffer, i);
if (msg == null) {
throw Exception('Failed to get message');
}
out = out.add(msg);
}
return out;
});
}

View file

@ -72,8 +72,11 @@ class DHTRecordPool with AsyncTableDBBacked<DHTRecordPoolAllocations> {
Object? valueToJson(DHTRecordPoolAllocations val) => val.toJson(); Object? valueToJson(DHTRecordPoolAllocations val) => val.toJson();
////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////
static Mutex instanceSetupMutex = Mutex();
// ignore: prefer_expression_function_bodies
static Future<DHTRecordPool> instance() async { static Future<DHTRecordPool> instance() async {
return instanceSetupMutex.protect(() async {
if (_singleton == null) { if (_singleton == null) {
final veilid = await eventualVeilid.future; final veilid = await eventualVeilid.future;
final routingContext = (await veilid.routingContext()) final routingContext = (await veilid.routingContext())
@ -89,6 +92,7 @@ class DHTRecordPool with AsyncTableDBBacked<DHTRecordPoolAllocations> {
_singleton = globalPool; _singleton = globalPool;
} }
return _singleton!; return _singleton!;
});
} }
Veilid get veilid => _veilid; Veilid get veilid => _veilid;