Skip to content

Commit

Permalink
Add getRoomEvents to Matrix client
Browse files Browse the repository at this point in the history
  • Loading branch information
AndrewKvalheim committed Mar 27, 2023
1 parent d477809 commit d01e8da
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
27 changes: 27 additions & 0 deletions src/lib/Client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,13 @@ import {
} from "matrix-bot-sdk";
import { setTimeout } from "timers/promises";
import {
Event,
GetRoomMessagesRequest,
GetRoomMessagesResponse,
isStateEvent,
MessageEvent,
Received,
RoomEventFilter,
StateEvent,
StateEventInput,
Sync,
Expand All @@ -24,6 +29,7 @@ export interface RoomCreateOptions extends RoomCreateFullOptions {

setRequestFn(getRequestFn().defaults({ headers: { "User-Agent": userAgent } }));

const directions = { forward: "f", reverse: "b" } as const;
const issue8895Cooldown = 1000 * Number(env("ISSUE_8895_COOLDOWN"));
const minTime = 1000 / Number(env("MATRIX_RATE_LIMIT"));

Expand Down Expand Up @@ -89,6 +95,27 @@ export default class Client extends MatrixClient {
return handler(...args);
};

// Pending https://github.com/turt2live/matrix-bot-sdk/issues/250
public async *getRoomEvents(
room: string,
direction: "forward" | "reverse",
filter?: RoomEventFilter
): AsyncGenerator<Received<Event>[], void, void> {
const path = `/_matrix/client/v3/rooms/${encodeURIComponent(room)}/messages`;
const base: GetRoomMessagesRequest = {
...(direction && { dir: directions[direction] }),
...(filter && { filter: JSON.stringify(filter) }),
};

let from: string | undefined;
do {
const query: GetRoomMessagesRequest = { ...base, ...(from && { from }) };
const response: GetRoomMessagesResponse = await this.doRequest("GET", path, query);
from = response.end;
yield response.chunk;
} while (from);
}

public override getRoomState: MatrixClient["getRoomState"] = async (id) => [
...(this.#cache.get(id)?.values() ?? []),
];
Expand Down
18 changes: 18 additions & 0 deletions src/lib/matrix.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,24 @@ export const mergeWithMatrixState = <T, F>(to: T, from: F): T & F =>
// Client API
//

export interface GetRoomMessagesRequest {
dir: "b" | "f";
filter?: string; // RoomEventFilter
from?: string;
}

export interface GetRoomMessagesResponse {
chunk: Received<Event>[];
end?: string;
}

export interface RoomEventFilter {
not_senders?: string[];
not_types?: string[];
senders?: string[];
types?: string[];
}

export interface Sync {
rooms?: {
join?: {
Expand Down

0 comments on commit d01e8da

Please sign in to comment.