feat: add relay manager

This commit is contained in:
reya
2024-08-06 08:24:12 +07:00
parent 4c60e55d50
commit c3334d91cf
13 changed files with 396 additions and 107 deletions

View File

@@ -4,6 +4,38 @@
/** user-defined commands **/
export const commands = {
async getBootstrapRelays() : Promise<Result<string[], string>> {
try {
return { status: "ok", data: await TAURI_INVOKE("get_bootstrap_relays") };
} catch (e) {
if(e instanceof Error) throw e;
else return { status: "error", error: e as any };
}
},
async setBootstrapRelays(relays: string) : Promise<Result<null, string>> {
try {
return { status: "ok", data: await TAURI_INVOKE("set_bootstrap_relays", { relays }) };
} catch (e) {
if(e instanceof Error) throw e;
else return { status: "error", error: e as any };
}
},
async getInboxRelays(userId: string) : Promise<Result<string[], string>> {
try {
return { status: "ok", data: await TAURI_INVOKE("get_inbox_relays", { userId }) };
} catch (e) {
if(e instanceof Error) throw e;
else return { status: "error", error: e as any };
}
},
async setInboxRelays(relays: string[]) : Promise<Result<null, string>> {
try {
return { status: "ok", data: await TAURI_INVOKE("set_inbox_relays", { relays }) };
} catch (e) {
if(e instanceof Error) throw e;
else return { status: "error", error: e as any };
}
},
async login(account: string, password: string) : Promise<Result<string, string>> {
try {
return { status: "ok", data: await TAURI_INVOKE("login", { account, password }) };
@@ -79,22 +111,6 @@ try {
else return { status: "error", error: e as any };
}
},
async getInbox(id: string) : Promise<Result<string[], string>> {
try {
return { status: "ok", data: await TAURI_INVOKE("get_inbox", { id }) };
} catch (e) {
if(e instanceof Error) throw e;
else return { status: "error", error: e as any };
}
},
async setInbox(relays: string[]) : Promise<Result<null, string>> {
try {
return { status: "ok", data: await TAURI_INVOKE("set_inbox", { relays }) };
} catch (e) {
if(e instanceof Error) throw e;
else return { status: "error", error: e as any };
}
},
async connectInbox(id: string) : Promise<Result<string[], string>> {
try {
return { status: "ok", data: await TAURI_INVOKE("connect_inbox", { id }) };

View File

@@ -13,7 +13,9 @@ import { createFileRoute } from '@tanstack/react-router'
// Import Routes
import { Route as rootRoute } from './routes/__root'
import { Route as BootstrapRelaysImport } from './routes/bootstrap-relays'
import { Route as IndexImport } from './routes/index'
import { Route as AccountRelaysImport } from './routes/$account.relays'
import { Route as AccountContactsImport } from './routes/$account.contacts'
import { Route as AccountChatsIdImport } from './routes/$account.chats.$id'
@@ -23,7 +25,6 @@ const NostrConnectLazyImport = createFileRoute('/nostr-connect')()
const NewLazyImport = createFileRoute('/new')()
const ImportKeyLazyImport = createFileRoute('/import-key')()
const CreateAccountLazyImport = createFileRoute('/create-account')()
const AccountRelaysLazyImport = createFileRoute('/$account/relays')()
const AccountChatsLazyImport = createFileRoute('/$account/chats')()
const AccountChatsNewLazyImport = createFileRoute('/$account/chats/new')()
@@ -51,18 +52,18 @@ const CreateAccountLazyRoute = CreateAccountLazyImport.update({
import('./routes/create-account.lazy').then((d) => d.Route),
)
const BootstrapRelaysRoute = BootstrapRelaysImport.update({
path: '/bootstrap-relays',
getParentRoute: () => rootRoute,
} as any).lazy(() =>
import('./routes/bootstrap-relays.lazy').then((d) => d.Route),
)
const IndexRoute = IndexImport.update({
path: '/',
getParentRoute: () => rootRoute,
} as any).lazy(() => import('./routes/index.lazy').then((d) => d.Route))
const AccountRelaysLazyRoute = AccountRelaysLazyImport.update({
path: '/$account/relays',
getParentRoute: () => rootRoute,
} as any).lazy(() =>
import('./routes/$account.relays.lazy').then((d) => d.Route),
)
const AccountChatsLazyRoute = AccountChatsLazyImport.update({
path: '/$account/chats',
getParentRoute: () => rootRoute,
@@ -70,6 +71,13 @@ const AccountChatsLazyRoute = AccountChatsLazyImport.update({
import('./routes/$account.chats.lazy').then((d) => d.Route),
)
const AccountRelaysRoute = AccountRelaysImport.update({
path: '/$account/relays',
getParentRoute: () => rootRoute,
} as any).lazy(() =>
import('./routes/$account.relays.lazy').then((d) => d.Route),
)
const AccountContactsRoute = AccountContactsImport.update({
path: '/$account/contacts',
getParentRoute: () => rootRoute,
@@ -102,6 +110,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof IndexImport
parentRoute: typeof rootRoute
}
'/bootstrap-relays': {
id: '/bootstrap-relays'
path: '/bootstrap-relays'
fullPath: '/bootstrap-relays'
preLoaderRoute: typeof BootstrapRelaysImport
parentRoute: typeof rootRoute
}
'/create-account': {
id: '/create-account'
path: '/create-account'
@@ -137,6 +152,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof AccountContactsImport
parentRoute: typeof rootRoute
}
'/$account/relays': {
id: '/$account/relays'
path: '/$account/relays'
fullPath: '/$account/relays'
preLoaderRoute: typeof AccountRelaysImport
parentRoute: typeof rootRoute
}
'/$account/chats': {
id: '/$account/chats'
path: '/$account/chats'
@@ -144,13 +166,6 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof AccountChatsLazyImport
parentRoute: typeof rootRoute
}
'/$account/relays': {
id: '/$account/relays'
path: '/$account/relays'
fullPath: '/$account/relays'
preLoaderRoute: typeof AccountRelaysLazyImport
parentRoute: typeof rootRoute
}
'/$account/chats/$id': {
id: '/$account/chats/$id'
path: '/$id'
@@ -172,16 +187,17 @@ declare module '@tanstack/react-router' {
export const routeTree = rootRoute.addChildren({
IndexRoute,
BootstrapRelaysRoute,
CreateAccountLazyRoute,
ImportKeyLazyRoute,
NewLazyRoute,
NostrConnectLazyRoute,
AccountContactsRoute,
AccountRelaysRoute,
AccountChatsLazyRoute: AccountChatsLazyRoute.addChildren({
AccountChatsIdRoute,
AccountChatsNewLazyRoute,
}),
AccountRelaysLazyRoute,
})
/* prettier-ignore-end */
@@ -193,18 +209,22 @@ export const routeTree = rootRoute.addChildren({
"filePath": "__root.tsx",
"children": [
"/",
"/bootstrap-relays",
"/create-account",
"/import-key",
"/new",
"/nostr-connect",
"/$account/contacts",
"/$account/chats",
"/$account/relays"
"/$account/relays",
"/$account/chats"
]
},
"/": {
"filePath": "index.tsx"
},
"/bootstrap-relays": {
"filePath": "bootstrap-relays.tsx"
},
"/create-account": {
"filePath": "create-account.lazy.tsx"
},
@@ -220,6 +240,9 @@ export const routeTree = rootRoute.addChildren({
"/$account/contacts": {
"filePath": "$account.contacts.tsx"
},
"/$account/relays": {
"filePath": "$account.relays.tsx"
},
"/$account/chats": {
"filePath": "$account.chats.lazy.tsx",
"children": [
@@ -227,9 +250,6 @@ export const routeTree = rootRoute.addChildren({
"/$account/chats/new"
]
},
"/$account/relays": {
"filePath": "$account.relays.lazy.tsx"
},
"/$account/chats/$id": {
"filePath": "$account.chats.$id.tsx",
"parent": "/$account/chats"

View File

@@ -12,6 +12,7 @@ export const Route = createLazyFileRoute("/$account/relays")({
function Screen() {
const navigate = Route.useNavigate();
const inboxRelays = Route.useLoaderData();
const { account } = Route.useParams();
const [newRelay, setNewRelay] = useState("");
@@ -43,6 +44,10 @@ function Screen() {
}
};
const remove = (relay: string) => {
setRelays((prev) => prev.filter((item) => item !== relay));
};
const submit = async () => {
startTransition(async () => {
if (!relays.length) {
@@ -50,7 +55,7 @@ function Screen() {
return;
}
const res = await commands.setInbox(relays);
const res = await commands.setInboxRelays(relays);
if (res.status === "ok") {
navigate({
@@ -69,16 +74,8 @@ function Screen() {
};
useEffect(() => {
async function getRelays() {
const res = await commands.getInbox(account);
if (res.status === "ok") {
setRelays((prev) => [...prev, ...res.data]);
}
}
getRelays();
}, []);
setRelays(inboxRelays);
}, [inboxRelays]);
return (
<div className="size-full flex items-center justify-center">
@@ -140,6 +137,7 @@ function Screen() {
<div className="flex items-center gap-2">
<button
type="button"
onClick={() => remove(relay)}
className="inline-flex items-center justify-center rounded-md size-7 text-neutral-700 dark:text-white/20 hover:bg-black/10 dark:hover:bg-white/10"
>
<X className="size-3" />

View File

@@ -0,0 +1,14 @@
import { commands } from "@/commands";
import { createFileRoute } from "@tanstack/react-router";
export const Route = createFileRoute("/$account/relays")({
loader: async ({ params }) => {
const res = await commands.getInboxRelays(params.account);
if (res.status === "ok") {
return res.data;
} else {
throw new Error(res.error);
}
},
});

View File

@@ -0,0 +1,142 @@
import { commands } from "@/commands";
import { Frame } from "@/components/frame";
import { Spinner } from "@/components/spinner";
import { Plus, X } from "@phosphor-icons/react";
import { createLazyFileRoute } from "@tanstack/react-router";
import { message } from "@tauri-apps/plugin-dialog";
import { useEffect, useState, useTransition } from "react";
export const Route = createLazyFileRoute("/bootstrap-relays")({
component: Screen,
});
function Screen() {
const bootstrapRelays = Route.useLoaderData();
const [relays, setRelays] = useState<string[]>([]);
const [newRelay, setNewRelay] = useState("");
const [isPending, startTransition] = useTransition();
const add = () => {
try {
let url = newRelay;
if (!url.startsWith("wss://")) {
url = `wss://${url}`;
}
// Validate URL
const relay = new URL(url);
// Update
setRelays((prev) => [...prev, relay.toString()]);
setNewRelay("");
} catch {
message("URL is not valid.", { kind: "error" });
}
};
const remove = (relay: string) => {
setRelays((prev) => prev.filter((item) => item !== relay));
};
const submit = async () => {
startTransition(async () => {
if (!relays.length) {
await message("You need to add at least 1 relay", {
title: "Manage Relays",
kind: "info",
});
return;
}
const merged = relays
.map((relay) => Object.values(relay).join(","))
.join("\n");
const res = await commands.setBootstrapRelays(merged);
if (res.status === "ok") {
// TODO: restart app
} else {
await message(res.error, {
title: "Manage Relays",
kind: "error",
});
return;
}
});
};
useEffect(() => {
setRelays(bootstrapRelays);
}, [bootstrapRelays]);
return (
<div className="size-full flex items-center justify-center">
<div className="w-[320px] flex flex-col gap-8">
<div className="flex flex-col gap-1 text-center">
<h1 className="leading-tight text-xl font-semibold">Manage Relays</h1>
<p className="text-sm text-neutral-700 dark:text-neutral-300">
This relays will be only use to get user's metadata.
</p>
</div>
<div className="flex flex-col gap-3">
<Frame
className="flex flex-col gap-3 p-3 rounded-xl overflow-hidden"
shadow
>
<div className="flex gap-2">
<input
name="relay"
type="text"
placeholder="ex: relay.nostr.net, ..."
value={newRelay}
onChange={(e) => setNewRelay(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") add();
}}
className="flex-1 px-3 rounded-lg h-9 bg-transparent border border-neutral-200 dark:border-neutral-800 focus:border-blue-500 focus:outline-none placeholder:text-neutral-400 dark:placeholder:text-neutral-600"
/>
<button
type="submit"
onClick={() => add()}
className="inline-flex items-center justify-center size-9 rounded-lg bg-neutral-100 hover:bg-neutral-200 dark:bg-neutral-900 dark:hover:bg-neutral-800"
>
<Plus className="size-5" />
</button>
</div>
<div className="flex flex-col gap-2">
{relays.map((relay) => (
<div
key={relay}
className="flex items-center justify-between h-9 px-2 rounded-lg bg-neutral-100 dark:bg-neutral-900"
>
<div className="text-sm font-medium">{relay}</div>
<div className="flex items-center gap-2">
<button
type="button"
onClick={() => remove(relay)}
className="inline-flex items-center justify-center rounded-md size-7 text-neutral-700 dark:text-white/20 hover:bg-black/10 dark:hover:bg-white/10"
>
<X className="size-3" />
</button>
</div>
</div>
))}
</div>
</Frame>
<div className="flex flex-col items-center gap-1">
<button
type="button"
onClick={() => submit()}
disabled={isPending || !relays.length}
className="inline-flex items-center justify-center w-full h-9 text-sm font-semibold text-white bg-blue-500 rounded-lg shrink-0 hover:bg-blue-600 disabled:opacity-50"
>
{isPending ? <Spinner /> : "Save & Restart"}
</button>
</div>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,14 @@
import { commands } from "@/commands";
import { createFileRoute } from "@tanstack/react-router";
export const Route = createFileRoute("/bootstrap-relays")({
loader: async () => {
const res = await commands.getBootstrapRelays();
if (res.status === "ok") {
return res.data.map((item) => item.replace(",", ""));
} else {
throw new Error(res.error);
}
},
});

View File

@@ -3,7 +3,7 @@ import { npub } from "@/commons";
import { Frame } from "@/components/frame";
import { Spinner } from "@/components/spinner";
import { User } from "@/components/user";
import { ArrowRight, DotsThree, Plus } from "@phosphor-icons/react";
import { ArrowRight, DotsThree, GearSix, Plus } from "@phosphor-icons/react";
import { Link, createLazyFileRoute } from "@tanstack/react-router";
import { Menu, MenuItem } from "@tauri-apps/api/menu";
import { message } from "@tauri-apps/plugin-dialog";
@@ -103,7 +103,7 @@ function Screen() {
return (
<div
data-tauri-drag-region
className="size-full flex items-center justify-center"
className="relative size-full flex items-center justify-center"
>
<div className="w-[320px] flex flex-col gap-8">
<div className="flex flex-col gap-1 text-center">
@@ -190,6 +190,15 @@ function Screen() {
</Link>
</Frame>
</div>
<div className="absolute bottom-2 right-2">
<Link
to="/bootstrap-relays"
className="h-8 w-max text-xs px-3 inline-flex items-center justify-center gap-1.5 bg-black/5 hover:bg-black/10 dark:bg-white/5 dark:hover:bg-white/10 rounded-full"
>
<GearSix className="size-4" />
Manage Relays
</Link>
</div>
</div>
);
}