snort/packages/app/src/Notifications.ts

55 lines
1.8 KiB
TypeScript
Raw Normal View History

2023-01-31 09:43:14 +00:00
import Nostrich from "nostrich.webp";
2023-02-11 20:05:46 +00:00
import { TaggedRawEvent } from "@snort/nostr";
import { EventKind } from "@snort/nostr";
import type { NotificationRequest } from "State/Login";
2023-03-29 12:10:22 +00:00
import { MetadataCache } from "Cache";
import { getDisplayName } from "Element/ProfileImage";
import { MentionRegex } from "Const";
2023-03-03 14:30:31 +00:00
import { tagFilterOfTextRepost, unwrap } from "Util";
2023-03-29 12:10:22 +00:00
import { UserCache } from "Cache/UserCache";
2023-03-03 14:30:31 +00:00
export async function makeNotification(ev: TaggedRawEvent): Promise<NotificationRequest | null> {
switch (ev.kind) {
case EventKind.TextNote: {
if (ev.tags.some(tagFilterOfTextRepost(ev))) {
2023-02-16 09:16:07 +00:00
return null;
}
2023-02-09 12:26:54 +00:00
const pubkeys = new Set([ev.pubkey, ...ev.tags.filter(a => a[0] === "p").map(a => a[1])]);
2023-03-03 14:30:31 +00:00
await UserCache.buffer([...pubkeys]);
const allUsers = [...pubkeys]
2023-03-29 12:10:22 +00:00
.map(a => UserCache.getFromCache(a))
2023-03-03 14:30:31 +00:00
.filter(a => a)
.map(a => unwrap(a));
2023-03-29 12:10:22 +00:00
const fromUser = UserCache.getFromCache(ev.pubkey);
const name = getDisplayName(fromUser, ev.pubkey);
2023-02-07 19:47:57 +00:00
const avatarUrl = fromUser?.picture || Nostrich;
return {
title: `Reply from ${name}`,
2023-03-03 14:30:31 +00:00
body: replaceTagsWithUser(ev, allUsers).substring(0, 50),
icon: avatarUrl,
timestamp: ev.created_at * 1000,
};
}
}
return null;
}
function replaceTagsWithUser(ev: TaggedRawEvent, users: MetadataCache[]) {
return ev.content
.split(MentionRegex)
2023-02-09 12:26:54 +00:00
.map(match => {
2023-02-07 19:47:57 +00:00
const matchTag = match.match(/#\[(\d+)\]/);
if (matchTag && matchTag.length === 2) {
2023-02-07 19:47:57 +00:00
const idx = parseInt(matchTag[1]);
const ref = ev.tags[idx];
if (ref && ref[0] === "p" && ref.length > 1) {
2023-02-09 12:26:54 +00:00
const u = users.find(a => a.pubkey === ref[1]);
return `@${getDisplayName(u, ref[1])}`;
}
}
return match;
})
.join();
}