relatica/lib/models/direct_message_thread.dart

99 wiersze
2.6 KiB
Dart

import 'package:flutter/foundation.dart';
import 'auth/profile.dart';
import 'direct_message.dart';
class DirectMessageThread {
final List<DirectMessage> messages;
final List<String> participantIds;
final String title;
final String parentUri;
DirectMessageThread({
required this.messages,
required this.participantIds,
required this.title,
required this.parentUri,
});
DirectMessageThread deepCopy() => DirectMessageThread(
messages: List.from(messages),
participantIds: List.from(participantIds),
title: title,
parentUri: parentUri,
);
DirectMessageThread copy({List<DirectMessage>? messages}) =>
DirectMessageThread(
messages: messages ?? this.messages,
participantIds: participantIds,
title: title,
parentUri: parentUri,
);
get allSeen => messages.isEmpty
? false
: messages
.map((m) => m.seen)
.reduce((allUnseen, thisUnseen) => allUnseen && thisUnseen);
static List<DirectMessageThread> createThreads(
Profile profile,
Iterable<DirectMessage> messages,
) {
final threads = <String, List<DirectMessage>>{};
for (final m in messages) {
final thread = threads.putIfAbsent(m.parentUri, () => []);
thread.add(m);
}
final result = <DirectMessageThread>[];
for (final t in threads.entries) {
final parentUri = t.key;
final threadMessages = t.value;
final participantIds = <String>{};
var title = '';
threadMessages.sort((m1, m2) => m1.createdAt.compareTo(m2.createdAt));
for (final m in threadMessages) {
participantIds.add(m.senderId);
participantIds.add(m.recipientId);
if (title.isEmpty) {
title = m.title;
}
}
final thread = DirectMessageThread(
messages: threadMessages,
participantIds: participantIds.toList(),
title: title,
parentUri: parentUri,
);
result.add(thread);
}
result.sort((t1, t2) =>
t2.messages.first.createdAt.compareTo(t1.messages.first.createdAt));
return result;
}
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is DirectMessageThread &&
runtimeType == other.runtimeType &&
title == other.title &&
parentUri == other.parentUri &&
listEquals(messages, other.messages) &&
listEquals(participantIds, other.participantIds);
@override
int get hashCode =>
title.hashCode ^
parentUri.hashCode ^
Object.hashAll(messages) ^
Object.hashAll(participantIds);
}