-
Notifications
You must be signed in to change notification settings - Fork 0
/
resend-message.ts
81 lines (75 loc) · 2.33 KB
/
resend-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
70
71
72
73
74
75
76
77
78
79
80
81
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useContext } from "react";
import { ChatContext } from "../chat-context-provider";
import {
Channel,
DirectContact,
Message,
useKeysQuery,
useNostrSendDirectMessage,
useNostrSendPublicMessage,
} from "../nostr";
import { PublishNostrError } from "../nostr/errors";
import { convertEvent } from "../nostr/utils/event-converter";
import { isCommunity } from "../utils";
import { Kind } from "nostr-tools";
import { MessagesQueryUtil } from "./utils";
export function useResendMessage(
currentChannel?: Channel,
currentContact?: DirectContact,
onSuccess?: () => void,
) {
const queryClient = useQueryClient();
const { receiverPubKey, activeUsername } = useContext(ChatContext);
const { privateKey, publicKey } = useKeysQuery();
const { mutateAsync: sendDirectMessage } = useNostrSendDirectMessage(
privateKey!!,
receiverPubKey,
undefined,
);
const { mutateAsync: sendPublicMessage } = useNostrSendPublicMessage(
currentChannel?.id,
undefined,
);
return useMutation({
mutationKey: ["chats/send-message"],
mutationFn: async (message: Message) => {
if (!currentChannel && isCommunity(currentContact?.name)) {
throw new Error(
"[Chat][SendMessage] – provided user is community but channel not found",
);
}
if (currentChannel) {
return sendPublicMessage({ message: message.content });
} else if (currentContact) {
return sendDirectMessage({ message: message.content });
} else {
throw new Error("[Chat][SendMessage] – no receiver");
}
},
onSuccess: (message) => {
MessagesQueryUtil.updateMessageStatusInQuery(
queryClient,
message,
0,
activeUsername,
currentChannel?.id ?? currentContact?.pubkey,
);
onSuccess?.();
},
onError: async (error: PublishNostrError | Error) => {
if ("event" in error) {
const message = await convertEvent<
Kind.EncryptedDirectMessage | Kind.ChannelMessage
>(error.event, publicKey!!, privateKey!!)!!;
MessagesQueryUtil.updateMessageStatusInQuery(
queryClient,
message,
2,
activeUsername,
currentChannel?.id ?? currentContact?.pubkey,
);
}
},
});
}