loadArchiveWithTimeline method

Future<List<ArchivedRoom>> loadArchiveWithTimeline()

Fetch the archived rooms from the server and return them as a list of ArchivedRoom objects containing the Room and the associated Timeline.

Implementation

Future<List<ArchivedRoom>> loadArchiveWithTimeline() async {
  _archivedRooms.clear();
  final syncResp = await sync(
    filter: '{"room":{"include_leave":true,"timeline":{"limit":10}}}',
    timeout: _archiveCacheBusterTimeout,
  );
  // wrap around and hope there are not more than 30 leaves in 2 minutes :)
  _archiveCacheBusterTimeout = (_archiveCacheBusterTimeout + 1) % 30;

  final leave = syncResp.rooms?.leave;
  if (leave != null) {
    for (final entry in leave.entries) {
      final id = entry.key;
      final room = entry.value;
      final leftRoom = Room(
        id: id,
        membership: Membership.leave,
        client: this,
        roomAccountData:
            room.accountData?.asMap().map((k, v) => MapEntry(v.type, v)) ??
                <String, BasicRoomEvent>{},
      );

      final timeline = Timeline(
          room: leftRoom,
          chunk: TimelineChunk(
              events: room.timeline?.events?.reversed
                      .toList() // we display the event in the other sence
                      .map((e) => Event.fromSDNEvent(e, leftRoom))
                      .toList() ??
                  []));

      for (var i = 0; i < timeline.events.length; i++) {
        // Try to decrypt encrypted events but don't update the database.
        if (leftRoom.encrypted && leftRoom.client.encryptionEnabled) {
          if (timeline.events[i].type == EventTypes.Encrypted) {
            timeline.events[i] =
                await leftRoom.client.encryption!.decryptRoomEvent(
              leftRoom.id,
              timeline.events[i],
            );
          }
        }
      }

      room.timeline?.events?.forEach((event) {
        leftRoom.setState(Event.fromSDNEvent(
          event,
          leftRoom,
        ));
      });

      leftRoom.prev_batch = room.timeline?.prevBatch;
      room.state?.forEach((event) {
        leftRoom.setState(Event.fromSDNEvent(
          event,
          leftRoom,
        ));
      });

      _archivedRooms.add(ArchivedRoom(room: leftRoom, timeline: timeline));
    }
  }
  return _archivedRooms;
}