flockstr/lib/hooks/useCurrentUser.ts

98 lines
2.6 KiB
TypeScript
Raw Normal View History

"use client";
2023-10-20 15:26:55 -04:00
import { useEffect } from "react";
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-20 15:26:55 -04:00
import useSubscriptions from "./useSubscriptions";
export default function useCurrentUser() {
const {
currentUser,
setCurrentUser,
updateCurrentUser,
follows,
2023-10-20 15:26:55 -04:00
setFollows,
2023-10-20 18:14:24 -04:00
addFollow,
} = currentUserStore();
2023-10-20 15:26:55 -04:00
const { loginWithNip07, getProfile, ndk, fetchEvents } = useNDK();
2023-10-18 12:23:39 -04:00
const { init } = useLists();
2023-10-20 15:26:55 -04:00
const { init: initSubscriptions, mySubscription } = useSubscriptions();
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");
}
2023-10-20 15:26:55 -04:00
const pubkey = nip19.decode(user.npub).data.toString();
await loginWithPubkey(pubkey);
void initSubscriptions(pubkey);
2023-10-15 12:11:39 -04:00
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
}
}
function logout() {
localStorage.removeItem("shouldReconnect");
setCurrentUser(null);
window.location.reload();
}
function handleUpdateUser(userInfo: string) {
const userObject = UserSchema.safeParse(JSON.parse(userInfo));
if (!userObject.success) return;
const parsedData = UserSchema.safeParse({
...currentUser,
...userObject,
});
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 });
console.log("user", user);
await user.fetchProfile();
setCurrentUser(user);
2023-10-18 12:23:39 -04:00
void init(user.pubkey);
}
2023-10-20 15:26:55 -04:00
useEffect(() => {
if (!currentUser) return;
console.log("fetching follows");
(async () => {
const following = await currentUser.follows();
setFollows(following);
})();
}, [currentUser]);
return {
currentUser,
isLoading: false,
follows,
setCurrentUser,
logout,
updateUser: handleUpdateUser,
loginWithPubkey,
2023-10-15 11:44:15 -04:00
attemptLogin,
2023-10-20 15:26:55 -04:00
initSubscriptions,
mySubscription,
2023-10-20 18:14:24 -04:00
addFollow,
setFollows,
};
}