Make MastoAPI streaming work for public feeds

This commit is contained in:
Alex Gleason
2023-08-25 14:59:37 -05:00
parent d1117f5513
commit f7cd67c572
2 changed files with 38 additions and 5 deletions

View File

@@ -1,6 +1,10 @@
import { AppController } from '@/app.ts';
import { type Event } from '@/deps.ts';
import { type DittoFilter } from '@/filter.ts';
import { TOKEN_REGEX } from '@/middleware/auth19.ts';
import { streamSchema, ws } from '@/stream.ts';
import { Sub } from '@/subs.ts';
import { toStatus } from '@/transformers/nostr-to-mastoapi.ts';
import { bech32ToPubkey } from '@/utils.ts';
const streamingController: AppController = (c) => {
@@ -29,10 +33,30 @@ const streamingController: AppController = (c) => {
pubkey: bech32ToPubkey(match[1]),
};
socket.addEventListener('open', () => {
function send(name: string, payload: object) {
if (socket.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify({
event: name,
payload: JSON.stringify(payload),
}));
}
}
socket.addEventListener('open', async () => {
console.log('websocket: connection opened');
if (stream) {
ws.subscribe(conn, { stream });
if (!stream) return;
ws.subscribe(conn, { stream });
const filter = topicToFilter(stream);
if (filter) {
for await (const event of Sub.sub(socket, '1', [filter])) {
const status = await toStatus(event);
if (status) {
send('update', status);
}
}
}
});
@@ -46,4 +70,13 @@ const streamingController: AppController = (c) => {
return response;
};
function topicToFilter(topic: string): DittoFilter<1> | undefined {
switch (topic) {
case 'public':
return { kinds: [1] };
case 'public:local':
return { kinds: [1], local: true };
}
}
export { streamingController };