wip: clean up & refactor

This commit is contained in:
Ren Amamiya
2023-08-16 20:52:09 +07:00
parent c05bb54976
commit ab61bfb2cd
79 changed files with 183 additions and 2618 deletions

View File

@@ -1,25 +1,2 @@
// get X days ago with user provided date
export function getDayAgo(numOfDays, date = new Date()) {
const days = new Date(date.getTime());
days.setDate(date.getDate() - numOfDays);
return days;
}
// get X hours ago with user provided date
export function getHourAgo(numOfHours, date = new Date()) {
const hours = new Date(date.getTime());
hours.setHours(date.getHours() - numOfHours);
return hours;
}
// convert date to unix timestamp
export function dateToUnix(_date?: Date) {
const date = _date || new Date();
return Math.floor(date.getTime() / 1000);
}
export const nHoursAgo = (hrs: number): number =>
Math.floor((Date.now() - hrs * 60 * 60 * 1000) / 1000);

View File

@@ -1,31 +0,0 @@
import { useQuery } from '@tanstack/react-query';
import { useNDK } from '@libs/ndk/provider';
import { useStorage } from '@libs/storage/provider';
export function useAccount() {
const { db } = useStorage();
const { ndk } = useNDK();
const { status, data: account } = useQuery(
['account'],
async () => {
const account = await db.getActiveAccount();
console.log('account: ', account);
if (account?.pubkey) {
const user = ndk.getUser({ hexpubkey: account?.pubkey });
await user.fetchProfile();
return { ...account, ...user.profile };
}
return account;
},
{
enabled: !!ndk,
staleTime: Infinity,
refetchOnMount: false,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
}
);
return { status, account };
}

View File

@@ -16,7 +16,7 @@ export function useEvent(id: string, embed?: string) {
return embed as unknown as LumeEvent;
} else {
const event = (await ndk.fetchEvent(id)) as LumeEvent;
if (!event) return null;
if (!event) throw new Error('event not found');
if (event.kind === 1) event['content'] = parser(event) as unknown as string;
return event as LumeEvent;
}

View File

@@ -6,7 +6,6 @@ import {
NDKSubscription,
NDKUser,
} from '@nostr-dev-kit/ndk';
import { destr } from 'destr';
import { LRUCache } from 'lru-cache';
import { nip19 } from 'nostr-tools';
import { useMemo } from 'react';
@@ -17,6 +16,14 @@ import { useStorage } from '@libs/storage/provider';
import { useStronghold } from '@stores/stronghold';
import { nHoursAgo } from '@utils/date';
import { LumeEvent } from '@utils/types';
interface NotesResponse {
status: string;
data: LumeEvent[];
nextCursor?: number;
message?: string;
}
export function useNostr() {
const { ndk } = useNDK();
@@ -37,6 +44,8 @@ export function useNostr() {
callback: (event: NDKEvent) => void,
closeOnEose?: boolean
) => {
if (!ndk) throw new Error('NDK instance not found');
const subEvent = ndk.subscribe(filter, { closeOnEose: closeOnEose ?? true });
subManager.set(JSON.stringify(filter), subEvent);
@@ -78,17 +87,22 @@ export function useNostr() {
}
};
const fetchNotes = async (since: number) => {
const fetchNotes = async (since: number): Promise<NotesResponse> => {
try {
if (!ndk) return { status: 'failed', message: 'NDK instance not found' };
if (!ndk) return { status: 'failed', data: [], message: 'NDK instance not found' };
console.log('fetch all events since: ', since);
const events = await ndk.fetchEvents({
kinds: [1],
authors: db.account.network ?? db.account.follows,
since: nHoursAgo(since),
});
return { status: 'ok', data: [...events], nextCursor: since * 2 };
const sorted = [...events].sort(
(a, b) => b.created_at - a.created_at
) as unknown as LumeEvent[];
return { status: 'ok', data: sorted, nextCursor: since * 2 };
} catch (e) {
console.error('failed get notes, error: ', e);
return { status: 'failed', data: [], message: e };
@@ -122,14 +136,6 @@ export function useNostr() {
};
const createZap = async (event: NDKEvent, amount: number, message?: string) => {
// @ts-expect-error, LumeEvent to NDKEvent
event.id = event.event_id;
// @ts-expect-error, LumeEvent to NDKEvent
if (typeof event.content !== 'string') event.content = event.content.original;
if (typeof event.tags === 'string') event.tags = destr(event.tags);
if (!privkey) throw new Error('Private key not found');
if (!ndk.signer) {
@@ -137,7 +143,7 @@ export function useNostr() {
ndk.signer = signer;
}
// @ts-expect-error, LumeEvent to NDKEvent
// @ts-expect-error, NostrEvent to NDKEvent
const ndkEvent = new NDKEvent(ndk, event);
const res = await ndkEvent.zap(amount, message ?? 'zap from lume');

View File

@@ -4,7 +4,7 @@ import { invoke } from '@tauri-apps/api/tauri';
import { Opengraph } from '@utils/types';
export function useOpenGraph(url: string) {
const { status, data, error, isFetching } = useQuery(
const { status, data, error } = useQuery(
['preview', url],
async () => {
const res: Opengraph = await invoke('opengraph', { url });
@@ -25,6 +25,5 @@ export function useOpenGraph(url: string) {
status,
data,
error,
isFetching,
};
}

View File

@@ -1,38 +0,0 @@
import { BaseDirectory, appConfigDir } from '@tauri-apps/api/path';
import { removeFile } from '@tauri-apps/plugin-fs';
import { Stronghold } from '@tauri-apps/plugin-stronghold';
const dir = await appConfigDir();
export function useSecureStorage() {
async function getClient(stronghold: Stronghold) {
try {
return await stronghold.loadClient('lume');
} catch {
return await stronghold.createClient('lume');
}
}
const save = async (key: string, value: string, password: string) => {
const stronghold = await Stronghold.load(`${dir}/lume.stronghold`, password);
const client = await getClient(stronghold);
const store = client.getStore();
await store.insert(key, Array.from(new TextEncoder().encode(value)));
return await stronghold.save();
};
const load = async (key: string, password: string) => {
const stronghold = await Stronghold.load(`${dir}/lume.stronghold`, password);
const client = await getClient(stronghold);
const store = client.getStore();
const value = await store.get(key);
const decoded = new TextDecoder().decode(new Uint8Array(value));
return decoded;
};
const reset = async () => {
return await removeFile('lume.stronghold', { dir: BaseDirectory.AppConfig });
};
return { save, load, reset };
}

View File

@@ -1,30 +1,5 @@
import { NDKTag } from '@nostr-dev-kit/ndk';
import { destr } from 'destr';
import { nip19 } from 'nostr-tools';
export function truncateContent(str, n) {
return str.length > n ? `${str.slice(0, n - 1)}...` : str;
}
export function setToArray(tags: any) {
const newArray = [];
tags.forEach((item) => {
const hexpubkey = nip19.decode(item.npub).data;
newArray.push(hexpubkey);
});
return newArray;
}
// convert NIP-02 to array of pubkey
export function nip02ToArray(tags: any) {
const arr = [];
tags.forEach((item) => {
arr.push(item[1]);
});
return arr;
}
// convert array to NIP-02 tag list
export function arrayToNIP02(arr: string[]) {
@@ -36,52 +11,9 @@ export function arrayToNIP02(arr: string[]) {
return nip02_arr;
}
// convert array object to pure array
export function arrayObjToPureArr(arr: any) {
const pure_arr = [];
arr.forEach((item) => {
pure_arr.push(item.content);
});
return pure_arr;
}
// get parent id from event tags
export function getParentID(arr: string[][], fallback: string) {
const tags = destr(arr);
let parentID = fallback;
if (tags.length > 0) {
if (tags[0][0] === 'e') {
parentID = tags[0][1];
} else {
tags.forEach((tag) => {
if (tag[0] === 'e' && (tag[2] === 'root' || tag[3] === 'root')) {
parentID = tag[1];
}
});
}
}
return parentID;
}
// check id present in event tags
export function isTagsIncludeID(id: string, arr: NDKTag[]) {
const tags = destr(arr);
if (tags.length > 0) {
if (tags[0][1] === id) {
return true;
}
} else {
return false;
}
}
// get parent id from event tags
// get repost id from event tags
export function getRepostID(arr: NDKTag[]) {
const tags = destr(arr);
const tags = destr(arr) as string[];
let quoteID = null;
if (tags.length > 0) {
@@ -94,12 +26,3 @@ export function getRepostID(arr: NDKTag[]) {
return quoteID;
}
// sort events by timestamp
export function sortEvents(arr: any) {
arr.sort((a, b) => {
return a.created_at - b.created_at;
});
return arr;
}