snort/src/Nostr/Thread.ts

54 lines
1.7 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 {
2023-01-15 19:40:47 +00:00
Root?: Tag;
ReplyTo?: Tag;
Mentions: Array<Tag>;
PubKeys: Array<u256>;
2022-12-18 14:51:47 +00:00
constructor() {
this.Mentions = [];
2022-12-20 12:08:41 +00:00
this.PubKeys = [];
2022-12-18 14:51:47 +00:00
}
/**
* Extract thread information from an Event
2023-01-15 19:40:47 +00:00
* @param ev Event to extract thread from
2022-12-18 14:51:47 +00:00
*/
2023-01-15 19:40:47 +00:00
static ExtractThread(ev: NEvent) {
2022-12-18 14:51:47 +00:00
let isThread = ev.Tags.some(a => a.Key === "e");
if (!isThread) {
return null;
}
2023-01-08 21:59:33 +00:00
let shouldWriteMarkers = ev.Kind === EventKind.TextNote;
2022-12-18 14:51:47 +00:00
let ret = new Thread();
let eTags = ev.Tags.filter(a => a.Key === "e");
2023-01-15 19:40:47 +00:00
let marked = eTags.some(a => a.Marker !== undefined);
2022-12-18 14:51:47 +00:00
if (!marked) {
ret.Root = eTags[0];
2023-01-15 19:40:47 +00:00
ret.Root.Marker = shouldWriteMarkers ? "root" : undefined;
2023-01-06 15:48:10 +00:00
if (eTags.length > 1) {
ret.ReplyTo = eTags[1];
2023-01-15 19:40:47 +00:00
ret.ReplyTo.Marker = shouldWriteMarkers ? "reply" : undefined;
2023-01-06 15:48:10 +00:00
}
2022-12-18 14:51:47 +00:00
if (eTags.length > 2) {
2023-01-06 15:48:10 +00:00
ret.Mentions = eTags.slice(2);
2023-01-08 21:59:33 +00:00
if (shouldWriteMarkers) {
ret.Mentions.forEach(a => a.Marker = "mention");
}
2022-12-18 14:51:47 +00:00
}
} else {
let root = eTags.find(a => a.Marker === "root");
let reply = eTags.find(a => a.Marker === "reply");
ret.Root = root;
ret.ReplyTo = reply;
2022-12-29 16:19:16 +00:00
ret.Mentions = eTags.filter(a => a.Marker === "mention");
2022-12-18 14:51:47 +00:00
}
2023-01-15 19:40:47 +00:00
ret.PubKeys = Array.from(new Set(ev.Tags.filter(a => a.Key === "p").map(a => <u256>a.PubKey)));
2022-12-18 14:51:47 +00:00
return ret;
}
}