diff --git a/lib/src/event.dart b/lib/src/event.dart index cbd96f0..1462bc7 100644 --- a/lib/src/event.dart +++ b/lib/src/event.dart @@ -428,10 +428,10 @@ class Event { /// Trys to decrypt this event and persists it in the database afterwards Future decryptAndStore([String updateType = 'timeline']) async { final newEvent = decrypted; - if (newEvent.type == EventTypes.Encrypted || room.client.database == null) { - return newEvent; // decryption failed or we don't have a database + if (newEvent.type == EventTypes.Encrypted) { + return newEvent; // decryption failed } - await room.client.database.storeEventUpdate( + await room.client.database?.storeEventUpdate( room.client.id, EventUpdate( eventType: newEvent.typeKey, @@ -441,6 +441,9 @@ class Event { sortOrder: newEvent.sortOrder, ), ); + if (updateType != 'history') { + room.setState(newEvent); + } return newEvent; } diff --git a/lib/src/room.dart b/lib/src/room.dart index 1823d3e..4a4612e 100644 --- a/lib/src/room.dart +++ b/lib/src/room.dart @@ -273,10 +273,7 @@ class Room { Future _tryAgainDecryptLastMessage() async { if (getState('m.room.encrypted') != null) { - final decrypted = await getState('m.room.encrypted').decryptAndStore(); - if (decrypted.type != EventTypes.Encrypted) { - setState(decrypted); - } + await getState('m.room.encrypted').decryptAndStore(); } } @@ -405,14 +402,22 @@ class Room { String notificationSettings; Event get lastEvent { - var lastSortOrder = -1e32; // this bound to be small enough + // as lastEvent calculation is based on the state events we unfortunately cannot + // use sortOrder here: With many state events we just know which ones are the + // newest ones, without knowing in which order they actually happened. As such, + // using the origin_server_ts is the best guess for this algorithm. While not + // perfect, it is only used for the room preview in the room list and sorting + // said room list, so it should be good enough. + var lastTime = DateTime.fromMillisecondsSinceEpoch(0); var lastEvent = getState('m.room.message'); if (lastEvent == null) { states.forEach((final String key, final entry) { if (!entry.containsKey('')) return; final Event state = entry['']; - if (state.sortOrder != null && state.sortOrder > lastSortOrder) { - lastSortOrder = state.sortOrder; + if (state.time != null && + state.time.millisecondsSinceEpoch > + lastTime.millisecondsSinceEpoch) { + lastTime = state.time; lastEvent = state; } });