-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrestore-chat-by-pin.ts
60 lines (51 loc) · 1.77 KB
/
restore-chat-by-pin.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
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { EncryptionTools } from "../utils";
import { NostrQueries, useKeysQuery, useNostrPublishMutation } from "../nostr";
import { Kind } from "nostr-tools";
import { useContext } from "react";
import { ChatContext } from "../chat-context-provider";
import { useGetKeysQuery, useSaveKeys } from "../api";
export function useRestoreChatByPin() {
const queryClient = useQueryClient();
const { activeUserData, activeUsername, storage } = useContext(ChatContext);
const { publicKey } = useKeysQuery();
const { data: keys } = useGetKeysQuery();
const { mutateAsync: updateProfile } = useNostrPublishMutation(
["chats/update-nostr-profile"],
Kind.Metadata,
() => {},
);
const { mutateAsync: uploadKeys } = useSaveKeys();
return useMutation({
mutationKey: ["chats/restore-chat-by-pin"],
mutationFn: async (pin: string) => {
if (!pin || !publicKey || !activeUserData) {
throw new Error(
"[Chat][Nostr] – no pin, public key or account information",
);
}
const { iv: initialVector, key: privateKey } = keys ?? {};
if (!initialVector || !privateKey) {
throw new Error("[Chat][Nostr] – no initial vector or private key");
}
const decryptedKey = EncryptionTools.decrypt(
privateKey,
pin,
Buffer.from(initialVector, "base64"),
);
queryClient.setQueryData(
[NostrQueries.PRIVATE_KEY, activeUsername],
decryptedKey,
);
storage?.setItem("ecency_nostr_pr_" + activeUsername, pin);
await updateProfile({
tags: [["p", publicKey]],
eventMetadata: {
name: activeUsername!,
about: "",
picture: "",
},
});
},
});
}