2023-10-15 10:58:44 -04:00
|
|
|
"use client";
|
|
|
|
|
|
|
|
import currentUserStore from "@/lib/stores/currentUser";
|
|
|
|
// import useEvents from "@/lib/hooks/useEvents";
|
|
|
|
import { UserSchema } from "@/types";
|
|
|
|
import { useNDK } from "@/app/_providers/ndk";
|
2023-10-15 11:44:15 -04:00
|
|
|
import { nip19 } from "nostr-tools";
|
2023-10-18 12:23:39 -04:00
|
|
|
import useLists from "./useLists";
|
2023-10-15 10:58:44 -04:00
|
|
|
export default function useCurrentUser() {
|
|
|
|
const {
|
|
|
|
currentUser,
|
|
|
|
setCurrentUser,
|
|
|
|
setFollows,
|
|
|
|
updateCurrentUser,
|
|
|
|
follows,
|
|
|
|
} = currentUserStore();
|
|
|
|
const { loginWithNip07, getProfile, ndk } = useNDK();
|
2023-10-18 12:23:39 -04:00
|
|
|
const { init } = useLists();
|
2023-10-15 11:44:15 -04:00
|
|
|
async function attemptLogin() {
|
2023-10-15 12:11:39 -04:00
|
|
|
try {
|
|
|
|
const shouldReconnect = localStorage.getItem("shouldReconnect");
|
|
|
|
if (!shouldReconnect || typeof window.nostr === "undefined") return;
|
|
|
|
const user = await loginWithNip07();
|
|
|
|
if (!user) {
|
|
|
|
throw new Error("NO auth");
|
|
|
|
}
|
|
|
|
console.log("LOGIN", user);
|
|
|
|
await loginWithPubkey(nip19.decode(user.npub).data.toString());
|
|
|
|
if (typeof window.webln !== "undefined") {
|
|
|
|
await window.webln.enable();
|
|
|
|
}
|
|
|
|
console.log("connected ");
|
|
|
|
} catch (err) {
|
|
|
|
console.log("Error at attemptLogin", err);
|
2023-10-15 11:44:15 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-10-15 10:58:44 -04:00
|
|
|
function logout() {
|
|
|
|
localStorage.removeItem("shouldReconnect");
|
|
|
|
setCurrentUser(null);
|
|
|
|
window.location.reload();
|
|
|
|
}
|
|
|
|
function handleUpdateUser(userInfo: string) {
|
2023-10-15 22:55:33 -04:00
|
|
|
const userObject = UserSchema.safeParse(JSON.parse(userInfo));
|
|
|
|
if (!userObject.success) return;
|
2023-10-15 10:58:44 -04:00
|
|
|
const parsedData = UserSchema.safeParse({
|
|
|
|
...currentUser,
|
2023-10-15 22:55:33 -04:00
|
|
|
...userObject,
|
2023-10-15 10:58:44 -04:00
|
|
|
});
|
|
|
|
if (parsedData.success) {
|
|
|
|
updateCurrentUser({
|
|
|
|
profile: {
|
|
|
|
...parsedData.data,
|
|
|
|
displayName: parsedData.data.display_name,
|
|
|
|
},
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async function loginWithPubkey(pubkey: string) {
|
2023-10-15 12:11:39 -04:00
|
|
|
if (!ndk) return;
|
|
|
|
const user = ndk.getUser({ hexpubkey: pubkey });
|
2023-10-15 10:58:44 -04:00
|
|
|
console.log("user", user);
|
|
|
|
await user.fetchProfile();
|
|
|
|
setCurrentUser(user);
|
2023-10-18 12:23:39 -04:00
|
|
|
void init(user.pubkey);
|
2023-10-15 10:58:44 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
currentUser,
|
|
|
|
isLoading: false,
|
|
|
|
follows,
|
|
|
|
setCurrentUser,
|
|
|
|
logout,
|
|
|
|
updateUser: handleUpdateUser,
|
|
|
|
loginWithPubkey,
|
2023-10-15 11:44:15 -04:00
|
|
|
attemptLogin,
|
2023-10-15 10:58:44 -04:00
|
|
|
};
|
|
|
|
}
|