Skip to content

Commit

Permalink
chore: clean up
Browse files Browse the repository at this point in the history
  • Loading branch information
reyamir committed Aug 28, 2024
1 parent f6eb5ee commit d128af1
Show file tree
Hide file tree
Showing 27 changed files with 313 additions and 743 deletions.
6 changes: 3 additions & 3 deletions src-tauri/src/commands/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use std::{str::FromStr, time::Duration};
use tauri::State;
use tauri_specta::Event;

use crate::{NewSettings, Nostr, Settings};
use crate::{common::get_latest_event, NewSettings, Nostr, Settings};

#[derive(Clone, Serialize, Deserialize, Type)]
pub struct Profile {
Expand Down Expand Up @@ -229,14 +229,14 @@ pub async fn get_lume_store(key: String, state: State<'_, Nostr>) -> Result<Stri
.author(public_key)
.kind(Kind::ApplicationSpecificData)
.identifier(key)
.limit(1);
.limit(10);

match client
.get_events_of(vec![filter], EventSource::Database)
.await
{
Ok(events) => {
if let Some(event) = events.first() {
if let Some(event) = get_latest_event(&events) {
match signer.nip44_decrypt(public_key, event.content()).await {
Ok(decrypted) => Ok(decrypted),
Err(_) => Err(event.content.to_string()),
Expand Down
58 changes: 57 additions & 1 deletion src/commons.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ import type {
PersistedQuery,
} from "@tanstack/query-persist-client-core";
import { Store } from "@tanstack/store";
import { ask, message } from "@tauri-apps/plugin-dialog";
import { ask, message, open } from "@tauri-apps/plugin-dialog";
import { readFile } from "@tauri-apps/plugin-fs";
import { relaunch } from "@tauri-apps/plugin-process";
import type { Store as TauriStore } from "@tauri-apps/plugin-store";
import { check } from "@tauri-apps/plugin-updater";
Expand Down Expand Up @@ -241,6 +242,61 @@ export async function checkForAppUpdates(silent: boolean) {
}
}

export async function upload(filePath?: string) {
const allowExts = [
"png",
"jpeg",
"jpg",
"gif",
"mp4",
"mp3",
"webm",
"mkv",
"avi",
"mov",
];

const selected =
filePath ||
(
await open({
multiple: false,
filters: [
{
name: "Media",
extensions: allowExts,
},
],
})
).path;

// User cancelled action
if (!selected) return null;

try {
const file = await readFile(selected);
const blob = new Blob([file]);

const data = new FormData();
data.append("fileToUpload", blob);
data.append("submit", "Upload Image");

const res = await fetch("https://nostr.build/api/v2/upload/files", {
method: "POST",
body: data,
});

if (!res.ok) return null;

const json = await res.json();
const content = json.data[0];

return content.url as string;
} catch (e) {
throw new Error(String(e));
}
}

export function toLumeEvents(richEvents: RichEvent[]) {
const events = richEvents.map((item) => {
const nostrEvent: NostrEvent = JSON.parse(item.raw);
Expand Down
4 changes: 3 additions & 1 deletion src/components/note/buttons/zap.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { appSettings, cn } from "@/commons";
import { LumeWindow } from "@/system";
import { Lightning } from "@phosphor-icons/react";
import { useSearch } from "@tanstack/react-router";
import { useStore } from "@tanstack/react-store";
import { useNoteContext } from "../provider";

export function NoteZap({ large = false }: { large?: boolean }) {
const search = useSearch({ strict: false });
const visible = useStore(appSettings, (state) => state.display_zap_button);
const event = useNoteContext();

Expand All @@ -13,7 +15,7 @@ export function NoteZap({ large = false }: { large?: boolean }) {
return (
<button
type="button"
onClick={() => LumeWindow.openZap(event.id)}
onClick={() => LumeWindow.openZap(event.id, search.account)}
className={cn(
"inline-flex items-center justify-center text-neutral-800 dark:text-neutral-200",
large
Expand Down
20 changes: 2 additions & 18 deletions src/components/repost.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@ import { cn } from "@/commons";
import { Spinner } from "@/components";
import { Note } from "@/components/note";
import { User } from "@/components/user";
import { type LumeEvent, NostrQuery } from "@/system";
import { useQuery } from "@tanstack/react-query";
import { type LumeEvent, useEvent } from "@/system";
import { memo } from "react";

export const RepostNote = memo(function RepostNote({
Expand All @@ -13,22 +12,7 @@ export const RepostNote = memo(function RepostNote({
event: LumeEvent;
className?: string;
}) {
const { isLoading, isError, data } = useQuery({
queryKey: ["event", event.repostId],
queryFn: async () => {
try {
const data = await NostrQuery.getRepostEvent(event);
return data;
} catch (e) {
throw new Error(e);
}
},
refetchOnWindowFocus: false,
refetchOnMount: false,
refetchOnReconnect: false,
staleTime: Number.POSITIVE_INFINITY,
retry: 2,
});
const { isLoading, isError, data } = useEvent(event.repostId);

return (
<Note.Root
Expand Down
69 changes: 37 additions & 32 deletions src/components/user/followButton.tsx
Original file line number Diff line number Diff line change
@@ -1,64 +1,69 @@
import { commands } from "@/commands.gen";
import { cn } from "@/commons";
import { Spinner } from "@/components";
import { NostrAccount } from "@/system";
import { useQuery } from "@tanstack/react-query";
import { useRouteContext } from "@tanstack/react-router";
import { message } from "@tauri-apps/plugin-dialog";
import { useEffect, useState, useTransition } from "react";
import { useTransition } from "react";
import { useUserContext } from "./provider";

export function UserFollowButton({
simple = false,
className,
}: {
simple?: boolean;
className?: string;
}) {
export function UserFollowButton({ className }: { className?: string }) {
const user = useUserContext();

const [followed, setFollowed] = useState(false);
const { queryClient } = useRouteContext({ strict: false });
const {
isLoading,
isError,
data: isFollow,
} = useQuery({
queryKey: ["status", user.pubkey],
queryFn: async () => {
const res = await commands.checkContact(user.pubkey);

if (res.status === "ok") {
return res.data;
} else {
throw new Error(res.error);
}
},
refetchOnWindowFocus: false,
});

const [isPending, startTransition] = useTransition();

const toggleFollow = () => {
startTransition(async () => {
const res = await commands.toggleContact(user.pubkey, null);

if (res.status === "ok") {
setFollowed((prev) => !prev);
queryClient.setQueryData(
["status", user.pubkey],
(prev: boolean) => !prev,
);

// invalidate cache
await queryClient.invalidateQueries({
queryKey: ["status", user.pubkey],
});

return;
} else {
await message(res.error, { kind: "error" });
return;
}
});
};

useEffect(() => {
let mounted = true;

NostrAccount.checkContact(user.pubkey).then((status) => {
if (mounted) setFollowed(status);
});

return () => {
mounted = false;
};
}, []);

return (
<button
type="button"
disabled={isPending}
onClick={() => toggleFollow()}
className={cn("w-max", className)}
>
{isPending ? (
<Spinner className="size-4" />
) : followed ? (
!simple ? (
"Unfollow"
) : null
) : (
"Follow"
)}
{isError ? "Error" : null}
{isPending || isLoading ? <Spinner className="size-4" /> : null}
{isFollow ? "Unfollow" : "Follow"}
</button>
);
}
15 changes: 7 additions & 8 deletions src/components/user/nip05.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { commands } from "@/commands.gen";
import { displayLongHandle, displayNpub } from "@/commons";
import { NostrQuery } from "@/system";
import { SealCheck } from "@phosphor-icons/react";
import * as Tooltip from "@radix-ui/react-tooltip";
import { useQuery } from "@tanstack/react-query";
Expand All @@ -10,14 +10,13 @@ export function UserNip05() {
const { isLoading, data: verified } = useQuery({
queryKey: ["nip05", user?.pubkey],
queryFn: async () => {
if (!user.profile?.nip05?.length) return false;
const res = await commands.verifyNip05(user.pubkey, user.profile?.nip05);

const verify = await NostrQuery.verifyNip05(
user.pubkey,
user.profile?.nip05,
);

return verify;
if (res.status === "ok") {
return res.data;
} else {
throw new Error(res.error);
}
},
enabled: !!user.profile?.nip05?.length,
refetchOnMount: false,
Expand Down
25 changes: 18 additions & 7 deletions src/routes/$account/_app/home.lazy.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { commands } from "@/commands.gen";
import { Spinner } from "@/components";
import { Column } from "@/components/column";
import { LumeWindow, NostrQuery } from "@/system";
import { LumeWindow } from "@/system";
import type { ColumnEvent, LumeColumn } from "@/types";
import { ArrowLeft, ArrowRight, Plus, StackPlus } from "@phosphor-icons/react";
import { createLazyFileRoute } from "@tanstack/react-router";
Expand All @@ -24,7 +25,7 @@ export const Route = createLazyFileRoute("/$account/_app/home")({
});

function Screen() {
const initialColumnList = Route.useLoaderData();
const { initialColumns } = Route.useRouteContext();

const [columns, setColumns] = useState<LumeColumn[]>([]);
const [emblaRef, emblaApi] = useEmblaCarousel({
Expand Down Expand Up @@ -105,6 +106,18 @@ function Screen() {
event.preventDefault();
}, 150);

const saveAllColumns = useDebouncedCallback(async () => {
const key = "lume_v4:columns";
const content = JSON.stringify(columns);
const res = await commands.setLumeStore(key, content);

if (res.status === "ok") {
return res.data;
} else {
console.log(res.error);
}
}, 200);

useEffect(() => {
if (emblaApi) {
emblaApi.on("scroll", emitScrollEvent);
Expand All @@ -120,14 +133,12 @@ function Screen() {
}, [emblaApi, emitScrollEvent, emitResizeEvent]);

useEffect(() => {
if (columns) {
NostrQuery.setColumns(columns).then(() => console.log("saved"));
}
if (columns) saveAllColumns();
}, [columns]);

useEffect(() => {
setColumns(initialColumnList);
}, [initialColumnList]);
setColumns(initialColumns);
}, [initialColumns]);

// Listen for keyboard event
useEffect(() => {
Expand Down
12 changes: 7 additions & 5 deletions src/routes/$account/_app/home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,18 @@ import type { LumeColumn } from "@/types";
import { createFileRoute } from "@tanstack/react-router";

export const Route = createFileRoute("/$account/_app/home")({
loader: async ({ context }) => {
beforeLoad: async ({ context }) => {
const key = "lume_v4:columns";
const defaultColumns = context.systemColumns.filter((col) => col.default);
const query = await commands.getLumeStore(key);

let initialColumns: LumeColumn[] = defaultColumns;

if (query.status === "ok") {
const columns: LumeColumn[] = JSON.parse(query.data);
return columns;
} else {
return defaultColumns;
initialColumns = JSON.parse(query.data);
return { initialColumns };
}

return { initialColumns };
},
});
10 changes: 8 additions & 2 deletions src/routes/$account/_settings/bitcoin-connect.lazy.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { commands } from "@/commands.gen";
import { NostrAccount } from "@/system";
import { Button } from "@getalby/bitcoin-connect-react";
import { createLazyFileRoute } from "@tanstack/react-router";
Expand All @@ -11,8 +12,13 @@ export const Route = createLazyFileRoute("/$account/_settings/bitcoin-connect")(

function Screen() {
const setNwcUri = async (uri: string) => {
const cmd = await NostrAccount.setWallet(uri);
if (cmd) getCurrentWebviewWindow().close();
const res = await commands.setWallet(uri);

if (res.status === "ok") {
await getCurrentWebviewWindow().close();
} else {
throw new Error(res.error);
}
};

return (
Expand Down
Loading

0 comments on commit d128af1

Please sign in to comment.