2025-04-17 11:23:46 -05:00
|
|
|
import { useNostr } from "@nostrify/react";
|
2025-05-30 23:40:57 +02:00
|
|
|
import { useMutation, type UseMutationResult } from "@tanstack/react-query";
|
2025-04-17 11:23:46 -05:00
|
|
|
|
|
|
|
import { useCurrentUser } from "./useCurrentUser";
|
|
|
|
|
2025-05-30 23:40:57 +02:00
|
|
|
import type { NostrEvent } from "@nostrify/nostrify";
|
2025-04-17 11:23:46 -05:00
|
|
|
|
2025-05-30 23:40:57 +02:00
|
|
|
export function useNostrPublish(): UseMutationResult<NostrEvent> {
|
2025-04-17 11:23:46 -05:00
|
|
|
const { nostr } = useNostr();
|
|
|
|
const { user } = useCurrentUser();
|
|
|
|
|
|
|
|
return useMutation({
|
2025-05-30 23:40:57 +02:00
|
|
|
mutationFn: async (t: Omit<NostrEvent, 'id' | 'pubkey' | 'sig'>) => {
|
2025-04-17 11:23:46 -05:00
|
|
|
if (user) {
|
2025-05-16 12:28:01 -05:00
|
|
|
const tags = t.tags ?? [];
|
|
|
|
|
|
|
|
// Add the client tag if it doesn't exist
|
2025-06-07 16:32:28 -05:00
|
|
|
if (location.protocol === "https:" && !tags.some(([name]) => name === "client")) {
|
2025-06-02 22:05:03 -05:00
|
|
|
tags.push(["client", location.hostname]);
|
2025-05-16 12:28:01 -05:00
|
|
|
}
|
|
|
|
|
2025-04-17 11:23:46 -05:00
|
|
|
const event = await user.signer.signEvent({
|
|
|
|
kind: t.kind,
|
|
|
|
content: t.content ?? "",
|
2025-05-16 12:28:01 -05:00
|
|
|
tags,
|
2025-04-17 11:23:46 -05:00
|
|
|
created_at: t.created_at ?? Math.floor(Date.now() / 1000),
|
|
|
|
});
|
2025-05-16 12:28:01 -05:00
|
|
|
|
2025-04-23 15:13:17 -05:00
|
|
|
await nostr.event(event, { signal: AbortSignal.timeout(5000) });
|
2025-05-30 23:40:57 +02:00
|
|
|
return event;
|
2025-04-17 11:23:46 -05:00
|
|
|
} else {
|
|
|
|
throw new Error("User is not logged in");
|
|
|
|
}
|
|
|
|
},
|
|
|
|
onError: (error) => {
|
|
|
|
console.error("Failed to publish event:", error);
|
|
|
|
},
|
|
|
|
onSuccess: (data) => {
|
|
|
|
console.log("Event published successfully:", data);
|
|
|
|
},
|
|
|
|
});
|
|
|
|
}
|