veilidchat/lib/providers/conversation.dart

375 lines
13 KiB
Dart
Raw Normal View History

2023-08-05 23:59:15 -04:00
import 'dart:convert';
import 'package:fast_immutable_collections/fast_immutable_collections.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
2023-09-26 18:46:02 -04:00
import '../proto/proto.dart' as proto;
import '../proto/proto.dart' show Conversation, Message;
2023-08-05 23:59:15 -04:00
2023-09-26 22:32:13 -04:00
import '../tools/tools.dart';
2023-09-26 18:46:02 -04:00
import '../veilid_init.dart';
2023-08-05 23:59:15 -04:00
import '../veilid_support/veilid_support.dart';
import 'account.dart';
2023-08-09 02:33:31 -04:00
import 'chat.dart';
import 'contact.dart';
2023-08-05 23:59:15 -04:00
2023-08-09 02:33:31 -04:00
part 'conversation.g.dart';
2023-08-05 23:59:15 -04:00
Future<DHTRecordCrypto> getConversationCrypto({
required ActiveAccountInfo activeAccountInfo,
2023-08-06 15:33:40 -04:00
required TypedKey remoteIdentityPublicKey,
2023-08-05 23:59:15 -04:00
}) async {
final veilid = await eventualVeilid.future;
final identitySecret = activeAccountInfo.userLogin.identitySecret;
final cs = await veilid.getCryptoSystem(identitySecret.kind);
final sharedSecret =
await cs.cachedDH(remoteIdentityPublicKey.value, identitySecret.value);
return DHTRecordCryptoPrivate.fromSecret(identitySecret.kind, sharedSecret);
}
2023-08-07 11:02:29 -04:00
KeyPair getConversationWriter({
required ActiveAccountInfo activeAccountInfo,
}) {
final identityKey =
activeAccountInfo.localAccount.identityMaster.identityPublicKey;
final identitySecret = activeAccountInfo.userLogin.identitySecret;
return KeyPair(key: identityKey, secret: identitySecret.value);
}
2023-08-06 15:33:40 -04:00
// Create a conversation
// If we were the initator of the conversation there may be an
// incomplete 'existingConversationRecord' that we need to fill
// in now that we have the remote identity key
Future<T> createConversation<T>(
{required ActiveAccountInfo activeAccountInfo,
required TypedKey remoteIdentityPublicKey,
required FutureOr<T> Function(DHTRecord) callback,
2023-08-07 11:02:29 -04:00
TypedKey? existingConversationRecordKey}) async {
2023-08-06 15:33:40 -04:00
final pool = await DHTRecordPool.instance();
final accountRecordKey =
activeAccountInfo.userLogin.accountRecordInfo.accountRecord.recordKey;
final crypto = await getConversationCrypto(
activeAccountInfo: activeAccountInfo,
remoteIdentityPublicKey: remoteIdentityPublicKey);
2023-08-07 11:02:29 -04:00
final writer = getConversationWriter(activeAccountInfo: activeAccountInfo);
2023-08-06 15:33:40 -04:00
2023-08-07 11:02:29 -04:00
// Open with SMPL scheme for identity writer
2023-08-06 15:33:40 -04:00
late final DHTRecord localConversationRecord;
2023-08-07 11:02:29 -04:00
if (existingConversationRecordKey != null) {
localConversationRecord = await pool.openWrite(
existingConversationRecordKey, writer,
2023-08-06 15:33:40 -04:00
parent: accountRecordKey, crypto: crypto);
} else {
2023-08-07 11:02:29 -04:00
final localConversationRecordCreate = await pool.create(
parent: accountRecordKey,
crypto: crypto,
schema: DHTSchema.smpl(
oCnt: 0, members: [DHTSchemaMember(mKey: writer.key, mCnt: 1)]));
await localConversationRecordCreate.close();
localConversationRecord = await pool.openWrite(
localConversationRecordCreate.key, writer,
parent: accountRecordKey, crypto: crypto);
2023-08-06 15:33:40 -04:00
}
return localConversationRecord
// ignore: prefer_expression_function_bodies
.deleteScope((localConversation) async {
// Make messages log
return (await DHTShortArray.create(
2023-08-07 11:02:29 -04:00
parent: localConversation.key, crypto: crypto, smplWriter: writer))
2023-08-06 15:33:40 -04:00
.deleteScope((messages) async {
// Write local conversation key
final conversation = Conversation()
..profile = activeAccountInfo.account.profile
..identityMasterJson =
jsonEncode(activeAccountInfo.localAccount.identityMaster.toJson())
2023-08-07 11:02:29 -04:00
..messages = messages.record.key.toProto();
2023-08-06 15:33:40 -04:00
//
final update = await localConversation.tryWriteProtobuf(
Conversation.fromBuffer, conversation);
if (update != null) {
throw Exception('Failed to write local conversation');
}
return await callback(localConversation);
});
});
}
2023-08-05 23:59:15 -04:00
Future<Conversation?> readRemoteConversation({
required ActiveAccountInfo activeAccountInfo,
2023-08-07 11:02:29 -04:00
required TypedKey remoteConversationRecordKey,
2023-08-06 15:33:40 -04:00
required TypedKey remoteIdentityPublicKey,
2023-08-05 23:59:15 -04:00
}) async {
final accountRecordKey =
activeAccountInfo.userLogin.accountRecordInfo.accountRecord.recordKey;
final pool = await DHTRecordPool.instance();
2023-08-06 15:33:40 -04:00
final crypto = await getConversationCrypto(
activeAccountInfo: activeAccountInfo,
remoteIdentityPublicKey: remoteIdentityPublicKey);
2023-08-07 11:02:29 -04:00
return (await pool.openRead(remoteConversationRecordKey,
2023-08-06 15:33:40 -04:00
parent: accountRecordKey, crypto: crypto))
2023-08-05 23:59:15 -04:00
.scope((remoteConversation) async {
//
final conversation =
await remoteConversation.getProtobuf(Conversation.fromBuffer);
return conversation;
});
}
Future<Conversation?> writeLocalConversation({
required ActiveAccountInfo activeAccountInfo,
2023-08-07 11:02:29 -04:00
required TypedKey localConversationRecordKey,
2023-08-06 15:33:40 -04:00
required TypedKey remoteIdentityPublicKey,
2023-08-05 23:59:15 -04:00
required Conversation conversation,
}) async {
final accountRecordKey =
activeAccountInfo.userLogin.accountRecordInfo.accountRecord.recordKey;
final pool = await DHTRecordPool.instance();
2023-08-06 15:33:40 -04:00
final crypto = await getConversationCrypto(
activeAccountInfo: activeAccountInfo,
remoteIdentityPublicKey: remoteIdentityPublicKey);
2023-08-07 11:02:29 -04:00
final writer = getConversationWriter(activeAccountInfo: activeAccountInfo);
2023-08-06 15:33:40 -04:00
2023-08-07 11:02:29 -04:00
return (await pool.openWrite(localConversationRecordKey, writer,
2023-08-06 15:33:40 -04:00
parent: accountRecordKey, crypto: crypto))
2023-08-05 23:59:15 -04:00
.scope((localConversation) async {
//
final update = await localConversation.tryWriteProtobuf(
Conversation.fromBuffer, conversation);
if (update != null) {
return update;
}
return null;
});
}
2023-08-07 00:55:57 -04:00
Future<Conversation?> readLocalConversation({
required ActiveAccountInfo activeAccountInfo,
2023-08-07 11:02:29 -04:00
required TypedKey localConversationRecordKey,
2023-08-07 00:55:57 -04:00
required TypedKey remoteIdentityPublicKey,
}) async {
final accountRecordKey =
activeAccountInfo.userLogin.accountRecordInfo.accountRecord.recordKey;
final pool = await DHTRecordPool.instance();
final crypto = await getConversationCrypto(
activeAccountInfo: activeAccountInfo,
remoteIdentityPublicKey: remoteIdentityPublicKey);
2023-08-07 11:02:29 -04:00
return (await pool.openRead(localConversationRecordKey,
2023-08-07 00:55:57 -04:00
parent: accountRecordKey, crypto: crypto))
.scope((localConversation) async {
//
final update = await localConversation.getProtobuf(Conversation.fromBuffer);
if (update != null) {
return update;
}
return null;
});
}
Future<void> addLocalConversationMessage(
{required ActiveAccountInfo activeAccountInfo,
2023-08-07 11:02:29 -04:00
required TypedKey localConversationRecordKey,
2023-08-07 00:55:57 -04:00
required TypedKey remoteIdentityPublicKey,
2023-08-09 02:33:31 -04:00
required Message message}) async {
2023-08-07 00:55:57 -04:00
final conversation = await readLocalConversation(
activeAccountInfo: activeAccountInfo,
2023-08-07 11:02:29 -04:00
localConversationRecordKey: localConversationRecordKey,
2023-08-07 00:55:57 -04:00
remoteIdentityPublicKey: remoteIdentityPublicKey);
if (conversation == null) {
return;
}
2023-08-07 11:02:29 -04:00
final messagesRecordKey =
proto.TypedKeyProto.fromProto(conversation.messages);
2023-08-07 00:55:57 -04:00
final crypto = await getConversationCrypto(
activeAccountInfo: activeAccountInfo,
remoteIdentityPublicKey: remoteIdentityPublicKey);
2023-08-07 11:02:29 -04:00
final writer = getConversationWriter(activeAccountInfo: activeAccountInfo);
2023-08-05 23:59:15 -04:00
2023-08-07 11:02:29 -04:00
await (await DHTShortArray.openWrite(messagesRecordKey, writer,
parent: localConversationRecordKey, crypto: crypto))
2023-08-07 00:55:57 -04:00
.scope((messages) async {
await messages.tryAddItem(message.writeToBuffer());
});
}
2023-08-08 02:03:26 -04:00
Future<bool> mergeLocalConversationMessages(
{required ActiveAccountInfo activeAccountInfo,
required TypedKey localConversationRecordKey,
required TypedKey remoteIdentityPublicKey,
2023-08-09 02:33:31 -04:00
required IList<Message> newMessages}) async {
2023-08-08 02:03:26 -04:00
final conversation = await readLocalConversation(
activeAccountInfo: activeAccountInfo,
localConversationRecordKey: localConversationRecordKey,
remoteIdentityPublicKey: remoteIdentityPublicKey);
if (conversation == null) {
return false;
}
2023-08-09 02:33:31 -04:00
var changed = false;
2023-08-08 02:03:26 -04:00
final messagesRecordKey =
proto.TypedKeyProto.fromProto(conversation.messages);
final crypto = await getConversationCrypto(
activeAccountInfo: activeAccountInfo,
remoteIdentityPublicKey: remoteIdentityPublicKey);
final writer = getConversationWriter(activeAccountInfo: activeAccountInfo);
newMessages = newMessages.sort((a, b) => Timestamp.fromInt64(a.timestamp)
.compareTo(Timestamp.fromInt64(b.timestamp)));
await (await DHTShortArray.openWrite(messagesRecordKey, writer,
parent: localConversationRecordKey, crypto: crypto))
.scope((messages) async {
// Ensure newMessages is sorted by timestamp
newMessages =
newMessages.sort((a, b) => a.timestamp.compareTo(b.timestamp));
// Existing messages will always be sorted by timestamp so merging is easy
var pos = 0;
outer:
for (final newMessage in newMessages) {
var skip = false;
while (pos < messages.length) {
final m = await messages.getItemProtobuf(proto.Message.fromBuffer, pos);
if (m == null) {
log.error('unable to get message #$pos');
break outer;
}
// If timestamp to insert is less than
// the current position, insert it here
final newTs = Timestamp.fromInt64(newMessage.timestamp);
final curTs = Timestamp.fromInt64(m.timestamp);
final cmp = newTs.compareTo(curTs);
if (cmp < 0) {
break;
} else if (cmp == 0) {
skip = true;
break;
}
pos++;
}
// Insert at this position
if (!skip) {
await messages.tryInsertItem(pos, newMessage.writeToBuffer());
changed = true;
}
}
});
return changed;
}
2023-08-09 02:33:31 -04:00
Future<IList<Message>?> getLocalConversationMessages({
2023-08-07 00:55:57 -04:00
required ActiveAccountInfo activeAccountInfo,
2023-08-07 11:02:29 -04:00
required TypedKey localConversationRecordKey,
2023-08-07 00:55:57 -04:00
required TypedKey remoteIdentityPublicKey,
}) async {
final conversation = await readLocalConversation(
activeAccountInfo: activeAccountInfo,
2023-08-07 11:02:29 -04:00
localConversationRecordKey: localConversationRecordKey,
2023-08-07 00:55:57 -04:00
remoteIdentityPublicKey: remoteIdentityPublicKey);
if (conversation == null) {
return null;
}
2023-08-07 11:02:29 -04:00
final messagesRecordKey =
proto.TypedKeyProto.fromProto(conversation.messages);
2023-08-07 00:55:57 -04:00
final crypto = await getConversationCrypto(
activeAccountInfo: activeAccountInfo,
remoteIdentityPublicKey: remoteIdentityPublicKey);
2023-08-07 11:02:29 -04:00
return (await DHTShortArray.openRead(messagesRecordKey,
parent: localConversationRecordKey, crypto: crypto))
2023-08-07 00:55:57 -04:00
.scope((messages) async {
2023-08-09 02:33:31 -04:00
var out = IList<Message>();
2023-08-07 00:55:57 -04:00
for (var i = 0; i < messages.length; i++) {
2023-08-09 02:33:31 -04:00
final msg = await messages.getItemProtobuf(Message.fromBuffer, i);
2023-08-07 00:55:57 -04:00
if (msg == null) {
throw Exception('Failed to get message');
}
out = out.add(msg);
}
return out;
});
}
2023-08-07 08:07:51 -04:00
2023-08-09 02:33:31 -04:00
Future<IList<Message>?> getRemoteConversationMessages({
2023-08-07 08:07:51 -04:00
required ActiveAccountInfo activeAccountInfo,
2023-08-07 11:02:29 -04:00
required TypedKey remoteConversationRecordKey,
2023-08-07 08:07:51 -04:00
required TypedKey remoteIdentityPublicKey,
}) async {
final conversation = await readRemoteConversation(
activeAccountInfo: activeAccountInfo,
2023-08-07 11:02:29 -04:00
remoteConversationRecordKey: remoteConversationRecordKey,
2023-08-07 08:07:51 -04:00
remoteIdentityPublicKey: remoteIdentityPublicKey);
if (conversation == null) {
return null;
}
2023-08-07 11:02:29 -04:00
final messagesRecordKey =
proto.TypedKeyProto.fromProto(conversation.messages);
2023-08-07 08:07:51 -04:00
final crypto = await getConversationCrypto(
activeAccountInfo: activeAccountInfo,
remoteIdentityPublicKey: remoteIdentityPublicKey);
2023-08-07 11:02:29 -04:00
return (await DHTShortArray.openRead(messagesRecordKey,
parent: remoteConversationRecordKey, crypto: crypto))
2023-08-07 08:07:51 -04:00
.scope((messages) async {
2023-08-09 02:33:31 -04:00
var out = IList<Message>();
2023-08-07 08:07:51 -04:00
for (var i = 0; i < messages.length; i++) {
2023-08-09 02:33:31 -04:00
final msg = await messages.getItemProtobuf(Message.fromBuffer, i);
2023-08-07 08:07:51 -04:00
if (msg == null) {
throw Exception('Failed to get message');
}
out = out.add(msg);
}
return out;
});
}
2023-08-09 02:33:31 -04:00
@riverpod
class ActiveConversationMessages extends _$ActiveConversationMessages {
/// Get message for active converation
@override
FutureOr<IList<Message>?> build() async {
2023-09-26 18:46:02 -04:00
await eventualVeilid.future;
2023-08-09 02:33:31 -04:00
final activeChat = activeChatState.currentState;
if (activeChat == null) {
return null;
}
final activeAccountInfo =
await ref.watch(fetchActiveAccountProvider.future);
if (activeAccountInfo == null) {
return null;
}
final contactList = ref.watch(fetchContactListProvider).asData?.value ??
const IListConst([]);
final activeChatContactIdx = contactList.indexWhere(
(c) =>
proto.TypedKeyProto.fromProto(c.remoteConversationRecordKey) ==
activeChat,
);
if (activeChatContactIdx == -1) {
return null;
}
final activeChatContact = contactList[activeChatContactIdx];
final remoteIdentityPublicKey =
proto.TypedKeyProto.fromProto(activeChatContact.identityPublicKey);
// final remoteConversationRecordKey = proto.TypedKeyProto.fromProto(
// activeChatContact.remoteConversationRecordKey);
final localConversationRecordKey = proto.TypedKeyProto.fromProto(
activeChatContact.localConversationRecordKey);
return await getLocalConversationMessages(
activeAccountInfo: activeAccountInfo,
localConversationRecordKey: localConversationRecordKey,
remoteIdentityPublicKey: remoteIdentityPublicKey,
);
}
}