update chats

This commit is contained in:
Ren Amamiya 2023-05-27 16:44:13 +07:00
parent 79e948ac05
commit ff6d494b49
11 changed files with 109 additions and 69 deletions

View File

@ -13,7 +13,11 @@ export function ChatMessageList() {
const itemContent: any = useCallback( const itemContent: any = useCallback(
(index: string | number) => { (index: string | number) => {
return ( return (
<ChatMessageItem data={messages[index]} userPrivkey={account.privkey} /> <ChatMessageItem
data={messages[index]}
userPubkey={account.pubkey}
userPrivkey={account.privkey}
/>
); );
}, },
[account.privkey, account.pubkey, messages], [account.privkey, account.pubkey, messages],

View File

@ -7,13 +7,14 @@ import { memo } from "react";
export const ChatMessageItem = memo(function ChatMessageItem({ export const ChatMessageItem = memo(function ChatMessageItem({
data, data,
userPubkey,
userPrivkey, userPrivkey,
}: { }: {
data: any; data: any;
userPubkey: string;
userPrivkey: string; userPrivkey: string;
}) { }) {
const decryptedContent = useDecryptMessage(data, userPrivkey); const decryptedContent = useDecryptMessage(data, userPubkey, userPrivkey);
console.log(decryptedContent);
// if we have decrypted content, use it instead of the encrypted content // if we have decrypted content, use it instead of the encrypted content
if (decryptedContent) { if (decryptedContent) {
data["content"] = decryptedContent; data["content"] = decryptedContent;
@ -26,7 +27,7 @@ export const ChatMessageItem = memo(function ChatMessageItem({
<div className="flex flex-col"> <div className="flex flex-col">
<ChatMessageUser pubkey={data.sender_pubkey} time={data.created_at} /> <ChatMessageUser pubkey={data.sender_pubkey} time={data.created_at} />
<div className="-mt-[20px] pl-[49px]"> <div className="-mt-[20px] pl-[49px]">
<div className="whitespace-pre-line break-words text-base leading-tight"> <div className="whitespace-pre-line break-words text-base text-zinc-100 leading-tight">
{content.parsed || ""} {content.parsed || ""}
</div> </div>
{Array.isArray(content.images) && content.images.length ? ( {Array.isArray(content.images) && content.images.length ? (

View File

@ -35,7 +35,7 @@ export function ChatMessageUser({
</div> </div>
<div className="flex w-full flex-1 items-start justify-between"> <div className="flex w-full flex-1 items-start justify-between">
<div className="flex items-baseline gap-2 text-base"> <div className="flex items-baseline gap-2 text-base">
<span className="font-semibold leading-none text-white group-hover:underline"> <span className="font-semibold leading-none text-zinc-200 group-hover:underline">
{user?.nip05 || user?.name || shortenKey(pubkey)} {user?.nip05 || user?.name || shortenKey(pubkey)}
</span> </span>
<span className="leading-none text-zinc-500">·</span> <span className="leading-none text-zinc-500">·</span>

View File

@ -16,13 +16,24 @@ export function ChatSidebar({ pubkey }: { pubkey: string }) {
className="h-11 w-11 rounded-md object-cover" className="h-11 w-11 rounded-md object-cover"
/> />
</div> </div>
<div className="flex flex-col gap-1"> <div className="flex flex-col gap-4">
<h3 className="leading-none text-lg font-semibold"> <div className="flex flex-col gap-1">
{user?.display_name || user?.name} <h3 className="leading-none text-lg font-semibold">
</h3> {user?.display_name || user?.name}
<p className="leading-none text-zinc-400"> </h3>
{user?.nip05 || user?.username || shortenKey(pubkey)} <h5 className="leading-none text-zinc-400">
</p> {user?.nip05 || user?.username || shortenKey(pubkey)}
</h5>
</div>
<div>
<p className="leading-tight">{user?.bio || user?.about}</p>
<a
href={`/app/user?npub=${user.npub}`}
className="mt-3 inline-flex w-full h-10 items-center justify-center rounded-md bg-zinc-900 hover:bg-zinc-800 text-sm text-zinc-300 hover:text-zinc-100 font-medium"
>
View full profile
</a>
</div>
</div> </div>
</div> </div>
</div> </div>

View File

@ -1,16 +1,20 @@
import { nip04 } from "nostr-tools"; import { nip04 } from "nostr-tools";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
export function useDecryptMessage(data: any, userPriv: string) { export function useDecryptMessage(
data: any,
userPubkey: string,
userPriv: string,
) {
const [content, setContent] = useState(data.content); const [content, setContent] = useState(data.content);
useEffect(() => { useEffect(() => {
async function decrypt() { async function decrypt() {
const result = await nip04.decrypt( const pubkey =
userPriv, userPubkey === data.sender_pubkey
data.sender_pubkey, ? data.receiver_pubkey
data.content, : data.sender_pubkey;
); const result = await nip04.decrypt(userPriv, pubkey, data.content);
setContent(result); setContent(result);
} }

View File

@ -33,15 +33,15 @@ export function Page() {
const getQuery = useCallback(() => { const getQuery = useCallback(() => {
const query = []; const query = [];
const follows = JSON.parse(account.follows); const follows = JSON.parse(account.follows);
const last = parseInt(lastLogin);
let queryNoteSince: number; let queryNoteSince: number;
let querySince: number;
if (totalNotes === 0) { if (totalNotes === 0) {
queryNoteSince = dateToUnix(getHourAgo(48, now.current)); queryNoteSince = dateToUnix(getHourAgo(48, now.current));
} else { } else {
if (parseInt(lastLogin) > 0) { if (parseInt(lastLogin) > 0) {
queryNoteSince = parseInt(lastLogin); queryNoteSince = last;
} else { } else {
queryNoteSince = dateToUnix(getHourAgo(48, now.current)); queryNoteSince = dateToUnix(getHourAgo(48, now.current));
} }
@ -58,21 +58,21 @@ export function Page() {
query.push({ query.push({
kinds: [4], kinds: [4],
"#p": [account.pubkey], "#p": [account.pubkey],
since: querySince, since: last,
}); });
// kind 4 (chats) query // kind 4 (chats) query
query.push({ query.push({
kinds: [4], kinds: [4],
authors: [account.pubkey], authors: [account.pubkey],
since: querySince, since: last,
}); });
// kind 43, 43 (mute user, hide message) query // kind 43, 43 (mute user, hide message) query
query.push({ query.push({
authors: [account.pubkey], authors: [account.pubkey],
kinds: [43, 44], kinds: [43, 44],
since: querySince, since: last,
}); });
return query; return query;
@ -107,8 +107,8 @@ export function Page() {
const receiver = event.tags.find((t) => t[0] === "p")[1]; const receiver = event.tags.find((t) => t[0] === "p")[1];
createChat( createChat(
event.id, event.id,
event.pubkey,
receiver, receiver,
event.pubkey,
event.content, event.content,
event.tags, event.tags,
event.created_at, event.created_at,
@ -116,8 +116,8 @@ export function Page() {
} else { } else {
createChat( createChat(
event.id, event.id,
event.pubkey,
account.pubkey, account.pubkey,
event.pubkey,
event.content, event.content,
event.tags, event.tags,
event.created_at, event.created_at,

View File

@ -2,7 +2,10 @@ import { LayoutDefault } from "./layoutDefault";
import { PageContext } from "./types"; import { PageContext } from "./types";
import { RelayProvider } from "@shared/relayProvider"; import { RelayProvider } from "@shared/relayProvider";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { dateToUnix } from "@utils/date";
import { PageContextProvider } from "@utils/hooks/usePageContext"; import { PageContextProvider } from "@utils/hooks/usePageContext";
import { updateLastLogin } from "@utils/storage";
import { useEffect } from "react";
const queryClient = new QueryClient(); const queryClient = new QueryClient();
@ -14,6 +17,23 @@ export function Shell({
(pageContext.exports.Layout as React.ElementType) || (pageContext.exports.Layout as React.ElementType) ||
(LayoutDefault as React.ElementType); (LayoutDefault as React.ElementType);
useEffect(() => {
async function initWindowEvent() {
const { TauriEvent } = await import("@tauri-apps/api/event");
const { appWindow, getCurrent } = await import("@tauri-apps/api/window");
// listen window close event
getCurrent().listen(TauriEvent.WINDOW_CLOSE_REQUESTED, () => {
// update last login time
updateLastLogin(dateToUnix());
// close window
appWindow.close();
});
}
initWindowEvent().catch(console.error);
}, []);
return ( return (
<PageContextProvider pageContext={pageContext}> <PageContextProvider pageContext={pageContext}>
<RelayProvider> <RelayProvider>

View File

@ -3,21 +3,14 @@ import { RelayContext } from "@shared/relayProvider";
import { useActiveAccount } from "@stores/accounts"; import { useActiveAccount } from "@stores/accounts";
import { READONLY_RELAYS } from "@stores/constants"; import { READONLY_RELAYS } from "@stores/constants";
import { dateToUnix } from "@utils/date"; import { dateToUnix } from "@utils/date";
import { import { createChat, createNote, updateAccount } from "@utils/storage";
createChat,
createNote,
updateAccount,
updateLastLogin,
} from "@utils/storage";
import { getParentID, nip02ToArray } from "@utils/transform"; import { getParentID, nip02ToArray } from "@utils/transform";
import { useContext, useEffect, useRef } from "react"; import { useContext } from "react";
import useSWRSubscription from "swr/subscription"; import useSWRSubscription from "swr/subscription";
export default function EventCollector() { export default function EventCollector() {
const pool: any = useContext(RelayContext); const pool: any = useContext(RelayContext);
const account = useActiveAccount((state: any) => state.account); const account = useActiveAccount((state: any) => state.account);
const now = useRef(new Date());
useSWRSubscription(account ? "eventCollector" : null, () => { useSWRSubscription(account ? "eventCollector" : null, () => {
const follows = JSON.parse(account.follows); const follows = JSON.parse(account.follows);
@ -26,7 +19,7 @@ export default function EventCollector() {
{ {
kinds: [1, 6], kinds: [1, 6],
authors: follows, authors: follows,
since: dateToUnix(now.current), since: dateToUnix(),
}, },
{ {
kinds: [3], kinds: [3],
@ -35,7 +28,12 @@ export default function EventCollector() {
{ {
kinds: [4], kinds: [4],
"#p": [account.pubkey], "#p": [account.pubkey],
since: dateToUnix(now.current), since: dateToUnix(),
},
{
kinds: [4],
authors: [account.pubkey],
since: dateToUnix(),
}, },
], ],
READONLY_RELAYS, READONLY_RELAYS,
@ -64,16 +62,29 @@ export default function EventCollector() {
break; break;
} }
// chat // chat
case 4: case 4: {
createChat( if (event.pubkey === account.pubkey) {
event.id, const receiver = event.tags.find((t) => t[0] === "p")[1];
account.pubkey, createChat(
event.pubkey, event.id,
event.content, receiver,
event.tags, event.pubkey,
event.created_at, event.content,
); event.tags,
event.created_at,
);
} else {
createChat(
event.id,
account.pubkey,
event.pubkey,
event.content,
event.tags,
event.created_at,
);
}
break; break;
}
// repost // repost
case 6: case 6:
createNote( createNote(
@ -98,23 +109,6 @@ export default function EventCollector() {
}; };
}); });
useEffect(() => {
async function initWindowEvent() {
const { TauriEvent } = await import("@tauri-apps/api/event");
const { appWindow, getCurrent } = await import("@tauri-apps/api/window");
// listen window close event
getCurrent().listen(TauriEvent.WINDOW_CLOSE_REQUESTED, () => {
// update last login time
updateLastLogin(dateToUnix(now.current));
// close window
appWindow.close();
});
}
initWindowEvent().catch(console.error);
}, []);
return ( return (
<div className="inline-flex h-6 w-6 items-center justify-center rounded text-zinc-500 hover:bg-zinc-900 hover:text-green-500"> <div className="inline-flex h-6 w-6 items-center justify-center rounded text-zinc-500 hover:bg-zinc-900 hover:text-green-500">
<HeartBeatIcon width={16} height={16} /> <HeartBeatIcon width={16} height={16} />

View File

@ -1,7 +1,6 @@
import PlusIcon from "@icons/plus"; import PlusIcon from "@icons/plus";
import { channelContentAtom } from "@stores/channel"; import { channelContentAtom } from "@stores/channel";
import { chatContentAtom } from "@stores/chat";
import { createBlobFromFile } from "@utils/createBlobFromFile"; import { createBlobFromFile } from "@utils/createBlobFromFile";
@ -14,9 +13,6 @@ export function ImagePicker({ type }: { type: string }) {
let atom; let atom;
switch (type) { switch (type) {
case "chat":
atom = chatContentAtom;
break;
case "channel": case "channel":
atom = channelContentAtom; atom = channelContentAtom;
break; break;

View File

@ -12,7 +12,7 @@ export const useChats = create((set) => ({
export const useChatMessages = create((set) => ({ export const useChatMessages = create((set) => ({
messages: [], messages: [],
fetch: async (receiver_pubkey: string, sender_pubkey: string) => { fetch: async (receiver_pubkey: string, sender_pubkey: string) => {
const response = await getChatMessages(receiver_pubkey, sender_pubkey); const response: any = await getChatMessages(receiver_pubkey, sender_pubkey);
set({ messages: response }); set({ messages: response });
}, },
add: (message: any) => { add: (message: any) => {

View File

@ -286,9 +286,19 @@ export async function getChatMessages(
sender_pubkey: string, sender_pubkey: string,
) { ) {
const db = await connect(); const db = await connect();
return await db.select( const sender: any = await db.select(
`SELECT * FROM chats WHERE receiver_pubkey = "${receiver_pubkey}" AND sender_pubkey = "${sender_pubkey}" ORDER BY created_at ASC;`, `SELECT * FROM chats WHERE sender_pubkey = "${sender_pubkey}" AND receiver_pubkey = "${receiver_pubkey}";`,
); );
const receiver: any = await db.select(
`SELECT * FROM chats WHERE sender_pubkey = "${receiver_pubkey}" AND receiver_pubkey = "${sender_pubkey}";`,
);
const result = [...sender, ...receiver].sort(
(x: { created_at: number }, y: { created_at: number }) =>
x.created_at - y.created_at,
);
return result;
} }
// create chat // create chat