wip: refactor

This commit is contained in:
Ren Amamiya
2023-08-16 11:43:04 +07:00
parent 2d53019c10
commit c05bb54976
33 changed files with 600 additions and 1052 deletions

View File

@@ -58,40 +58,28 @@ export function ImportStep3Screen() {
</h1>
</div>
<div className="w-full rounded-xl bg-white/10 p-4">
{status === 'loading' ? (
<div className="w-full">
<div className="flex items-center gap-2">
<div className="h-11 w-11 animate-pulse rounded-lg bg-white/10" />
<div>
<div className="mb-1 h-4 w-16 animate-pulse rounded bg-white/10" />
<div className="h-3 w-36 animate-pulse rounded bg-white/10" />
</div>
</div>
</div>
) : (
<div className="flex flex-col gap-3">
<User pubkey={db.account.pubkey} />
<button
type="button"
className="inline-flex h-11 w-full items-center justify-between gap-2 rounded-lg bg-fuchsia-500 px-6 font-medium leading-none text-white hover:bg-fuchsia-600 focus:outline-none"
onClick={() => submit()}
>
{loading ? (
<>
<span className="w-5" />
<span>It might take a bit, please patient...</span>
<LoaderIcon className="h-5 w-5 animate-spin text-white" />
</>
) : (
<>
<span className="w-5" />
<span>Continue</span>
<ArrowRightCircleIcon className="h-5 w-5" />
</>
)}
</button>
</div>
)}
<div className="flex flex-col gap-3">
<User pubkey={db.account.pubkey} />
<button
type="button"
className="inline-flex h-11 w-full items-center justify-between gap-2 rounded-lg bg-fuchsia-500 px-6 font-medium leading-none text-white hover:bg-fuchsia-600 focus:outline-none"
onClick={() => submit()}
>
{loading ? (
<>
<span className="w-5" />
<span>It might take a bit, please patient...</span>
<LoaderIcon className="h-5 w-5 animate-spin text-white" />
</>
) : (
<>
<span className="w-5" />
<span>Continue</span>
<ArrowRightCircleIcon className="h-5 w-5" />
</>
)}
</button>
</div>
</div>
</div>
);

View File

@@ -5,15 +5,12 @@ import { useState } from 'react';
import { Resolver, useForm } from 'react-hook-form';
import { useNavigate } from 'react-router-dom';
import { removePrivkey } from '@libs/storage';
import { useStorage } from '@libs/storage/provider';
import { EyeOffIcon, EyeOnIcon, LoaderIcon } from '@shared/icons';
import { useStronghold } from '@stores/stronghold';
import { useAccount } from '@utils/hooks/useAccount';
type FormValues = {
password: string;
};
@@ -73,7 +70,7 @@ export function MigrateScreen() {
// add privkey to state
setPrivkey(db.account.privkey);
// remove privkey in db
await removePrivkey();
await db.removePrivkey();
// clear cache
await queryClient.invalidateQueries(['account']);
// redirect to home

View File

@@ -4,9 +4,11 @@ import { useState } from 'react';
import { Resolver, useForm } from 'react-hook-form';
import { Link, useNavigate } from 'react-router-dom';
import { User } from '@app/auth/components/user';
import { useStorage } from '@libs/storage/provider';
import { EyeOffIcon, EyeOnIcon, LoaderIcon } from '@shared/icons';
import { ArrowRightCircleIcon, EyeOffIcon, EyeOnIcon, LoaderIcon } from '@shared/icons';
import { useStronghold } from '@stores/stronghold';
@@ -36,7 +38,6 @@ export function UnlockScreen() {
const [loading, setLoading] = useState<boolean>(false);
const { db } = useStorage();
const {
register,
setError,
@@ -79,13 +80,17 @@ export function UnlockScreen() {
<div className="mb-6 text-center">
<h1 className="text-2xl font-semibold text-white">Enter password to unlock</h1>
</div>
<div className="mb-4 w-full rounded-xl bg-white/5 p-4">
<User pubkey={db.account.pubkey} />
</div>
<form onSubmit={handleSubmit(onSubmit)} className="mb-0 flex flex-col gap-3">
<div className="flex flex-col gap-1">
<div className="relative">
<input
{...register('password', { required: true })}
type={showPassword ? 'text' : 'password'}
className="relative h-12 w-full rounded-lg bg-white/10 py-1 text-center text-white !outline-none placeholder:text-white/10"
placeholder="Password"
className="relative h-12 w-full rounded-lg bg-white/10 py-1 text-center text-white !outline-none placeholder:text-white/50"
/>
<button
type="button"
@@ -107,12 +112,20 @@ export function UnlockScreen() {
<button
type="submit"
disabled={!isDirty || !isValid}
className="inline-flex h-12 w-full items-center justify-center rounded-md bg-fuchsia-500 font-medium text-white hover:bg-fuchsia-600"
className="inline-flex h-11 w-full items-center justify-between gap-2 rounded-lg bg-fuchsia-500 px-6 font-medium leading-none text-white hover:bg-fuchsia-600 focus:outline-none"
>
{loading ? (
<LoaderIcon className="h-4 w-4 animate-spin text-white" />
<>
<span className="w-5" />
<span>Decryting...</span>
<LoaderIcon className="h-5 w-5" />
</>
) : (
'Continue →'
<>
<span className="w-5" />
<span>Continue</span>
<ArrowRightCircleIcon className="h-5 w-5" />
</>
)}
</button>
<Link

View File

@@ -3,30 +3,25 @@ import * as Dialog from '@radix-ui/react-dialog';
import { nip19 } from 'nostr-tools';
import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { useHotkeys } from 'react-hotkeys-hook';
import { User } from '@app/auth/components/user';
import { useStorage } from '@libs/storage/provider';
import { CancelIcon, CheckCircleIcon, CommandIcon, LoaderIcon } from '@shared/icons';
import { BLOCK_KINDS, DEFAULT_AVATAR } from '@stores/constants';
import { ADD_FEEDBLOCK_SHORTCUT } from '@stores/shortcuts';
import { useWidgets } from '@stores/widgets';
import { useAccount } from '@utils/hooks/useAccount';
export function FeedModal() {
const setWidget = useWidgets((state) => state.setWidget);
const [open, setOpen] = useState(false);
const [loading, setLoading] = useState(false);
const [selected, setSelected] = useState([]);
const [query, setQuery] = useState('');
const { status, account } = useAccount();
const setWidget = useWidgets((state) => state.setWidget);
useHotkeys(ADD_FEEDBLOCK_SHORTCUT, () => setOpen(true));
const { db } = useStorage();
const {
register,
handleSubmit,
@@ -43,8 +38,8 @@ export function FeedModal() {
}
});
// insert to database
setWidget({
// update state
setWidget(db, {
kind: BLOCK_KINDS.feed,
title: data.title,
content: JSON.stringify(selected),
@@ -155,26 +150,22 @@ export function FeedModal() {
)}
</Combobox.Option>
)}
{status === 'loading' ? (
<p>Loading...</p>
) : (
account?.follows?.map((follow) => (
<Combobox.Option
key={follow}
value={follow}
className="group flex w-full items-center justify-between rounded-md px-2 py-2 hover:bg-white/10"
>
{({ selected }) => (
<>
<User pubkey={follow} />
{selected && (
<CheckCircleIcon className="h-4 w-4 text-green-500" />
)}
</>
)}
</Combobox.Option>
))
)}
{db.account?.follows?.map((follow) => (
<Combobox.Option
key={follow}
value={follow}
className="group flex w-full items-center justify-between rounded-md px-2 py-2 hover:bg-white/10"
>
{({ selected }) => (
<>
<User pubkey={follow} />
{selected && (
<CheckCircleIcon className="h-4 w-4 text-green-500" />
)}
</>
)}
</Combobox.Option>
))}
</Combobox.Options>
</Combobox>
</div>

View File

@@ -1,22 +1,21 @@
import * as Dialog from '@radix-ui/react-dialog';
import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { useHotkeys } from 'react-hotkeys-hook';
import { useStorage } from '@libs/storage/provider';
import { CancelIcon, CommandIcon, LoaderIcon } from '@shared/icons';
import { BLOCK_KINDS } from '@stores/constants';
import { ADD_HASHTAGBLOCK_SHORTCUT } from '@stores/shortcuts';
import { useWidgets } from '@stores/widgets';
export function HashtagModal() {
const setWidget = useWidgets((state) => state.setWidget);
const [loading, setLoading] = useState(false);
const [open, setOpen] = useState(false);
const setWidget = useWidgets((state) => state.setWidget);
useHotkeys(ADD_HASHTAGBLOCK_SHORTCUT, () => setOpen(false));
const { db } = useStorage();
const {
register,
handleSubmit,
@@ -27,8 +26,8 @@ export function HashtagModal() {
const onSubmit = async (data: { hashtag: string }) => {
setLoading(true);
// mutate
setWidget({
// update state
setWidget(db, {
kind: BLOCK_KINDS.hashtag,
title: data.hashtag,
content: data.hashtag.replace('#', ''),

View File

@@ -1,13 +1,13 @@
import * as Dialog from '@radix-ui/react-dialog';
import { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import { useHotkeys } from 'react-hotkeys-hook';
import { useStorage } from '@libs/storage/provider';
import { CancelIcon, CommandIcon, LoaderIcon } from '@shared/icons';
import { Image } from '@shared/image';
import { BLOCK_KINDS, DEFAULT_AVATAR } from '@stores/constants';
import { ADD_IMAGEBLOCK_SHORTCUT } from '@stores/shortcuts';
import { useWidgets } from '@stores/widgets';
import { useImageUploader } from '@utils/hooks/useUploader';
@@ -20,8 +20,7 @@ export function ImageModal() {
const [loading, setLoading] = useState(false);
const [image, setImage] = useState('');
useHotkeys(ADD_IMAGEBLOCK_SHORTCUT, () => setOpen(false));
const { db } = useStorage();
const {
register,
handleSubmit,
@@ -41,7 +40,7 @@ export function ImageModal() {
setLoading(true);
// mutate
setWidget({ kind: BLOCK_KINDS.image, title: data.title, content: data.content });
setWidget(db, { kind: BLOCK_KINDS.image, title: data.title, content: data.content });
setLoading(false);
// reset form

View File

@@ -58,21 +58,13 @@ export function FeedBlock({ params }: { params: Widget }) {
const reply = note.tags.find((el) => el[3] === 'reply')?.[1];
if (root || reply) {
return (
<div
key={note.event_id || note.id}
data-index={index}
ref={rowVirtualizer.measureElement}
>
<div key={note.id} data-index={index} ref={rowVirtualizer.measureElement}>
<NoteThread event={note} root={root} reply={reply} />
</div>
);
} else {
return (
<div
key={note.event_id || note.id}
data-index={index}
ref={rowVirtualizer.measureElement}
>
<div key={note.id} data-index={index} ref={rowVirtualizer.measureElement}>
<NoteKind_1 event={note} skipMetadata={false} />
</div>
);
@@ -80,32 +72,20 @@ export function FeedBlock({ params }: { params: Widget }) {
}
case 6:
return (
<div
key={note.event_id || note.id}
data-index={index}
ref={rowVirtualizer.measureElement}
>
<Repost key={note.event_id} event={note} />
<div key={note.id} data-index={index} ref={rowVirtualizer.measureElement}>
<Repost key={note.id} event={note} />
</div>
);
case 1063:
return (
<div
key={note.event_id || note.id}
data-index={index}
ref={rowVirtualizer.measureElement}
>
<NoteKind_1063 key={note.event_id} event={note} />
<div key={note.id} data-index={index} ref={rowVirtualizer.measureElement}>
<NoteKind_1063 key={note.id} event={note} />
</div>
);
default:
return (
<div
key={note.event_id || note.id}
data-index={index}
ref={rowVirtualizer.measureElement}
>
<NoteKindUnsupport key={note.event_id} event={note} />
<div key={note.id} data-index={index} ref={rowVirtualizer.measureElement}>
<NoteKindUnsupport key={note.id} event={note} />
</div>
);
}

View File

@@ -1,7 +1,7 @@
import { useInfiniteQuery } from '@tanstack/react-query';
import { useVirtualizer } from '@tanstack/react-virtual';
import { NostrEvent } from 'nostr-fetch';
import { useCallback, useEffect, useMemo, useRef } from 'react';
import { useCallback, useMemo, useRef } from 'react';
import { Link } from 'react-router-dom';
import { NoteKind_1, NoteKind_1063, NoteThread, Repost } from '@shared/notes';
@@ -14,14 +14,15 @@ import { LumeEvent } from '@utils/types';
export function NetworkBlock() {
const { fetchNotes } = useNostr();
const { status, data, hasNextPage, isFetchingNextPage, fetchNextPage } =
useInfiniteQuery({
queryKey: ['network-widget'],
queryFn: async ({ pageParam = 24 }) => {
return await fetchNotes(pageParam);
},
getNextPageParam: (lastPage) => lastPage.nextCursor,
});
const { status, data, hasNextPage, isFetchingNextPage } = useInfiniteQuery({
queryKey: ['network-widget'],
queryFn: async ({ pageParam = 24 }) => {
return await fetchNotes(pageParam);
},
getNextPageParam: (lastPage) => lastPage.nextCursor,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
});
const parentRef = useRef();
const notes = useMemo(
@@ -40,18 +41,6 @@ export function NetworkBlock() {
const itemsVirtualizer = rowVirtualizer.getVirtualItems();
const totalSize = rowVirtualizer.getTotalSize();
useEffect(() => {
const [lastItem] = [...itemsVirtualizer].reverse();
if (!lastItem) {
return;
}
if (lastItem.index >= notes.length - 1 && hasNextPage && !isFetchingNextPage) {
fetchNextPage();
}
}, [notes.length, fetchNextPage, itemsVirtualizer]);
const renderItem = useCallback(
(index: string | number) => {
const note: LumeEvent = notes[index];
@@ -69,7 +58,7 @@ export function NetworkBlock() {
if (root || reply) {
return (
<div
key={(root || reply) + (note.event_id || note.id) + index}
key={(root || reply) + note.id + index}
data-index={index}
ref={rowVirtualizer.measureElement}
>
@@ -79,7 +68,7 @@ export function NetworkBlock() {
} else {
return (
<div
key={(note.event_id || note.id) + index}
key={note.id + index}
data-index={index}
ref={rowVirtualizer.measureElement}
>
@@ -91,31 +80,31 @@ export function NetworkBlock() {
case 6:
return (
<div
key={(note.event_id || note.id) + index}
key={note.id + index}
data-index={index}
ref={rowVirtualizer.measureElement}
>
<Repost key={note.event_id} event={note} />
<Repost key={note.id} event={note} />
</div>
);
case 1063:
return (
<div
key={(note.event_id || note.id) + index}
key={note.id + index}
data-index={index}
ref={rowVirtualizer.measureElement}
>
<NoteKind_1063 key={note.event_id} event={note} />
<NoteKind_1063 key={note.id} event={note} />
</div>
);
default:
return (
<div
key={(note.event_id || note.id) + index}
key={note.id + index}
data-index={index}
ref={rowVirtualizer.measureElement}
>
<NoteKindUnsupport key={note.event_id} event={note} />
<NoteKindUnsupport key={note.id} event={note} />
</div>
);
}

View File

@@ -1,4 +1,5 @@
// import { useLiveThread } from '@app/space/hooks/useLiveThread';
import { useStorage } from '@libs/storage/provider';
import {
NoteActions,
NoteContent,
@@ -10,16 +11,12 @@ import { RepliesList } from '@shared/notes/replies/list';
import { NoteSkeleton } from '@shared/notes/skeleton';
import { TitleBar } from '@shared/titleBar';
import { useAccount } from '@utils/hooks/useAccount';
import { useEvent } from '@utils/hooks/useEvent';
import { Widget } from '@utils/types';
export function ThreadBlock({ params }: { params: Widget }) {
const { status, data } = useEvent(params.content);
const { account } = useAccount();
// subscribe to live reply
// useLiveThread(params.content);
const { db } = useStorage();
return (
<div className="scrollbar-hide h-full w-[400px] shrink-0 overflow-y-auto bg-white/10 pb-20">
@@ -50,7 +47,7 @@ export function ThreadBlock({ params }: { params: Widget }) {
</div>
)}
<div className="px-3">
{account && <NoteReplyForm id={params.content} pubkey={account.pubkey} />}
<NoteReplyForm id={params.content} pubkey={db.account.pubkey} />
<RepliesList id={params.content} />
</div>
</div>

View File

@@ -10,6 +10,8 @@ import { NetworkBlock } from '@app/space/components/widgets/network';
import { ThreadBlock } from '@app/space/components/widgets/thread';
import { UserBlock } from '@app/space/components/widgets/user';
import { useStorage } from '@libs/storage/provider';
import { LoaderIcon } from '@shared/icons';
import { useWidgets } from '@stores/widgets';
@@ -22,6 +24,8 @@ export function SpaceScreen() {
state.fetchWidgets,
]);
const { db } = useStorage();
const renderItem = useCallback(
(widget: Widget) => {
switch (widget.kind) {
@@ -43,7 +47,7 @@ export function SpaceScreen() {
);
useEffect(() => {
fetchWidgets();
fetchWidgets(db);
}, [fetchWidgets]);
return (

View File

@@ -30,7 +30,7 @@ export function SplashScreen() {
if (user.status === 'ok') {
const now = Math.floor(Date.now() / 1000);
await db.updateLastLogin(now);
invoke('close_splashscreen');
await invoke('close_splashscreen');
} else {
setIsLoading(false);
setErrorMessage(user.message);
@@ -55,7 +55,7 @@ export function SplashScreen() {
}, [ndk, db.account]);
return (
<div className="relative flex h-screen w-screen items-center justify-center bg-black">
<div className="relative flex h-screen w-screen items-center justify-center bg-black/90">
<div data-tauri-drag-region className="absolute left-0 top-0 z-10 h-11 w-full" />
<div className="flex min-h-0 w-full flex-1 items-center justify-center">
<div className="flex flex-col items-center justify-center gap-4">

View File

@@ -3,19 +3,20 @@ import { Link } from 'react-router-dom';
import { UserMetadata } from '@app/users/components/metadata';
import { useStorage } from '@libs/storage/provider';
import { EditProfileModal } from '@shared/editProfileModal';
import { Image } from '@shared/image';
import { DEFAULT_AVATAR } from '@stores/constants';
import { useAccount } from '@utils/hooks/useAccount';
import { useProfile } from '@utils/hooks/useProfile';
import { useSocial } from '@utils/hooks/useSocial';
import { shortenKey } from '@utils/shortenKey';
export function UserProfile({ pubkey }: { pubkey: string }) {
const { db } = useStorage();
const { user } = useProfile(pubkey);
const { account } = useAccount();
const { status, userFollows, follow, unfollow } = useSocial();
const [followed, setFollowed] = useState(false);
@@ -109,7 +110,7 @@ export function UserProfile({ pubkey }: { pubkey: string }) {
Message
</Link>
<span className="mx-2 inline-flex h-4 w-px bg-white/10" />
{account && account.pubkey === pubkey && <EditProfileModal />}
{db.account.pubkey === pubkey && <EditProfileModal />}
</div>
</div>
<div className="flex flex-col gap-8">

View File

@@ -3,7 +3,6 @@ import NDK from '@nostr-dev-kit/ndk';
import { useEffect, useState } from 'react';
import TauriAdapter from '@libs/ndk/cache';
import { getExplicitRelayUrls } from '@libs/storage';
import { useStorage } from '@libs/storage/provider';
import { FULL_RELAYS } from '@stores/constants';
@@ -56,7 +55,7 @@ export const NDKInstance = () => {
async function initNDK() {
let explicitRelayUrls: string[];
const explicitRelayUrlsFromDB = await getExplicitRelayUrls();
const explicitRelayUrlsFromDB = await db.getExplicitRelayUrls();
if (explicitRelayUrlsFromDB) {
explicitRelayUrls = await verifyRelays(explicitRelayUrlsFromDB);

View File

@@ -1,5 +1,5 @@
import Database from '@tauri-apps/plugin-sql';
import destr from 'destr';
import { destr } from 'destr';
import { parser } from '@utils/parser';
import { getParentID } from '@utils/transform';

View File

@@ -184,6 +184,12 @@ export class LumeStorage {
);
}
public async removePrivkey() {
return await this.db.execute(
`UPDATE accounts SET privkey = "privkey is stored in secure storage" WHERE id = "${this.account.id}";`
);
}
public async close() {
return this.db.close();
}

View File

@@ -24,10 +24,6 @@ const StorageProvider = ({ children }: PropsWithChildren<object>) => {
useEffect(() => {
if (!db) initLumeStorage();
return () => {
db.close();
};
}, []);
if (db) {

View File

@@ -2,20 +2,11 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { createRoot } from 'react-dom/client';
import { NDKProvider } from '@libs/ndk/provider';
import { getSetting } from '@libs/storage';
import { StorageProvider } from '@libs/storage/provider';
import App from './app';
const cacheTime = await getSetting('cache_time');
const queryClient = new QueryClient({
defaultOptions: {
queries: {
cacheTime: parseInt(cacheTime),
},
},
});
const queryClient = new QueryClient();
const container = document.getElementById('root');
const root = createRoot(container);

View File

@@ -1,6 +1,8 @@
import * as Dialog from '@radix-ui/react-dialog';
import { useHotkeys } from 'react-hotkeys-hook';
import { useStorage } from '@libs/storage/provider';
import { Composer, ComposerUser } from '@shared/composer';
import {
CancelIcon,
@@ -12,10 +14,8 @@ import {
import { useComposer } from '@stores/composer';
import { COMPOSE_SHORTCUT } from '@stores/shortcuts';
import { useAccount } from '@utils/hooks/useAccount';
export function ComposerModal() {
const { account } = useAccount();
const { db } = useStorage();
const [toggle, open] = useComposer((state) => [state.toggleModal, state.open]);
useHotkeys(COMPOSE_SHORTCUT, () => toggle(true));
@@ -25,7 +25,7 @@ export function ComposerModal() {
<Dialog.Trigger asChild>
<button
type="button"
className="inline-flex h-9 w-min items-center justify-center gap-1 rounded-md bg-white/10 px-4 text-sm font-medium text-white hover:bg-fuchsia-500 focus:outline-none active:translate-y-1 disabled:pointer-events-none disabled:opacity-50"
className="inline-flex h-9 w-min items-center justify-center gap-1 rounded-md bg-white/10 px-8 text-sm font-medium text-white hover:bg-fuchsia-500 focus:outline-none active:translate-y-1 disabled:pointer-events-none disabled:opacity-50"
>
<ComposeIcon className="h-4 w-4" />
Postr
@@ -37,7 +37,7 @@ export function ComposerModal() {
<div className="relative h-min w-full max-w-2xl rounded-xl bg-white/10">
<div className="flex items-center justify-between px-4 py-4">
<div className="flex items-center gap-2">
{account && <ComposerUser pubkey={account.pubkey} />}
<ComposerUser pubkey={db.account.pubkey} />
<span>
<ChevronRightIcon className="h-4 w-4 text-white/50" />
</span>

View File

@@ -1,31 +1,31 @@
import { create } from 'zustand';
import { createJSONStorage, persist } from 'zustand/middleware';
import { createWidget, getWidgets, removeWidget } from '@libs/storage';
import { LumeStorage } from '@libs/storage/instance';
import { Widget } from '@utils/types';
interface WidgetState {
widgets: null | Array<Widget>;
fetchWidgets: () => void;
setWidget: ({ kind, title, content }: Widget) => void;
removeWidget: (id: string) => void;
fetchWidgets: (db: LumeStorage) => void;
setWidget: (db: LumeStorage, { kind, title, content }: Widget) => void;
removeWidget: (db: LumeStorage, id: string) => void;
}
export const useWidgets = create<WidgetState>()(
persist(
(set) => ({
widgets: null,
fetchWidgets: async () => {
const widgets = await getWidgets();
fetchWidgets: async (db: LumeStorage) => {
const widgets = await db.getWidgets();
set({ widgets: widgets });
},
setWidget: async ({ kind, title, content }: Widget) => {
const widget: Widget = await createWidget(kind, title, content);
setWidget: async (db: LumeStorage, { kind, title, content }: Widget) => {
const widget: Widget = await db.createWidget(kind, title, content);
set((state) => ({ widgets: [...state.widgets, widget] }));
},
removeWidget: async (id: string) => {
await removeWidget(id);
removeWidget: async (db: LumeStorage, id: string) => {
await db.removeWidget(id);
set((state) => ({ widgets: state.widgets.filter((widget) => widget.id !== id) }));
},
}),

View File

@@ -2,32 +2,27 @@ import Database from '@tauri-apps/plugin-sql';
import { Account } from '@utils/types';
let db: null | Database = null;
async function connect(): Promise<Database> {
let db: null | Database = null;
if (db) {
return db;
}
try {
db = await Database.load('sqlite:lume.db');
} catch (e) {
throw new Error('Failed to connect to database, error: ', e);
}
return db;
}
export async function checkActiveAccount() {
const tempDB = await connect();
const db = await connect();
const result: Array<Account> = await db.select(
'SELECT * FROM accounts WHERE is_active = 1;'
);
// close temp db
tempDB.close();
if (result.length > 0) {
return true;
} else {
return false;
}
return result.length > 0;
}

View File

@@ -13,12 +13,12 @@ export function useEvent(id: string, embed?: string) {
if (embed) {
const event: LumeEvent = JSON.parse(embed);
if (event.kind === 1) embed['content'] = parser(event);
return embed;
return embed as unknown as LumeEvent;
} else {
const event = (await ndk.fetchEvent(id)) as unknown as LumeEvent;
if (!event) throw new Error('Event not found');
if (event.kind === 1) event['content'] = parser(event);
return event as unknown as LumeEvent;
const event = (await ndk.fetchEvent(id)) as LumeEvent;
if (!event) return null;
if (event.kind === 1) event['content'] = parser(event) as unknown as string;
return event as LumeEvent;
}
},
{

View File

@@ -6,10 +6,8 @@ import {
NDKSubscription,
NDKUser,
} from '@nostr-dev-kit/ndk';
import { ndkAdapter } from '@nostr-fetch/adapter-ndk';
import destr from 'destr';
import { destr } from 'destr';
import { LRUCache } from 'lru-cache';
import { NostrFetcher } from 'nostr-fetch';
import { nip19 } from 'nostr-tools';
import { useMemo } from 'react';
@@ -21,11 +19,10 @@ import { useStronghold } from '@stores/stronghold';
import { nHoursAgo } from '@utils/date';
export function useNostr() {
const { ndk, relayUrls } = useNDK();
const { ndk } = useNDK();
const { db } = useStorage();
const privkey = useStronghold((state) => state.privkey);
const fetcher = useMemo(() => NostrFetcher.withCustomPool(ndkAdapter(ndk)), [ndk]);
const subManager = useMemo(
() =>
new LRUCache<string, NDKSubscription, void>({
@@ -85,20 +82,13 @@ export function useNostr() {
try {
if (!ndk) return { status: 'failed', message: 'NDK instance not found' };
const until = since === 24 ? Math.floor(Date.now() / 1000) : nHoursAgo(since / 2);
console.log('fetch events since: ', since);
console.log('fetch events until: ', until);
/*
const events = await ndk.fetchEvents({
kinds: [1],
authors: db.account.network ?? db.account.follows,
since: since,
until: until,
since: nHoursAgo(since),
});
*/
return { status: 'ok', data: [], nextCursor: since * 2 };
return { status: 'ok', data: [...events], nextCursor: since * 2 };
} catch (e) {
console.error('failed get notes, error: ', e);
return { status: 'failed', data: [], message: e };

View File

@@ -1,7 +1,6 @@
import { useQuery } from '@tanstack/react-query';
import { useNDK } from '@libs/ndk/provider';
import { createMetadata } from '@libs/storage';
export function useProfile(pubkey: string, fallback?: string) {
const { ndk } = useNDK();
@@ -18,7 +17,6 @@ export function useProfile(pubkey: string, fallback?: string) {
await user.fetchProfile();
if (user.profile) {
user.profile.display_name = user.profile.displayName;
await createMetadata(user.npub, pubkey, JSON.stringify(user.profile));
return user.profile;
} else {
throw new Error('User not found');
@@ -29,6 +27,7 @@ export function useProfile(pubkey: string, fallback?: string) {
}
},
{
enabled: !!ndk,
staleTime: Infinity,
refetchOnMount: false,
refetchOnWindowFocus: false,

View File

@@ -1,10 +1,8 @@
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useNDK } from '@libs/ndk/provider';
import { createNote } from '@libs/storage';
import { useStorage } from '@libs/storage/provider';
import { nHoursAgo } from '@utils/date';
import { useAccount } from '@utils/hooks/useAccount';
import { useNostr } from '@utils/hooks/useNostr';
export function useSocial() {
@@ -12,12 +10,12 @@ export function useSocial() {
const { publish } = useNostr();
const { ndk } = useNDK();
const { account } = useAccount();
const { db } = useStorage();
const { status, data: userFollows } = useQuery(
['userFollows', account.pubkey],
['userFollows', db.account.pubkey],
async () => {
const keys = [];
const user = ndk.getUser({ hexpubkey: account.pubkey });
const user = ndk.getUser({ hexpubkey: db.account.pubkey });
const follows = await user.follows();
follows.forEach((item) => {
@@ -27,7 +25,6 @@ export function useSocial() {
return keys;
},
{
enabled: account ? true : false,
refetchOnReconnect: false,
refetchOnMount: false,
refetchOnWindowFocus: false,
@@ -47,7 +44,7 @@ export function useSocial() {
publish({ content: '', kind: 3, tags: tags });
// invalid cache
queryClient.invalidateQueries({
queryKey: ['userFollows', account.pubkey],
queryKey: ['userFollows', db.account.pubkey],
});
};
@@ -64,26 +61,8 @@ export function useSocial() {
publish({ content: '', kind: 3, tags: tags });
// invalid cache
queryClient.invalidateQueries({
queryKey: ['userFollows', account.pubkey],
queryKey: ['userFollows', db.account.pubkey],
});
// fetch events
const events = await ndk.fetchEvents({
authors: [pubkey],
kinds: [1, 6],
since: nHoursAgo(24),
});
for (const event of events) {
await createNote(
event.id,
event.pubkey,
event.kind,
event.tags,
event.content,
event.created_at
);
}
};
return { status, userFollows, follow, unfollow };

View File

@@ -2,7 +2,7 @@ import getUrls from 'get-urls';
import { Event, parseReferences } from 'nostr-tools';
import ReactPlayer from 'react-player';
import { Content, LumeEvent } from '@utils/types';
import { LumeEvent, RichContent } from '@utils/types';
export function parser(event: LumeEvent) {
if (event.kind !== 1) return;
@@ -10,8 +10,7 @@ export function parser(event: LumeEvent) {
const references = parseReferences(event as unknown as Event);
const urls = getUrls(event.content as unknown as string);
const content: Content = {
original: event.content as unknown as string,
const content: RichContent = {
parsed: event.content as unknown as string,
notes: [],
images: [],

View File

@@ -1,5 +1,5 @@
import { NDKTag } from '@nostr-dev-kit/ndk';
import destr from 'destr';
import { destr } from 'destr';
import { nip19 } from 'nostr-tools';
export function truncateContent(str, n) {

View File

@@ -1,7 +1,6 @@
import { NDKEvent, NDKUserProfile } from '@nostr-dev-kit/ndk';
export interface Content {
original: string;
export interface RichContent {
parsed: string;
notes: string[];
images: string[];
@@ -10,10 +9,7 @@ export interface Content {
}
export interface LumeEvent extends NDKEvent {
event_id?: string;
parent_id?: string;
replies?: LumeEvent[];
content: Content;
richContent: RichContent;
}
export interface Account extends NDKUserProfile {