mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-05 16:33:36 +00:00
53 lines
1.6 KiB
TypeScript
53 lines
1.6 KiB
TypeScript
import { useNostr } from "@nostrify/react";
|
|
import { useMutation, type UseMutationResult } from "@tanstack/react-query";
|
|
|
|
import { useCurrentUser } from "./useCurrentUser";
|
|
|
|
import type { NostrEvent } from "@nostrify/nostrify";
|
|
|
|
type EventTemplate = Pick<NostrEvent, 'kind' | 'content'> &
|
|
Partial<Pick<NostrEvent, 'tags' | 'created_at'>>;
|
|
|
|
export function useNostrPublish(): UseMutationResult<
|
|
NostrEvent,
|
|
Error,
|
|
EventTemplate
|
|
> {
|
|
const { nostr } = useNostr();
|
|
const { user } = useCurrentUser();
|
|
|
|
return useMutation({
|
|
mutationFn: async (t: EventTemplate) => {
|
|
if (user) {
|
|
const tags = t.tags ?? [];
|
|
|
|
const { hostname } = location;
|
|
const isLocalhost = hostname === "localhost" || hostname.endsWith(".localhost");
|
|
const isIpAddress = /^\d{1,3}(\.\d{1,3}){3}$/.test(hostname) || hostname.startsWith("[");
|
|
|
|
// Add the client tag if it doesn't exist
|
|
if (location.protocol === "https:" && !isLocalhost && !isIpAddress && !tags.some(([name]) => name === "client")) {
|
|
tags.push(["client", location.hostname]);
|
|
}
|
|
|
|
const event = await user.signer.signEvent({
|
|
kind: t.kind,
|
|
content: t.content ?? "",
|
|
tags,
|
|
created_at: t.created_at ?? Math.floor(Date.now() / 1000),
|
|
});
|
|
|
|
await nostr.event(event, { signal: AbortSignal.timeout(5000) });
|
|
return event;
|
|
} 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);
|
|
},
|
|
});
|
|
} |