completed migrate to tauri-sql

This commit is contained in:
Ren Amamiya
2023-04-18 19:15:04 +07:00
parent fc1101f97b
commit c72798507e
40 changed files with 321 additions and 476 deletions

View File

@@ -13,7 +13,7 @@ import { Suspense, useContext, useEffect, useRef } from 'react';
export default function Page({ params }: { params: { id: string } }) {
const [pool, relays]: any = useContext(RelayContext);
const [activeAccount]: any = useLocalStorage('activeAccount', {});
const [activeAccount]: any = useLocalStorage('account', {});
const setChannelMessages = useSetAtom(channelMessagesAtom);
const resetChannelMessages = useResetAtom(channelMessagesAtom);

View File

@@ -2,18 +2,15 @@
import { BrowseChannelItem } from '@components/channels/browseChannelItem';
import { getChannels } from '@utils/storage';
import { useEffect, useState } from 'react';
export default function Page() {
const [list, setList] = useState([]);
useEffect(() => {
const fetchChannels = async () => {
const { getChannels } = await import('@utils/bindings');
return await getChannels({ limit: 100, offset: 0 });
};
fetchChannels()
getChannels(100, 0)
.then((res) => setList(res))
.catch(console.error);
}, []);

View File

@@ -13,7 +13,7 @@ import { Suspense, useCallback, useContext, useEffect, useRef } from 'react';
export default function Page({ params }: { params: { pubkey: string } }) {
const [pool, relays]: any = useContext(RelayContext);
const [activeAccount]: any = useLocalStorage('activeAccount', {});
const [activeAccount]: any = useLocalStorage('account', {});
const setChatMessages = useSetAtom(chatMessagesAtom);
const resetChatMessages = useResetAtom(chatMessagesAtom);

View File

@@ -8,6 +8,7 @@ import { NoteQuoteRepost } from '@components/note/quoteRepost';
import { filteredNotesAtom, hasNewerNoteAtom, notesAtom } from '@stores/note';
import { dateToUnix } from '@utils/getDate';
import { getLatestNotes, getNotes } from '@utils/storage';
import { ArrowUp } from 'iconoir-react';
import { useAtom, useAtomValue, useSetAtom } from 'jotai';
@@ -40,43 +41,28 @@ export default function Page() {
const computeItemKey = useCallback(
(index: string | number) => {
return data[index].eventId;
return data[index].event_id;
},
[data]
);
const initialData = useCallback(async () => {
const { getNotes } = await import('@utils/bindings');
const result: any = await getNotes({
date: dateToUnix(now.current),
limit: limit.current,
offset: offset.current,
});
const result = await getNotes(dateToUnix(now.current), limit.current, offset.current);
setData((data) => [...data, ...result]);
}, [setData]);
const loadMore = useCallback(async () => {
const { getNotes } = await import('@utils/bindings');
offset.current += limit.current;
// next query
const result: any = await getNotes({
date: dateToUnix(now.current),
limit: limit.current,
offset: offset.current,
});
// query next page
const result = await getNotes(dateToUnix(now.current), limit.current, offset.current);
setData((data) => [...data, ...result]);
}, [setData]);
const loadLatest = useCallback(async () => {
const { getLatestNotes } = await import('@utils/bindings');
// next query
const result: any = await getLatestNotes({ date: dateToUnix(now.current) });
const result = await getLatestNotes(dateToUnix(now.current));
// update data
if (Array.isArray(result)) {
setData((data) => [...result, ...data]);
} else {
setData((data) => [result, ...data]);
}
setData((data) => [...result, ...data]);
// hide newer trigger
setHasNewerNote(false);
// scroll to top

View File

@@ -73,10 +73,11 @@ export default function Page({ params }: { params: { slug: string } }) {
// save follows to database then broadcast
const submit = useCallback(async () => {
setLoading(true);
const nip02 = arrayToNIP02(follows);
// update account's folllows with nip03 tag list
updateAccount('follows', nip02, pubkey);
// update account's folllows with NIP-02 tag list
updateAccount('follows', follows, pubkey);
// create pleb
for (const tag of follows) {
@@ -93,7 +94,6 @@ export default function Page({ params }: { params: { slug: string } }) {
pubkey: pubkey,
tags: nip02,
};
console.log(event);
event.id = getEventHash(event);
event.sig = signEvent(event, privkey);
// broadcast

View File

@@ -6,7 +6,8 @@ import { DEFAULT_AVATAR } from '@stores/constants';
import { fetchProfileMetadata } from '@utils/hooks/useProfileMetadata';
import { shortenKey } from '@utils/shortenKey';
import { createAccount, createPleb } from '@utils/storage';
import { createAccount, createPleb, updateAccount } from '@utils/storage';
import { nip02ToArray } from '@utils/transform';
import Image from 'next/image';
import { useRouter } from 'next/navigation';
@@ -26,7 +27,7 @@ export default function Page({ params }: { params: { privkey: string } }) {
const createPlebs = useCallback(async (tags: string[]) => {
for (const tag of tags) {
fetchProfileMetadata(tag[1])
.then((res: any) => createPleb(tag[1], res))
.then((res: any) => createPleb(tag[1], res.content))
.catch(console.error);
}
}, []);
@@ -37,6 +38,7 @@ export default function Page({ params }: { params: { privkey: string } }) {
{
authors: [pubkey],
kinds: [0, 3],
since: 0,
},
],
relays,
@@ -46,11 +48,14 @@ export default function Page({ params }: { params: { privkey: string } }) {
createAccount(pubkey, params.privkey, event.content);
// update state
setProfile({
metadata: JSON.parse(event.metadata),
metadata: JSON.parse(event.content),
});
} else {
if (event.tags.length > 0) {
createPlebs(event.tags);
const arr = nip02ToArray(event.tags);
// update account's folllows with NIP-02 tag list
updateAccount('follows', arr, pubkey);
}
}
},

View File

@@ -2,7 +2,7 @@
import { CableTag } from 'iconoir-react';
import { useRouter } from 'next/navigation';
import { nip19 } from 'nostr-tools';
import { getPublicKey, nip19 } from 'nostr-tools';
import { Resolver, useForm } from 'react-hook-form';
type FormValues = {
@@ -33,14 +33,15 @@ export default function Page() {
} = useForm<FormValues>({ resolver });
const onSubmit = async (data: any) => {
let privkey = data['key'];
if (privkey.substring(0, 4) === 'nsec') {
privkey = nip19.decode(privkey).data;
}
try {
router.push(`/onboarding/login/${privkey}`);
let privkey = data['key'];
if (privkey.substring(0, 4) === 'nsec') {
privkey = nip19.decode(privkey).data;
}
if (typeof getPublicKey(privkey) === 'string') {
router.push(`/onboarding/login/${privkey}`);
}
} catch (error) {
setError('key', {
type: 'custom',
@@ -75,7 +76,7 @@ export default function Page() {
<span className="bg-black px-2 text-sm text-zinc-500">or</span>
</div>
</div>
<div className="flex flex-col gap-2">
<div className="flex flex-col gap-0.5">
<div className="relative shrink-0 before:pointer-events-none before:absolute before:-inset-1 before:rounded-[11px] before:border before:border-blue-500 before:opacity-0 before:ring-2 before:ring-blue-500/20 before:transition after:pointer-events-none after:absolute after:inset-px after:rounded-[7px] after:shadow-highlight after:shadow-white/5 after:transition focus-within:before:opacity-100 focus-within:after:shadow-blue-500/100 dark:focus-within:after:shadow-blue-500/20">
<input
{...register('key', { required: true, minLength: 32 })}
@@ -84,10 +85,10 @@ export default function Page() {
className="relative w-full rounded-lg border border-black/5 px-3.5 py-2.5 text-center shadow-input shadow-black/5 !outline-none placeholder:text-zinc-400 dark:bg-zinc-800 dark:text-zinc-200 dark:shadow-black/10 dark:placeholder:text-zinc-500"
/>
</div>
<span className="text-sm text-red-400">{errors.key && <p>{errors.key.message}</p>}</span>
<span className="text-xs text-red-400">{errors.key && <p>{errors.key.message}</p>}</span>
</div>
</div>
<div className="mt-1 flex h-10 items-center justify-center">
<div className="mt-3 flex h-10 items-center justify-center">
{isSubmitting ? (
<svg
className="h-5 w-5 animate-spin text-white"

View File

@@ -3,8 +3,16 @@
import { RelayContext } from '@components/relaysProvider';
import { dateToUnix, hoursAgo } from '@utils/getDate';
import { getActiveAccount } from '@utils/storage';
import { getParentID, pubkeyArray } from '@utils/transform';
import {
countTotalChannels,
countTotalNotes,
createChannel,
createChat,
createNote,
getActiveAccount,
getPlebs,
} from '@utils/storage';
import { getParentID, nip02ToArray } from '@utils/transform';
import LumeSymbol from '@assets/icons/Lume';
@@ -22,48 +30,24 @@ export default function Page() {
const eose = useRef(0);
const unsubscribe = useRef(null);
const fetchPlebsByAccount = useCallback(async (id: number, kind: number) => {
const { getPlebs } = await import('@utils/bindings');
return await getPlebs({ account_id: id, kind: kind });
}, []);
const totalNotes = useCallback(async () => {
const { countTotalNotes } = await import('@utils/commands');
return countTotalNotes();
}, []);
const totalChannels = useCallback(async () => {
const { countTotalChannels } = await import('@utils/commands');
return countTotalChannels();
}, []);
const totalChats = useCallback(async () => {
const { countTotalChats } = await import('@utils/commands');
return countTotalChats();
}, []);
const fetchData = useCallback(
async (account) => {
const { createNote } = await import('@utils/bindings');
const { createChat } = await import('@utils/bindings');
const { createChannel } = await import('@utils/bindings');
const notes = await totalNotes();
const channels = await totalChannels();
const chats = await totalChats();
async (account: { id: number; pubkey: string; chats: string[] }, follows: any) => {
const notes = await countTotalNotes();
const channels = await countTotalChannels();
const chats = account.chats?.length || 0;
const query = [];
let since: number;
// kind 1 (notes) query
if (notes === 0) {
if (notes.total === 0) {
since = dateToUnix(hoursAgo(24, now.current));
} else {
since = dateToUnix(new Date(lastLogin));
}
query.push({
kinds: [1, 6],
authors: account.follows,
authors: JSON.parse(follows),
since: since,
until: dateToUnix(now.current),
});
@@ -77,7 +61,7 @@ export default function Page() {
});
}
// kind 40 (channels) query
if (channels === 0) {
if (channels.total === 0) {
query.push({
kinds: [40],
since: 0,
@@ -88,51 +72,46 @@ export default function Page() {
unsubscribe.current = pool.subscribe(
query,
relays,
(event) => {
(event: { kind: number; tags: string[]; id: string; pubkey: string; content: string; created_at: number }) => {
switch (event.kind) {
// short text note
case 1:
const parentID = getParentID(event.tags, event.id);
// insert event to local database
createNote({
event_id: event.id,
pubkey: event.pubkey,
kind: event.kind,
tags: JSON.stringify(event.tags),
content: event.content,
parent_id: parentID,
parent_comment_id: '',
created_at: event.created_at,
account_id: account.id,
}).catch(console.error);
createNote(
event.id,
account.id,
event.pubkey,
event.kind,
event.tags,
event.content,
event.created_at,
parentID
);
break;
// chat
case 4:
if (event.pubkey !== account.pubkey) {
createChat({
pubkey: event.pubkey,
created_at: event.created_at,
account_id: account.id,
}).catch(console.error);
createChat(account.id, event.pubkey, event.created_at);
}
break;
// repost
case 6:
createNote({
event_id: event.id,
pubkey: event.pubkey,
kind: event.kind,
tags: JSON.stringify(event.tags),
content: event.content,
parent_id: '',
parent_comment_id: '',
created_at: event.created_at,
account_id: account.id,
}).catch(console.error);
createNote(
event.id,
account.id,
event.pubkey,
event.kind,
event.tags,
event.content,
event.created_at,
''
);
break;
// channel
case 40:
createChannel({ event_id: event.id, content: event.content, account_id: account.id }).catch(
console.error
);
createChannel(event.id, event.content, event.created_at);
break;
default:
break;
}
@@ -151,18 +130,26 @@ export default function Page() {
}
);
},
[router, pool, relays, lastLogin, totalChannels, totalChats, totalNotes]
[router, pool, relays, lastLogin]
);
useEffect(() => {
getPlebs()
.then((res) => {
if (res) {
writeStorage('plebs', res);
}
})
.catch(console.error);
getActiveAccount()
.then((res: any) => {
if (res) {
const account = res;
// update local storage
writeStorage('activeAccount', account);
writeStorage('account', account);
// fetch data
fetchData(account);
fetchData(account, account.follows);
} else {
router.replace('/onboarding');
}