Skip to content

Commit

Permalink
merge
Browse files Browse the repository at this point in the history
  • Loading branch information
feruzm committed Apr 4, 2024
2 parents ee837c9 + 3d4464f commit 453c49f
Show file tree
Hide file tree
Showing 16 changed files with 213 additions and 90 deletions.
34 changes: 15 additions & 19 deletions lib/mutations/add-direct-contact.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,26 +66,22 @@ export function useAddDirectContact() {
{
onSuccess: (contact) => {
if (contact) {
const directContacts =
queryClient.getQueryData<DirectContact[]>([
ChatQueries.DIRECT_CONTACTS,
activeUsername,
]) ?? [];
if (directContacts.every((dc) => dc.pubkey !== contact.pubkey)) {
queryClient.setQueryData(
[ChatQueries.DIRECT_CONTACTS, activeUsername],
[...directContacts, contact],
);
}
queryClient.setQueryData(
queryClient.setQueryData<DirectContact[]>(
[ChatQueries.DIRECT_CONTACTS, activeUsername],
(directContacts) => {
const notExists = directContacts?.every(
(dc) => dc.pubkey !== contact.pubkey,
);
if (notExists) {
return [...(directContacts ?? []), contact];
}
return directContacts;
},
);

queryClient.setQueryData<DirectContact[]>(
[ChatQueries.ORIGINAL_DIRECT_CONTACTS, activeUsername],
[
...(queryClient.getQueryData<DirectContact[]>([
ChatQueries.ORIGINAL_DIRECT_CONTACTS,
activeUsername,
]) ?? []),
contact,
],
(data) => [...(data ?? []), contact],
);
}
},
Expand Down
1 change: 1 addition & 0 deletions lib/mutations/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,4 @@ export * from "./restore-chat-by-pin";
export * from "./update-direct-contacts-last-seen-date";
export * from "./update-channel-last-seen-date";
export * from "./mute-user-in-channel";
export * from "./pin-contact";
71 changes: 71 additions & 0 deletions lib/mutations/pin-contact.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useContext } from "react";
import { ChatContext } from "../chat-context-provider";
import { DirectContact, useNostrPublishMutation } from "../nostr";
import { Kind } from "nostr-tools";
import { ChatQueries } from "../queries";
import { updateContactsBasedOnResult } from "./utils";

export function usePinContact() {
const queryClient = useQueryClient();
const { activeUsername } = useContext(ChatContext);

const { mutateAsync: publishDirectContact } = useNostrPublishMutation(
["chats/nostr-publish-direct-contact"],
Kind.Contacts,
() => {},
);

return useMutation(
["chats/nostr-update-direct-contacts-pins"],
async ({
contact,
pinned,
}: {
contact: DirectContact;
pinned: boolean;
}) => {
const directContacts =
queryClient.getQueryData<DirectContact[]>([
ChatQueries.ORIGINAL_DIRECT_CONTACTS,
activeUsername,
]) ?? [];
console.debug("[ns-query] Updating direct contact pin", contact, pinned);

const contactTags = directContacts.map((c) => [
"p",
c.pubkey,
"",
c.name,
]);
const pinTags = directContacts
.filter((c) => contact.pubkey !== c.pubkey)
.map((c) => ["pinned", c.pubkey, c.pinned ? "true" : "false"]);
const lastSeenTags = directContacts.map((c) => [
"lastSeenDate",
c.pubkey,
c.lastSeenDate?.getTime().toString() ?? "",
]);

await publishDirectContact({
tags: [
...contactTags,
...lastSeenTags,
...pinTags,
["pinned", contact.pubkey, pinned ? "true" : "false"],
],
eventMetadata: "",
});

contact.pinned = pinned;
return contact;
},
{
onSuccess: (contact) => {
if (contact) {
updateContactsBasedOnResult(queryClient, activeUsername, contact);
}
},
},
);
}
2 changes: 1 addition & 1 deletion lib/mutations/resend-message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ export function useResendMessage(
if (currentChannel) {
return sendPublicMessage({ message: message.content });
} else if (currentContact) {
return sendDirectMessage(message.content);
return sendDirectMessage({ message: message.content });
} else {
throw new Error("[Chat][SendMessage] – no receiver");
}
Expand Down
12 changes: 9 additions & 3 deletions lib/mutations/send-message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,13 @@ export function useSendMessage(

return useMutation(
["chats/send-message"],
async (message: string) => {
async ({
forwardedFrom,
message,
}: {
message: string;
forwardedFrom?: string;
}) => {
if (!message || message.includes("Uploading")) {
throw new Error(
"[Chat][SendMessage] – empty message or has uploading file",
Expand All @@ -52,9 +58,9 @@ export function useSendMessage(
}

if (currentChannel) {
return sendPublicMessage({ message });
return sendPublicMessage({ message, forwardedFrom });
} else if (currentContact) {
return sendDirectMessage(message);
return sendDirectMessage({ message, forwardedFrom });
} else {
throw new Error("[Chat][SendMessage] – no receiver");
}
Expand Down
26 changes: 8 additions & 18 deletions lib/mutations/update-direct-contacts-last-seen-date.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { ChatQueries } from "../queries";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useContext } from "react";
import { ChatContext } from "../chat-context-provider";
import { updateContactsBasedOnResult } from "./utils";

export function useUpdateDirectContactsLastSeenDate() {
const queryClient = useQueryClient();
Expand Down Expand Up @@ -41,6 +42,11 @@ export function useUpdateDirectContactsLastSeenDate() {
"",
c.name,
]);
const pinTags = directContacts.map((c) => [
"pinned",
c.pubkey,
c.pinned ? "true" : "false",
]);
const lastSeenTags = directContacts
.filter((c) => contact.pubkey !== c.pubkey)
.map((c) => [
Expand All @@ -53,6 +59,7 @@ export function useUpdateDirectContactsLastSeenDate() {
tags: [
...contactTags,
...lastSeenTags,
...pinTags,
["lastSeenDate", contact.pubkey, lastSeenDate.getTime().toString()],
],
eventMetadata: "",
Expand All @@ -64,24 +71,7 @@ export function useUpdateDirectContactsLastSeenDate() {
{
onSuccess: (contact) => {
if (contact) {
const directContacts =
queryClient.getQueryData<DirectContact[]>([
ChatQueries.DIRECT_CONTACTS,
activeUsername,
]) ?? [];
const nextDirectContacts = [
...directContacts.filter((dc) => dc.pubkey !== contact.pubkey),
contact,
];
queryClient.setQueryData(
[ChatQueries.DIRECT_CONTACTS, activeUsername],
nextDirectContacts,
);
console.debug(
"[ns-query] Next direct contacts",
contact,
nextDirectContacts,
);
updateContactsBasedOnResult(queryClient, activeUsername, contact);
}
},
},
Expand Down
1 change: 1 addition & 0 deletions lib/mutations/utils/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./update-contacts-based-on-result";
24 changes: 24 additions & 0 deletions lib/mutations/utils/update-contacts-based-on-result.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { DirectContact } from "../../nostr";
import { ChatQueries } from "../../queries";
import { QueryClient } from "@tanstack/react-query";

export function updateContactsBasedOnResult(
queryClient: QueryClient,
activeUsername: string | undefined,
contact: DirectContact,
) {
queryClient.setQueryData<DirectContact[]>(
[ChatQueries.ORIGINAL_DIRECT_CONTACTS, activeUsername],
(directContacts) => [
...(directContacts ?? []).filter((dc) => dc.pubkey !== contact.pubkey),
contact,
],
);
queryClient.setQueryData<DirectContact[]>(
[ChatQueries.DIRECT_CONTACTS, activeUsername],
(directContacts) => [
...(directContacts ?? []).filter((dc) => dc.pubkey !== contact.pubkey),
contact,
],
);
}
2 changes: 1 addition & 1 deletion lib/nostr/core/use-live-listener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export function useLiveListener<DATA extends object>(
subInfo.unsub();
reset();
});
}, 10000);
}, 3000);

useEffect(() => {
if (!options.enabled || filters.length === 0) {
Expand Down
66 changes: 40 additions & 26 deletions lib/nostr/mutations/send-direct-message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,34 +18,48 @@ export function useNostrSendDirectMessage(
);
const { mutateAsync: findHealthyRelay } = useFindHealthyRelayQuery();

return useMutation(["chats/send-direct-message"], async (message: string) => {
if (!publicKey || !privateKey || !destinationPublicKey) {
throw new Error(
"[Chat][Nostr] – attempting to send direct message with no private, destination or public key",
return useMutation(
["chats/send-direct-message"],
async ({
message,
forwardedFrom,
}: {
message: string;
forwardedFrom?: string;
}) => {
if (!publicKey || !privateKey || !destinationPublicKey) {
throw new Error(
"[Chat][Nostr] – attempting to send direct message with no private, destination or public key",
);
}

const encryptedMessage = await nip04.encrypt(
ownerPrivateKey,
destinationPublicKey,
message,
);
}
const tags = [["p", destinationPublicKey]];

const encryptedMessage = await nip04.encrypt(
ownerPrivateKey,
destinationPublicKey,
message,
);
const tags = [["p", destinationPublicKey]];
if (parent) {
const relay = await findHealthyRelay(parent);
if (relay) {
tags.push(["e", parent, relay, "root"]);
}
}

if (parent) {
const relay = await findHealthyRelay(parent);
if (relay) {
tags.push(["e", parent, relay, "root"]);
if (forwardedFrom) {
tags.push(["fwd", forwardedFrom]);
}
}
const event = await publishEncryptedMessage({
tags,
eventMetadata: encryptedMessage,
});
return convertEvent<Kind.EncryptedDirectMessage>(
event,
publicKey,
privateKey,
)!!;
});

const event = await publishEncryptedMessage({
tags,
eventMetadata: encryptedMessage,
});
return convertEvent<Kind.EncryptedDirectMessage>(
event,
publicKey,
privateKey,
)!!;
},
);
}
7 changes: 6 additions & 1 deletion lib/nostr/mutations/send-public-message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { Kind } from "nostr-tools";
interface Payload {
message: string;
mentions?: string[];
forwardedFrom?: string;
}

export function useNostrSendPublicMessage(channelId?: string, parent?: string) {
Expand All @@ -19,7 +20,7 @@ export function useNostrSendPublicMessage(channelId?: string, parent?: string) {

return useMutation(
["chats/send-public-message"],
async ({ message, mentions }: Payload) => {
async ({ message, mentions, forwardedFrom }: Payload) => {
const root = parent || channelId;

if (!root) {
Expand All @@ -39,6 +40,10 @@ export function useNostrSendPublicMessage(channelId?: string, parent?: string) {
mentions.forEach((m) => tags.push(["p", m]));
}

if (forwardedFrom) {
tags.push(["fwd", forwardedFrom]);
}

const event = await publishChannelMessage({
tags,
eventMetadata: message,
Expand Down
1 change: 1 addition & 0 deletions lib/nostr/types/direct-contact.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ export type DirectContact = {
name: string;
pubkey: string;
lastSeenDate?: Date;
pinned?: boolean;
};
18 changes: 9 additions & 9 deletions lib/nostr/types/messages.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,24 @@
export type PublicMessage = {
interface BaseMessage {
id: string;
root: string;
content: string;
creator: string;
created: number;
forwardedFrom?: string;
}

export interface PublicMessage extends BaseMessage {
root: string;
children?: PublicMessage[];
mentions: string[];
sent?: number;
};
}

export type DirectMessage = {
id: string;
export interface DirectMessage extends BaseMessage {
root?: string;
content: string;
peer: string;
creator: string;
created: number;
children?: DirectMessage[];
decrypted: boolean;
sent?: number;
};
}

export type Message = PublicMessage | DirectMessage;
Loading

0 comments on commit 453c49f

Please sign in to comment.