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

@ -0,0 +1,10 @@
-- Add migration script here
-- create chats table
CREATE TABLE
chats (
id INTEGER NOT NULL PRIMARY KEY,
account_id INTEGER NOT NULL,
pubkey TEXT NOT NULL UNIQUE,
created_at INTEGER NOT NULL,
FOREIGN KEY (account_id) REFERENCES accounts (id)
);

View File

@ -50,12 +50,20 @@ fn main() {
tauri_plugin_sql::Builder::default()
.add_migrations(
"sqlite:lume.db",
vec![Migration {
version: 20230418013219,
description: "initial data",
sql: include_str!("../migrations/20230418013219_initial_data.sql"),
kind: MigrationKind::Up,
}],
vec![
Migration {
version: 20230418013219,
description: "initial data",
sql: include_str!("../migrations/20230418013219_initial_data.sql"),
kind: MigrationKind::Up,
},
Migration {
version: 20230418080146,
description: "create chats",
sql: include_str!("../migrations/20230418080146_create_chats.sql"),
kind: MigrationKind::Up,
},
],
)
.build(),
)

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');
}

View File

@ -16,19 +16,9 @@ export const BrowseChannelItem = ({ data }: { data: any }) => {
[router]
);
const joinChannel = useCallback(
async (id: string) => {
const { updateChannel } = await import('@utils/bindings');
updateChannel({ event_id: id, active: true })
.then(() => openChannel(id))
.catch(console.error);
},
[openChannel]
);
return (
<div
onClick={() => openChannel(data.eventId)}
onClick={() => openChannel(data.event_id)}
className="group relative flex items-center gap-2 border-b border-zinc-800 px-3 py-2.5 hover:bg-black/20"
>
<div className="relative h-11 w-11 shrink overflow-hidden rounded-md border border-white/10">
@ -44,10 +34,7 @@ export const BrowseChannelItem = ({ data }: { data: any }) => {
<span className="text-sm leading-tight text-zinc-400">{channel.about}</span>
</div>
<div className="absolute right-2 top-1/2 hidden -translate-y-1/2 transform group-hover:inline-flex">
<button
onClick={() => joinChannel(data.eventId)}
className="inline-flex h-8 w-16 items-center justify-center rounded-md bg-fuchsia-500 px-4 text-sm font-medium shadow-button hover:bg-fuchsia-600 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50"
>
<button className="inline-flex h-8 w-16 items-center justify-center rounded-md bg-fuchsia-500 px-4 text-sm font-medium shadow-button hover:bg-fuchsia-600 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50">
Join
</button>
</div>

View File

@ -3,21 +3,10 @@ import { CreateChannelModal } from '@components/channels/createChannelModal';
import { Globe } from 'iconoir-react';
import Link from 'next/link';
import { useEffect, useState } from 'react';
import { useState } from 'react';
export default function ChannelList() {
const [list, setList] = useState([]);
useEffect(() => {
const fetchChannels = async () => {
const { getActiveChannels } = await import('@utils/bindings');
return await getActiveChannels({ active: true });
};
fetchChannels()
.then((res) => setList(res))
.catch(console.error);
}, []);
const [list] = useState([]);
return (
<div className="flex flex-col gap-px">

View File

@ -8,14 +8,14 @@ export const ChannelListItem = ({ data }: { data: any }) => {
return (
<ActiveLink
href={`/nostr/channels/${data.eventId}`}
href={`/nostr/channels/${data.event_id}`}
activeClassName="dark:bg-zinc-900 dark:text-zinc-100 hover:dark:bg-zinc-800"
className="inline-flex items-center gap-2 rounded-md px-2.5 py-1.5 hover:bg-zinc-900"
>
<div className="relative h-5 w-5 shrink-0 overflow-hidden rounded">
<ImageWithFallback
src={channel?.picture || DEFAULT_AVATAR}
alt={data.eventId}
alt={data.event_id}
fill={true}
className="rounded object-cover"
/>

View File

@ -6,14 +6,13 @@ import * as Dialog from '@radix-ui/react-dialog';
import useLocalStorage from '@rehooks/local-storage';
import { Cancel, Plus } from 'iconoir-react';
import { getEventHash, signEvent } from 'nostr-tools';
import { useCallback, useContext, useState } from 'react';
import { useContext, useState } from 'react';
import { useForm } from 'react-hook-form';
export const CreateChannelModal = () => {
const [pool, relays]: any = useContext(RelayContext);
const [open, setOpen] = useState(false);
const [activeAccount]: any = useLocalStorage('activeAccount', {});
const [activeAccount]: any = useLocalStorage('account', {});
const {
register,
@ -22,11 +21,6 @@ export const CreateChannelModal = () => {
formState: { isDirty, isValid },
} = useForm();
const insertChannelToDB = useCallback(async (id, data, account) => {
const { createChannel } = await import('@utils/bindings');
return await createChannel({ event_id: id, content: data, account_id: account });
}, []);
const onSubmit = (data) => {
const event: any = {
content: JSON.stringify(data),
@ -40,8 +34,6 @@ export const CreateChannelModal = () => {
// publish channel
pool.publish(event, relays);
// save to database
insertChannelToDB(event.id, data, activeAccount.id);
// close modal
setOpen(false);
// reset form

View File

@ -11,7 +11,7 @@ import { useCallback, useContext } from 'react';
export const HideMessageButton = ({ id }: { id: string }) => {
const [pool, relays]: any = useContext(RelayContext);
const [activeAccount]: any = useLocalStorage('activeAccount', {});
const [activeAccount]: any = useLocalStorage('account', {});
const hideMessage = useCallback(() => {
const event: any = {

View File

@ -11,7 +11,7 @@ import { useCallback, useContext } from 'react';
export const MuteButton = ({ pubkey }: { pubkey: string }) => {
const [pool, relays]: any = useContext(RelayContext);
const [activeAccount]: any = useLocalStorage('activeAccount', {});
const [activeAccount]: any = useLocalStorage('account', {});
const muteUser = useCallback(() => {
const event: any = {

View File

@ -4,6 +4,8 @@ import { ImageWithFallback } from '@components/imageWithFallback';
import { DEFAULT_AVATAR } from '@stores/constants';
import { getChats } from '@utils/storage';
import useLocalStorage from '@rehooks/local-storage';
import { useRouter } from 'next/navigation';
import { useEffect, useState } from 'react';
@ -12,7 +14,7 @@ export default function ChatList() {
const router = useRouter();
const [list, setList] = useState([]);
const [activeAccount]: any = useLocalStorage('activeAccount', {});
const [activeAccount]: any = useLocalStorage('account', {});
const profile = activeAccount.metadata ? JSON.parse(activeAccount.metadata) : null;
const openSelfChat = () => {
@ -20,12 +22,7 @@ export default function ChatList() {
};
useEffect(() => {
const fetchChats = async () => {
const { getChats } = await import('@utils/bindings');
return await getChats({ account_id: activeAccount.id });
};
fetchChats()
getChats(activeAccount.id)
.then((res) => setList(res))
.catch(console.error);
}, [activeAccount.id]);

View File

@ -1,24 +1,19 @@
import { ChatModalUser } from '@components/chats/chatModalUser';
import { getPlebs } from '@utils/storage';
import * as Dialog from '@radix-ui/react-dialog';
import useLocalStorage from '@rehooks/local-storage';
import { Cancel, Plus } from 'iconoir-react';
import { useCallback, useEffect, useState } from 'react';
import { useEffect, useState } from 'react';
export const ChatModal = () => {
const [plebs, setPlebs] = useState([]);
const [activeAccount]: any = useLocalStorage('activeAccount', {});
const fetchPlebsByAccount = useCallback(async (id) => {
const { getPlebs } = await import('@utils/bindings');
return await getPlebs({ account_id: id, kind: 0 });
}, []);
useEffect(() => {
fetchPlebsByAccount(activeAccount.id)
getPlebs()
.then((res) => setPlebs(res))
.catch(console.error);
}, [activeAccount.id, fetchPlebsByAccount]);
}, []);
return (
<Dialog.Root>

View File

@ -9,7 +9,7 @@ import { useCallback, useRef } from 'react';
import { Virtuoso } from 'react-virtuoso';
export const MessageList = () => {
const [activeAccount]: any = useLocalStorage('activeAccount', {});
const [activeAccount]: any = useLocalStorage('account', {});
const virtuosoRef = useRef(null);
const data = useAtomValue(sortedChatMessagesAtom);

View File

@ -6,8 +6,8 @@ import { RelayContext } from '@components/relaysProvider';
import { hasNewerNoteAtom } from '@stores/note';
import { dateToUnix } from '@utils/getDate';
import { fetchProfileMetadata } from '@utils/hooks/useProfileMetadata';
import { getParentID, pubkeyArray } from '@utils/transform';
import { createChannel, createChat, createNote, updateAccount } from '@utils/storage';
import { getParentID, nip02ToArray } from '@utils/transform';
import useLocalStorage, { writeStorage } from '@rehooks/local-storage';
import { window } from '@tauri-apps/api';
@ -17,46 +17,19 @@ import { useCallback, useContext, useEffect, useRef } from 'react';
export default function EventCollector() {
const [pool, relays]: any = useContext(RelayContext);
const [activeAccount]: any = useLocalStorage('activeAccount', {});
const [follows] = useLocalStorage('activeAccountFollows', []);
const [activeAccount]: any = useLocalStorage('account', {});
const setHasNewerNote = useSetAtom(hasNewerNoteAtom);
const now = useRef(new Date());
const unsubscribe = useRef(null);
const createFollowingPlebs = useCallback(
async (tags) => {
const { createPleb } = await import('@utils/bindings');
for (const tag of tags) {
const pubkey = tag[1];
fetchProfileMetadata(pubkey)
.then((res: { content: string }) => {
createPleb({
pleb_id: pubkey + '-lume' + activeAccount.id.toString(),
pubkey: pubkey,
kind: 0,
metadata: res.content,
account_id: activeAccount.id,
}).catch(console.error);
})
.catch(console.error);
}
},
[activeAccount.id]
);
const subscribe = useCallback(async () => {
const { createNote } = await import('@utils/bindings');
const { createChat } = await import('@utils/bindings');
const { createChannel } = await import('@utils/bindings');
unsubscribe.current = pool.subscribe(
[
{
kinds: [1, 6],
authors: pubkeyArray(follows),
authors: activeAccount.follows,
since: dateToUnix(now.current),
},
{
@ -79,65 +52,54 @@ export default function EventCollector() {
// short text note
case 1:
const parentID = getParentID(event.tags, event.id);
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: activeAccount.id,
})
.then(() =>
// notify user reload to get newer note
setHasNewerNote(true)
)
.catch(console.error);
createNote(
event.id,
activeAccount.id,
event.pubkey,
event.kind,
event.tags,
event.content,
event.created_at,
parentID
);
// notify user reload to get newer note
setHasNewerNote(true);
break;
// contacts
case 3:
createFollowingPlebs(event.tags);
const arr = nip02ToArray(event.tags);
// update account's folllows with NIP-02 tag list
updateAccount('follows', arr, event.pubkey);
break;
// chat
case 4:
if (event.pubkey !== activeAccount.pubkey) {
createChat({
pubkey: event.pubkey,
created_at: event.created_at,
account_id: activeAccount.id,
}).catch(console.error);
createChat(activeAccount.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: activeAccount.id,
})
.then(() =>
// notify user reload to get newer note
setHasNewerNote(true)
)
.catch(console.error);
createNote(
event.id,
activeAccount.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: activeAccount.id }).catch(
console.error
);
createChannel(event.id, event.content, event.created_at);
break;
default:
break;
}
}
);
}, [pool, relays, activeAccount.id, activeAccount.pubkey, follows, setHasNewerNote, createFollowingPlebs]);
}, [activeAccount.follows, activeAccount.pubkey, activeAccount.id, pool, relays, setHasNewerNote]);
const listenWindowClose = useCallback(async () => {
window.getCurrent().listen(TauriEvent.WINDOW_CLOSE_REQUESTED, () => {

View File

@ -18,7 +18,7 @@ export default function FormBase() {
const [value, setValue] = useAtom(noteContentAtom);
const resetValue = useResetAtom(noteContentAtom);
const [activeAccount]: any = useLocalStorage('activeAccount', {});
const [activeAccount]: any = useLocalStorage('account', {});
const submitEvent = () => {
const event: any = {

View File

@ -17,7 +17,7 @@ export default function FormChannelMessage({ eventId }: { eventId: string | stri
const [pool, relays]: any = useContext(RelayContext);
const [value, setValue] = useState('');
const [activeAccount]: any = useLocalStorage('activeAccount', {});
const [activeAccount]: any = useLocalStorage('account', {});
const channelReply = useAtomValue(channelReplyAtom);
const resetChannelReply = useResetAtom(channelReplyAtom);

View File

@ -11,7 +11,7 @@ export default function FormChat({ receiverPubkey }: { receiverPubkey: string })
const [pool, relays]: any = useContext(RelayContext);
const [value, setValue] = useState('');
const [activeAccount]: any = useLocalStorage('activeAccount', {});
const [activeAccount]: any = useLocalStorage('account', {});
const encryptMessage = useCallback(
async (privkey: string) => {

View File

@ -10,7 +10,7 @@ import { useContext, useState } from 'react';
export default function FormComment({ eventID }: { eventID: any }) {
const [pool, relays]: any = useContext(RelayContext);
const [activeAccount]: any = useLocalStorage('activeAccount', {});
const [activeAccount]: any = useLocalStorage('account', {});
const [value, setValue] = useState('');
const profile = JSON.parse(activeAccount.metadata);

View File

@ -5,6 +5,8 @@ import { InactiveAccount } from '@components/multiAccounts/inactiveAccount';
import { APP_VERSION } from '@stores/constants';
import { getAccounts } from '@utils/storage';
import LumeSymbol from '@assets/icons/Lume';
import useLocalStorage from '@rehooks/local-storage';
@ -14,7 +16,7 @@ import { useCallback, useEffect, useState } from 'react';
export default function MultiAccounts() {
const [users, setUsers] = useState([]);
const [activeAccount]: any = useLocalStorage('activeAccount', {});
const [activeAccount]: any = useLocalStorage('account', {});
const renderAccount = useCallback(
(user: { pubkey: string }) => {
@ -27,16 +29,11 @@ export default function MultiAccounts() {
[activeAccount.pubkey]
);
const fetchAccounts = useCallback(async () => {
const { getAccounts } = await import('@utils/bindings');
const accounts = await getAccounts();
// update state
setUsers(accounts);
}, []);
useEffect(() => {
fetchAccounts().catch(console.error);
}, [fetchAccounts]);
getAccounts()
.then((res) => setUsers(res))
.catch(console.error);
}, []);
return (
<div className="flex h-full flex-col items-center justify-between px-2 pb-4 pt-3">

View File

@ -13,7 +13,7 @@ export const NoteBase = memo(function NoteBase({ event }: { event: any }) {
const parentNote = () => {
if (event.parent_id) {
if (event.parent_id !== event.eventId && !event.content.includes('#[0]')) {
if (event.parent_id !== event.event_id && !event.content.includes('#[0]')) {
return <NoteParent key={event.parent_id} id={event.parent_id} />;
}
}
@ -42,17 +42,17 @@ export const NoteBase = memo(function NoteBase({ event }: { event: any }) {
{parentNote()}
<div className="relative z-10 flex flex-col">
<div onClick={(e) => openUserPage(e)}>
<UserExtend pubkey={event.pubkey} time={event.createdAt || event.created_at} />
<UserExtend pubkey={event.pubkey} time={event.created_at} />
</div>
<div className="mt-1 pl-[52px]">
<div className="whitespace-pre-line break-words text-[15px] leading-tight text-zinc-100">{content}</div>
</div>
<div onClick={(e) => e.stopPropagation()} className="mt-5 pl-[52px]">
<NoteMetadata
eventID={event.eventId}
eventID={event.event_id}
eventPubkey={event.pubkey}
eventContent={event.content}
eventTime={event.createdAt || event.created_at}
eventTime={event.created_at}
/>
</div>
</div>

View File

@ -60,7 +60,7 @@ export const NoteComment = memo(function NoteComment({ event }: { event: any })
return (
<div className="relative z-10 flex h-min min-h-min w-full select-text flex-col border-b border-zinc-800 px-3 py-5 hover:bg-black/20">
<div className="relative z-10 flex flex-col">
<UserExtend pubkey={event.pubkey} time={event.createdAt || event.created_at} />
<UserExtend pubkey={event.pubkey} time={event.created_at} />
<div className="-mt-5 pl-[52px]">
<div className="flex flex-col gap-2">
<div className="prose prose-zinc max-w-none break-words text-[15px] leading-tight dark:prose-invert prose-p:m-0 prose-p:text-[15px] prose-p:leading-tight prose-a:font-normal prose-a:text-fuchsia-500 prose-a:no-underline prose-img:m-0 prose-video:m-0">
@ -70,10 +70,10 @@ export const NoteComment = memo(function NoteComment({ event }: { event: any })
</div>
<div onClick={(e) => e.stopPropagation()} className="mt-5 pl-[52px]">
<NoteMetadata
eventID={event.eventId}
eventID={event.event_id}
eventPubkey={event.pubkey}
eventContent={event.content}
eventTime={event.createdAt || event.created_at}
eventTime={event.created_at}
/>
</div>
</div>

View File

@ -60,7 +60,7 @@ export const NoteExtend = memo(function NoteExtend({ event }: { event: any }) {
return (
<div className="relative z-10 flex h-min min-h-min w-full select-text flex-col">
<div className="relative z-10 flex flex-col">
<UserLarge pubkey={event.pubkey} time={event.createdAt || event.created_at} />
<UserLarge pubkey={event.pubkey} time={event.created_at} />
<div className="mt-2">
<div className="flex flex-col gap-2">
<div className="prose prose-zinc max-w-none break-words text-[15px] leading-tight dark:prose-invert prose-p:m-0 prose-p:text-[15px] prose-p:leading-tight prose-a:font-normal prose-a:text-fuchsia-500 prose-a:no-underline prose-img:m-0 prose-video:m-0">
@ -70,10 +70,10 @@ export const NoteExtend = memo(function NoteExtend({ event }: { event: any }) {
</div>
<div className="mt-5 flex items-center border-b border-t border-zinc-800 py-2">
<NoteMetadata
eventID={event.eventId}
eventID={event.event_id}
eventPubkey={event.pubkey}
eventContent={event.content}
eventTime={event.createdAt || event.created_at}
eventTime={event.created_at}
/>
</div>
</div>

View File

@ -30,7 +30,7 @@ export const NoteComment = ({
const [open, setOpen] = useState(false);
const [value, setValue] = useState('');
const [activeAccount]: any = useLocalStorage('activeAccount', {});
const [activeAccount]: any = useLocalStorage('account', {});
const profile = activeAccount.metadata ? JSON.parse(activeAccount.metadata) : null;
const openThread = () => {

View File

@ -19,7 +19,7 @@ export const NoteReaction = ({
eventPubkey: string;
}) => {
const [pool, relays]: any = useContext(RelayContext);
const [activeAccount]: any = useLocalStorage('activeAccount', {});
const [activeAccount]: any = useLocalStorage('account', {});
const [isReact, setIsReact] = useState(false);
const [like, setLike] = useState(0);

View File

@ -17,7 +17,7 @@ export const NoteMetadata = memo(function NoteMetadata({
eventContent: any;
}) {
const [pool, relays]: any = useContext(RelayContext);
const [activeAccount]: any = useLocalStorage('activeAccount', {});
const [activeAccount]: any = useLocalStorage('account', {});
const [liked, setLiked] = useState(false);
const [likeCount, setLikeCount] = useState(0);

View File

@ -3,6 +3,7 @@ import { RelayContext } from '@components/relaysProvider';
import { UserExtend } from '@components/user/extend';
import { contentParser } from '@utils/parser';
import { createNote, getNoteByID } from '@utils/storage';
import { getParentID } from '@utils/transform';
import useLocalStorage from '@rehooks/local-storage';
@ -11,14 +12,13 @@ import { memo, useCallback, useContext, useEffect, useRef, useState } from 'reac
export const NoteParent = memo(function NoteParent({ id }: { id: string }) {
const [pool, relays]: any = useContext(RelayContext);
const [activeAccount]: any = useLocalStorage('activeAccount', {});
const [activeAccount]: any = useLocalStorage('account', {});
const [event, setEvent] = useState(null);
const unsubscribe = useRef(null);
const content = event ? contentParser(event.content, event.tags) : '';
const fetchEvent = useCallback(async () => {
const { createNote } = await import('@utils/bindings');
unsubscribe.current = pool.subscribe(
[
{
@ -33,17 +33,16 @@ export const NoteParent = memo(function NoteParent({ id }: { id: string }) {
// insert to database
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: activeAccount.id,
}).catch(console.error);
createNote(
event.id,
activeAccount.id,
event.pubkey,
event.kind,
event.tags,
event.content,
event.created_at,
parentID
);
},
undefined,
undefined,
@ -54,8 +53,7 @@ export const NoteParent = memo(function NoteParent({ id }: { id: string }) {
}, [activeAccount.id, id, pool, relays]);
const checkNoteExist = useCallback(async () => {
const { getNoteById } = await import('@utils/bindings');
getNoteById({ event_id: id })
getNoteByID(id)
.then((res) => {
if (res) {
setEvent(res);
@ -81,16 +79,16 @@ export const NoteParent = memo(function NoteParent({ id }: { id: string }) {
<div className="relative pb-5">
<div className="absolute left-[21px] top-0 h-full w-0.5 bg-gradient-to-t from-zinc-800 to-zinc-600"></div>
<div className="relative z-10 flex flex-col">
<UserExtend pubkey={event.pubkey} time={event.createdAt || event.created_at} />
<UserExtend pubkey={event.pubkey} time={event.created_at} />
<div className="mt-1 pl-[52px]">
<div className="whitespace-pre-line break-words text-[15px] leading-tight text-zinc-100">{content}</div>
</div>
<div onClick={(e) => e.stopPropagation()} className="mt-5 pl-[52px]">
<NoteMetadata
eventID={event.eventId}
eventID={event.event_id}
eventPubkey={event.pubkey}
eventContent={event.content}
eventTime={event.createdAt || event.created_at}
eventTime={event.created_at}
/>
</div>
</div>

View File

@ -2,6 +2,7 @@ import { RelayContext } from '@components/relaysProvider';
import { UserExtend } from '@components/user/extend';
import { contentParser } from '@utils/parser';
import { createNote, getNoteByID } from '@utils/storage';
import { getParentID } from '@utils/transform';
import useLocalStorage from '@rehooks/local-storage';
@ -10,15 +11,13 @@ import { memo, useCallback, useContext, useEffect, useRef, useState } from 'reac
export const NoteQuote = memo(function NoteQuote({ id }: { id: string }) {
const [pool, relays]: any = useContext(RelayContext);
const [activeAccount]: any = useLocalStorage('activeAccount', {});
const [activeAccount]: any = useLocalStorage('account', {});
const [event, setEvent] = useState(null);
const unsubscribe = useRef(null);
const content = event ? contentParser(event.content, event.tags) : '';
const fetchEvent = useCallback(async () => {
const { createNote } = await import('@utils/bindings');
unsubscribe.current = pool.subscribe(
[
{
@ -32,18 +31,16 @@ export const NoteQuote = memo(function NoteQuote({ id }: { id: string }) {
setEvent(event);
// insert to database
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: activeAccount.id,
}).catch(console.error);
createNote(
event.id,
activeAccount.id,
event.pubkey,
event.kind,
event.tags,
event.content,
event.created_at,
parentID
);
},
undefined,
undefined,
@ -54,8 +51,7 @@ export const NoteQuote = memo(function NoteQuote({ id }: { id: string }) {
}, [activeAccount.id, id, pool, relays]);
const checkNoteExist = useCallback(async () => {
const { getNoteById } = await import('@utils/bindings');
getNoteById({ event_id: id })
getNoteByID(id)
.then((res) => {
if (res) {
setEvent(res);
@ -80,7 +76,7 @@ export const NoteQuote = memo(function NoteQuote({ id }: { id: string }) {
return (
<div className="relative mb-2 mt-3 rounded-lg border border-zinc-700 bg-zinc-800 p-2 py-3">
<div className="relative z-10 flex flex-col">
<UserExtend pubkey={event.pubkey} time={event.createdAt || event.created_at} />
<UserExtend pubkey={event.pubkey} time={event.created_at} />
<div className="mt-1 pl-[52px]">
<div className="whitespace-pre-line break-words text-[15px] leading-tight text-zinc-100">{content}</div>
</div>

View File

@ -20,7 +20,7 @@ export const NoteQuoteRepost = memo(function NoteQuoteRepost({ event }: { event:
<div className="relative z-10 m-0 flex h-min min-h-min w-full select-text flex-col border-b border-zinc-800 px-3 py-5 hover:bg-black/20">
<div className="relative z-10 flex flex-col pb-8">
<div className="absolute left-[21px] top-0 h-full w-0.5 bg-gradient-to-t from-zinc-800 to-zinc-600"></div>
<UserQuoteRepost pubkey={event.pubkey} time={event.createdAt || event.created_at} />
<UserQuoteRepost pubkey={event.pubkey} time={event.created_at} />
</div>
{rootNote()}
</div>

View File

@ -16,7 +16,7 @@ const relays = [
'wss://relay.current.fyi',
'wss://nostr.bitcoiner.social',
//'wss://relay.nostr.info',
'wss://nostr-01.dorafactory.org',
//'wss://nostr-01.dorafactory.org',
'wss://nostr.zhongwen.world',
'wss://nostro.cc',
'wss://relay.nostr.net.in',

View File

@ -1,110 +0,0 @@
// This file was generated by [tauri-specta](https://github.com/oscartbeaumont/tauri-specta). Do not edit this file manually.
declare global {
interface Window {
__TAURI_INVOKE__<T>(cmd: string, args?: Record<string, unknown>): Promise<T>;
}
}
const invoke = window.__TAURI_INVOKE__;
export function getAccounts() {
return invoke<Account[]>('get_accounts');
}
export function createAccount(data: CreateAccountData) {
return invoke<Account>('create_account', { data });
}
export function getPlebs(data: GetPlebData) {
return invoke<Pleb[]>('get_plebs', { data });
}
export function getPlebByPubkey(data: GetPlebPubkeyData) {
return invoke<Pleb | null>('get_pleb_by_pubkey', { data });
}
export function createPleb(data: CreatePlebData) {
return invoke<Pleb>('create_pleb', { data });
}
export function createNote(data: CreateNoteData) {
return invoke<Note>('create_note', { data });
}
export function getNotes(data: GetNoteData) {
return invoke<Note[]>('get_notes', { data });
}
export function getLatestNotes(data: GetLatestNoteData) {
return invoke<Note[]>('get_latest_notes', { data });
}
export function getNoteById(data: GetNoteByIdData) {
return invoke<Note | null>('get_note_by_id', { data });
}
export function createChannel(data: CreateChannelData) {
return invoke<Channel>('create_channel', { data });
}
export function updateChannel(data: UpdateChannelData) {
return invoke<Channel>('update_channel', { data });
}
export function getChannels(data: GetChannelData) {
return invoke<Channel[]>('get_channels', { data });
}
export function getActiveChannels(data: GetActiveChannelData) {
return invoke<Channel[]>('get_active_channels', { data });
}
export function createChat(data: CreateChatData) {
return invoke<Chat>('create_chat', { data });
}
export function getChats(data: GetChatData) {
return invoke<Chat[]>('get_chats', { data });
}
export type GetLatestNoteData = { date: number };
export type Note = {
id: number;
eventId: string;
pubkey: string;
kind: number;
tags: string;
content: string;
parent_id: string;
parent_comment_id: string;
createdAt: number;
accountId: number;
};
export type GetActiveChannelData = { active: boolean };
export type CreateChannelData = { event_id: string; content: string; account_id: number };
export type CreateNoteData = {
event_id: string;
pubkey: string;
kind: number;
tags: string;
content: string;
parent_id: string;
parent_comment_id: string;
created_at: number;
account_id: number;
};
export type GetPlebData = { account_id: number; kind: number };
export type CreatePlebData = { pleb_id: string; pubkey: string; kind: number; metadata: string; account_id: number };
export type Chat = { id: number; pubkey: string; createdAt: number; accountId: number };
export type Account = { id: number; pubkey: string; privkey: string; active: boolean; metadata: string };
export type GetNoteByIdData = { event_id: string };
export type GetPlebPubkeyData = { pubkey: string };
export type GetChatData = { account_id: number };
export type GetNoteData = { date: number; limit: number; offset: number };
export type Channel = { id: number; eventId: string; content: string; active: boolean; accountId: number };
export type UpdateChannelData = { event_id: string; active: boolean };
export type CreateChatData = { pubkey: string; created_at: number; account_id: number };
export type CreateAccountData = { pubkey: string; privkey: string; metadata: string };
export type GetChannelData = { limit: number; offset: number };
export type Pleb = { id: number; plebId: string; pubkey: string; kind: number; metadata: string; accountId: number };

View File

@ -1,13 +0,0 @@
import { invoke } from '@tauri-apps/api';
export function countTotalNotes() {
return invoke('count_total_notes');
}
export function countTotalChannels() {
return invoke('count_total_channels');
}
export function countTotalChats() {
return invoke('count_total_chats');
}

View File

@ -1,3 +1,5 @@
import { createPleb } from '@utils/storage';
import useLocalStorage from '@rehooks/local-storage';
import { fetch } from '@tauri-apps/api/http';
import { useCallback, useEffect, useMemo, useState } from 'react';
@ -11,8 +13,8 @@ export const fetchProfileMetadata = async (pubkey: string) => {
};
export const useProfileMetadata = (pubkey) => {
const [activeAccount]: any = useLocalStorage('activeAccount', {});
const [plebs] = useLocalStorage('activeAccountFollows', []);
const [activeAccount]: any = useLocalStorage('account', {});
const [plebs] = useLocalStorage('plebs', []);
const [profile, setProfile] = useState(null);
const cacheProfile = useMemo(() => {
@ -31,19 +33,9 @@ export const useProfileMetadata = (pubkey) => {
return metadata;
}, [plebs, pubkey, activeAccount.pubkey, activeAccount.metadata]);
const insertPlebToDB = useCallback(
async (pubkey: string, metadata: string) => {
const { createPleb } = await import('@utils/bindings');
return await createPleb({
pleb_id: pubkey + '-lume' + activeAccount.id,
pubkey: pubkey,
kind: 1,
metadata: metadata,
account_id: activeAccount.id,
}).catch(console.error);
},
[activeAccount.id]
);
const insertPlebToDB = useCallback(async (pubkey: string, metadata: string) => {
return createPleb(pubkey, metadata);
}, []);
useEffect(() => {
if (!cacheProfile) {

View File

@ -20,6 +20,12 @@ export async function getActiveAccount() {
return result[0];
}
// get all accounts
export async function getAccounts() {
const db = await connect();
return await db.select(`SELECT * FROM accounts ORDER BY created_at DESC;`);
}
// create account
export async function createAccount(pubkey: string, privkey: string, metadata: string) {
const db = await connect();
@ -36,12 +42,25 @@ export async function updateAccount(column: string, value: string | string[], pu
return await db.execute(`UPDATE accounts SET ${column} = '${JSON.stringify(value)}' WHERE pubkey = "${pubkey}";`);
}
// get all plebs
export async function getPlebs() {
const db = await connect();
return await db.select(`SELECT * FROM plebs ORDER BY created_at DESC;`);
}
// create pleb
export async function createPleb(pubkey: string, metadata: string) {
const db = await connect();
return await db.execute('INSERT OR IGNORE INTO plebs (pubkey, metadata) VALUES (?, ?);', [pubkey, metadata]);
}
// count total notes
export async function countTotalChannels() {
const db = await connect();
const result = await db.select('SELECT COUNT(*) AS "total" FROM channels;');
return result[0];
}
// count total notes
export async function countTotalNotes() {
const db = await connect();
@ -50,15 +69,72 @@ export async function countTotalNotes() {
}
// get all notes
export async function getNotes(time: string, limit: number, offset: number) {
export async function getNotes(time: number, limit: number, offset: number) {
const db = await connect();
return await db.select(
`SELECT * FROM notes WHERE created_at <= "${time}" ORDER BY created_at DESC LIMIT "${limit}" OFFSET "${offset}";`
);
}
// get note by id
export async function getNoteByID(event_id) {
const db = await connect();
const result = await db.select(`SELECT * FROM notes WHERE event_id = "${event_id}";`);
return result[0];
}
// get all latest notes
export async function getLatestNotes(time) {
export async function getLatestNotes(time: number) {
const db = await connect();
return await db.select(`SELECT * FROM cache_notes WHERE created_at > "${time}" ORDER BY created_at DESC;`);
}
// create note
export async function createNote(
event_id: string,
account_id: number,
pubkey: string,
kind: number,
tags: string[],
content: string,
created_at: number,
parent_id: string
) {
const db = await connect();
return await db.execute(
'INSERT OR IGNORE INTO notes (event_id, account_id, pubkey, kind, tags, content, created_at, parent_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?);',
[event_id, account_id, pubkey, kind, tags, content, created_at, parent_id]
);
}
// get all channels
export async function getChannels(limit: number, offset: number) {
const db = await connect();
return await db.select(`SELECT * FROM channels ORDER BY created_at DESC LIMIT "${limit}" OFFSET "${offset}";`);
}
// create channel
export async function createChannel(event_id: string, metadata: string, created_at: number) {
const db = await connect();
return await db.execute('INSERT OR IGNORE INTO channels (event_id, metadata, created_at) VALUES (?, ?, ?);', [
event_id,
metadata,
created_at,
]);
}
// get all chats
export async function getChats(account_id: number) {
const db = await connect();
return await db.select(`SELECT * FROM chats WHERE account_id <= "${account_id}" ORDER BY created_at DESC;`);
}
// create chat
export async function createChat(account_id: number, pubkey: string, created_at: number) {
const db = await connect();
return await db.execute('INSERT OR IGNORE INTO chats (account_id, pubkey, created_at) VALUES (?, ?, ?);', [
account_id,
pubkey,
created_at,
]);
}

View File

@ -1,33 +1,26 @@
import destr from 'destr';
export const tagsToArray = (arr) => {
const newarr = [];
// push item to newarr
arr.forEach((item) => {
newarr.push(item[1]);
// convert NIP-02 to array of pubkey
export const nip02ToArray = (tags: string[]) => {
const arr = [];
tags.forEach((item) => {
arr.push(item[1]);
});
return newarr;
return arr;
};
// convert array to NIP-02 tag list
export const arrayToNIP02 = (arr: string[]) => {
const nip03_array = [];
const nip02_arr = [];
arr.forEach((item) => {
nip03_array.push(['p', item]);
nip02_arr.push(['p', item]);
});
return nip03_array;
return nip02_arr;
};
export const pubkeyArray = (arr) => {
const newarr = [];
// push item to newarr
arr.forEach((item) => {
newarr.push(item.pubkey);
});
return newarr;
};
export const getParentID = (arr, fallback) => {
// get parent id from event tags
export const getParentID = (arr: string[], fallback: string) => {
const tags = destr(arr);
let parentID = fallback;