snort/src/Nostr/Thread.ts

57 lines
1.6 KiB
TypeScript
Raw Normal View History

2023-01-20 11:11:50 +00:00
import { u256 } from "Nostr";
import { default as NEvent } from "Nostr/Event";
import EventKind from "Nostr/EventKind";
import Tag from "Nostr/Tag";
2022-12-18 14:51:47 +00:00
export default class Thread {
Root?: Tag;
ReplyTo?: Tag;
Mentions: Array<Tag>;
PubKeys: Array<u256>;
2023-01-15 19:40:47 +00:00
constructor() {
this.Mentions = [];
this.PubKeys = [];
}
2022-12-18 14:51:47 +00:00
/**
* Extract thread information from an Event
* @param ev Event to extract thread from
*/
static ExtractThread(ev: NEvent) {
2023-02-07 19:47:57 +00:00
const isThread = ev.Tags.some((a) => a.Key === "e");
if (!isThread) {
return null;
}
2022-12-18 14:51:47 +00:00
2023-02-07 19:47:57 +00:00
const shouldWriteMarkers = ev.Kind === EventKind.TextNote;
const ret = new Thread();
const eTags = ev.Tags.filter((a) => a.Key === "e");
const marked = eTags.some((a) => a.Marker !== undefined);
if (!marked) {
ret.Root = eTags[0];
ret.Root.Marker = shouldWriteMarkers ? "root" : undefined;
if (eTags.length > 1) {
ret.ReplyTo = eTags[1];
ret.ReplyTo.Marker = shouldWriteMarkers ? "reply" : undefined;
}
if (eTags.length > 2) {
ret.Mentions = eTags.slice(2);
if (shouldWriteMarkers) {
ret.Mentions.forEach((a) => (a.Marker = "mention"));
2022-12-18 14:51:47 +00:00
}
}
} else {
2023-02-07 19:47:57 +00:00
const root = eTags.find((a) => a.Marker === "root");
const reply = eTags.find((a) => a.Marker === "reply");
ret.Root = root;
ret.ReplyTo = reply;
ret.Mentions = eTags.filter((a) => a.Marker === "mention");
2022-12-18 14:51:47 +00:00
}
ret.PubKeys = Array.from(
new Set(ev.Tags.filter((a) => a.Key === "p").map((a) => <u256>a.PubKey))
);
return ret;
}
}