-
Notifications
You must be signed in to change notification settings - Fork 0
/
send-direct-message.ts
69 lines (62 loc) · 1.97 KB
/
send-direct-message.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import { useKeysQuery, useNostrPublishMutation } from "../core";
import { Kind, nip04 } from "nostr-tools";
import { useMutation } from "@tanstack/react-query";
import { useFindHealthyRelayQuery } from "./find-healthy-relay";
import { convertEvent } from "../utils/event-converter";
import { MessagesManagement } from "../utils";
interface Payload {
message: string;
forwardedFrom?: string;
parentMessageId?: string;
}
export function useNostrSendDirectMessage(
ownerPrivateKey: string,
destinationPublicKey?: string,
parent?: string,
) {
const { privateKey, publicKey } = useKeysQuery();
const { mutateAsync: publishEncryptedMessage } = useNostrPublishMutation(
["chats/nostr-publish-encrypted-message"],
Kind.EncryptedDirectMessage,
() => {},
);
const { mutateAsync: findHealthyRelay } = useFindHealthyRelayQuery();
return useMutation({
mutationKey: ["chats/send-direct-message"],
mutationFn: async ({
message,
forwardedFrom,
parentMessageId,
}: Payload) => {
if (!publicKey || !privateKey || !destinationPublicKey) {
throw new Error(
"[Chat][Nostr] – attempting to send direct message with no private, destination or public key",
);
}
const encryptedMessage = await nip04.encrypt(
ownerPrivateKey,
destinationPublicKey,
message,
);
const tagsBuilder = MessagesManagement.MessagesTagsBuilder.shared
.withDestination(destinationPublicKey)
.withForwardedFrom(forwardedFrom)
.withReferenceTo(parentMessageId);
if (parent) {
const relay = await findHealthyRelay(parent);
if (relay) {
tagsBuilder.withRoot(parent, relay);
}
}
const event = await publishEncryptedMessage({
tags: tagsBuilder.build(),
eventMetadata: encryptedMessage,
});
return convertEvent<Kind.EncryptedDirectMessage>(
event,
publicKey,
privateKey,
)!!;
},
});
}