This commit is contained in:
KoalaSat 2022-10-25 04:29:59 +02:00
parent 5cd9db514f
commit fd2134897f
No known key found for this signature in database
GPG Key ID: 2F7F61C6146AB157
22 changed files with 274 additions and 237 deletions

View File

@ -1 +0,0 @@

View File

@ -2,11 +2,12 @@
![nostros_logo](https://user-images.githubusercontent.com/111684255/197588983-2a196d74-0f1e-45e8-be56-0da8c1602835.png)
Wellcome to the NOSTROS project.
Wellcome to the NOSTROS project.
# Getting Started
## Required Libraries and Frameworks
- Node 16.x
- JDK 17.0.x
- (Android) Android Studio SKD
@ -16,41 +17,60 @@ Wellcome to the NOSTROS project.
- Open a virtual device
- Install
```
yarn install
```
- Run Metro
```
yarn start
```
# Some Features to Work On
### Bugs
- [ ] User info missing on first start
- [ ] i18n not loading
- [ ] Logging out and in again does not work
- [ ] Clipboard library not working
### Basics
- [ ] Infinite Load
- [ ] Go to replied event
- [ ] Relays management (add, remove and recomend)
- [ ] Random Key Generator
### Home
- [ ] Public Room
- [ ] Other Rooms
### Profile
### Profile
- [ ] Verify NIP-05
- [ ] Verify LNURL https://github.com/andrerfneves/lightning-address
### Contacts
- [ ] Direct Messages https://github.com/nostr-protocol/nips/blob/master/04.md
### Note
- [ ] Mentions https://github.com/nostr-protocol/nips/blob/master/08.md
- [ ] Reactions https://github.com/nostr-protocol/nips/blob/master/25.md
- [ ] Deletion https://github.com/nostr-protocol/nips/blob/master/09.md
- [ ] Tag Users https://github.com/nostr-protocol/nips/blob/master/10.md
### Send
- [ ] Mentions https://github.com/nostr-protocol/nips/blob/master/08.md
### Config
- [ ] Private Key download
# Kudos
@ -58,6 +78,6 @@ yarn start
- Inspired on https://github.com/jb55/nostr-js and https://github.com/fiatjaf/nostr-tools
- Discovered thanks to https://lunaticoin.com
------
---
Made with 🐨 by https://getalby.com/p/koalasat

View File

@ -17,7 +17,7 @@ import { RelayPoolContext } from '../../Contexts/RelayPoolContext';
export const ConfigPage: React.FC = () => {
const theme = useTheme();
const { setPage, page, database } = useContext(AppContext);
const { setPrivateKey } = useContext(RelayPoolContext);
const { setPrivateKey, relayPool } = useContext(RelayPoolContext);
const { t } = useTranslation('common');
const breadcrump = page.split('%');
@ -26,10 +26,13 @@ export const ConfigPage: React.FC = () => {
};
const onPressLogout: () => void = () => {
setPrivateKey('')
EncryptedStorage.removeItem('privateKey');
if (database) {
dropTables(database).then(() => setPage('landing'))
dropTables(database).then(() => {
setPrivateKey('');
relayPool?.unsubscribeAll();
EncryptedStorage.removeItem('privateKey');
setPage('landing');
});
}
};
@ -67,7 +70,9 @@ export const ConfigPage: React.FC = () => {
<Button
onPress={onPressLogout}
status='danger'
accessoryLeft={<Icon name='power-off' size={16} color={theme['text-basic-color']} solid />}
accessoryLeft={
<Icon name='power-off' size={16} color={theme['text-basic-color']} solid />
}
>
{t('configPage.logout')}
</Button>

View File

@ -6,7 +6,12 @@ import { AppContext } from '../../Contexts/AppContext';
import Icon from 'react-native-vector-icons/FontAwesome5';
import { Event, EventKind } from '../../lib/nostr/Events';
import { useTranslation } from 'react-i18next';
import { addContact, getUsers, insertUserContact, User } from '../../Functions/DatabaseFunctions/Users';
import {
addContact,
getUsers,
insertUserContact,
User,
} from '../../Functions/DatabaseFunctions/Users';
import UserCard from '../UserCard';
import { RelayPoolContext } from '../../Contexts/RelayPoolContext';
import Relay from '../../lib/nostr/Relay';
@ -22,7 +27,7 @@ export const ContactsPage: React.FC = () => {
const { t } = useTranslation('common');
useEffect(() => {
if (database) {
if (database && publicKey) {
getUsers(database, { contacts: true }).then((results) => {
if (results) {
setUsers(results);
@ -37,19 +42,18 @@ export const ContactsPage: React.FC = () => {
useEffect(() => {
relayPool?.on('event', 'contacts', (relay: Relay, _subId?: string, event?: Event) => {
console.log('RELAYPOOL EVENT =======>', relay.url, event);
if (database && event?.id && event.kind === EventKind.petNames) {
insertUserContact(event, database).finally(() => setLastEventId(event?.id ?? ''));
}
},
);
}, [])
console.log('RELAYPOOL EVENT =======>', relay.url, event);
if (database && event?.id && event.kind === EventKind.petNames) {
insertUserContact(event, database).finally(() => setLastEventId(event?.id ?? ''));
}
});
}, []);
const onPressAddContact: () => void = () => {
if (contactInput && relayPool && database) {
if (contactInput && relayPool && database && publicKey) {
addContact(contactInput, database).then(() => {
populatePets(relayPool, database, publicKey)
setShowAddContant(false)
populatePets(relayPool, database, publicKey);
setShowAddContant(false);
});
}
};
@ -125,4 +129,3 @@ export const ContactsPage: React.FC = () => {
};
export default ContactsPage;

View File

@ -31,10 +31,10 @@ export const HomePage: React.FC = () => {
};
const subscribeNotes: () => void = () => {
if (database) {
if (database && publicKey) {
getNotes(database, { limit: 1 }).then((notes) => {
getUsers(database, { contacts: true }).then((users) => {
setTotalContacts(users.length)
setTotalContacts(users.length);
let message: RelayFilters = {
kinds: [EventKind.textNote, EventKind.recommendServer],
authors: [publicKey, ...users.map((user) => user.id)],
@ -55,7 +55,7 @@ export const HomePage: React.FC = () => {
};
useEffect(() => {
loadNotes()
loadNotes();
}, [lastEventId]);
useEffect(() => {

View File

@ -5,25 +5,22 @@ import Loading from '../Loading';
import { RelayPoolContext } from '../../Contexts/RelayPoolContext';
import { useTranslation } from 'react-i18next';
import { tagToUser } from '../../Functions/RelayFunctions/Users';
import Relay, { RelayFilters } from '../../lib/nostr/Relay';
import Relay from '../../lib/nostr/Relay';
import { Event, EventKind } from '../../lib/nostr/Events';
import { AppContext } from '../../Contexts/AppContext';
import { getUsers, insertUserContact } from '../../Functions/DatabaseFunctions/Users';
import { getPublickey } from '../../lib/nostr/Bip';
import { insertUserContact } from '../../Functions/DatabaseFunctions/Users';
import EncryptedStorage from 'react-native-encrypted-storage';
import { SQLiteDatabase } from 'react-native-sqlite-storage';
export const LandingPage: React.FC = () => {
const { privateKey, setPrivateKey, publicKey, setPublicKey, relayPool, initRelays } =
useContext(RelayPoolContext);
const { database, setPage, runMigrations, loadingDb } = useContext(AppContext);
const { database, setPage } = useContext(AppContext);
const { privateKey, publicKey, relayPool, setPrivateKey } = useContext(RelayPoolContext);
const { t } = useTranslation('common');
const [init, setInit] = useState<boolean>(true);
const [loading, setLoading] = useState<boolean>(false);
const [status, setStatus] = useState<number>(0);
const [totalPets, setTotalPets] = useState<number>();
const [loadedUsers, setLoadedUsers] = useState<number>(0);
const [usersReady, setUsersReady] = useState<boolean>(false);
const [inputValue, setInputValue] = useState<string>('');
const [loadedUsers, setLoadedUsers] = useState<number>();
const [loadedNotes, setLoadedNotes] = useState<number>();
const styles = StyleSheet.create({
tab: {
height: '100%',
@ -45,110 +42,97 @@ export const LandingPage: React.FC = () => {
},
});
useEffect(() => { // #1 STEP
if (init) {
EncryptedStorage.getItem('privateKey').then((result) => {
if (result && result !== '') {
setPrivateKey(result);
setPublicKey(getPublickey(result));
setUsersReady(true);
} if (!loadingDb) {
setInit(false);
} else {
runMigrations();
}
useEffect(() => {
// #1 STEP
if (relayPool && publicKey) {
setStatus(1);
initEvents();
relayPool?.subscribe('main-channel', {
kinds: [EventKind.petNames],
authors: [publicKey],
});
}
}, [init, relayPool, loadingDb]);
}, [relayPool, publicKey]);
useEffect(() => {
if (usersReady && relayPool && !loadingDb) {
initRelays()
if (status > 3) {
relayPool?.removeOn('event', 'landing');
setPage('home');
}
}, [usersReady, relayPool]);
}, [status]);
useEffect(() => {
if (loading && publicKey !== '') {
initEvents();
if (loadedUsers ?? loadedNotes) {
const timer = setTimeout(() => setStatus(4), 4000);
return () => {
clearTimeout(timer);
};
}
}, [loading, publicKey]);
useEffect(() => {
if (loading && loadedUsers) {
loadUsers();
}
}, [loading, totalPets, loadedUsers]);
}, [loadedUsers, loadedNotes]);
const initEvents: () => void = () => {
relayPool?.on('event', 'landing', (_relay: Relay, _subId?: string, event?: Event) => {
if (database && event) {
console.log('LandingPage EVENT =======>', event);
if (event && database) {
if (event.kind === EventKind.petNames) {
loadPets(event);
} else {
if (event.kind === EventKind.meta && event.pubkey !== publicKey) {
setLoadedUsers((prev) => prev + 1)
}
loadPets(event);
} else if (event.kind === EventKind.meta) {
setLoadedUsers((prev) => (prev ? prev + 1 : 1));
if (loadedUsers && loadedUsers - 1 === totalPets) setStatus(3);
} else if (event.kind === EventKind.textNote) {
setLoadedNotes((prev) => (prev ? prev + 1 : 1));
}
}
});
relayPool?.subscribe('main-channel', {
kinds: [EventKind.meta, EventKind.petNames],
authors: [publicKey],
});
};
const loadPets: (event: Event) => void = (event) => {
if (database) {
setTotalPets(event.tags.length);
insertUserContact(event, database).then(() => {
relayPool?.subscribe('main-channel', {
kinds: [EventKind.meta],
authors: event.tags.map((tag) => tagToUser(tag).id),
if (event.tags.length > 0) {
setStatus(2);
insertUserContact(event, database).then(() => {
requestUserData(event);
});
})
setStatus(2);
} else {
setStatus(4);
}
}
};
const requestUsers: (database: SQLiteDatabase) => void = () => {
if (database && status < 3) {
setUsersReady(true);
getUsers(database, { exludeIds: [publicKey], contacts: true }).then((users) => {
const message: RelayFilters = {
kinds: [EventKind.textNote, EventKind.recommendServer],
authors: [publicKey, ...users.map((user) => user.id)],
limit: 15,
};
relayPool?.subscribe('main-channel', message);
setStatus(3);
})
}
}
const loadUsers: () => void = () => {
if (database) {
getUsers(database, { exludeIds: [publicKey], contacts: true }).then((users) => {
if (loadedUsers === totalPets) {
requestUsers(database)
}
const requestUserData: (event: Event) => void = (event) => {
if (publicKey) {
const authors: string[] = [publicKey, ...event.tags.map((tag) => tagToUser(tag).id)];
relayPool?.subscribe('main-channel', {
kinds: [EventKind.meta],
authors,
});
relayPool?.subscribe('main-channel', {
kinds: [EventKind.textNote, EventKind.recommendServer],
authors,
limit: 20,
});
relayPool?.subscribe('main-channel', {
kinds: [EventKind.textNote, EventKind.recommendServer],
authors: [publicKey],
limit: 10,
});
setTimeout(() => requestUsers(database), 10000);
}
};
const onPress: () => void = () => {
setLoading(true);
setPublicKey(getPublickey(privateKey));
setPrivateKey(inputValue);
setStatus(1);
EncryptedStorage.setItem('privateKey', privateKey);
EncryptedStorage.setItem('privateKey', inputValue);
};
const statusName: { [status: number]: string } = {
0: t('landing.connect'),
1: t('landing.connecting'),
2: `${t('landing.loadingContacts')} ${loadedUsers}/${totalPets ?? 0}`,
2: t('landing.loadingContacts'),
3: t('landing.loadingTimeline'),
4: t('landing.ready'),
};
return (
@ -159,15 +143,15 @@ export const LandingPage: React.FC = () => {
<Text style={styles.title} category='h1'>
NOSTROS
</Text>
{!init && (
{(!privateKey || status !== 0) && (
<>
<Input
style={styles.input}
size='medium'
label={t('landing.privateKey')}
secureTextEntry={true}
onChangeText={setPrivateKey}
value={privateKey}
onChangeText={setInputValue}
value={inputValue}
disabled={loading}
/>
<Button onPress={onPress} disabled={loading}>

View File

@ -15,7 +15,7 @@ import ConfigPage from '../ConfigPage';
export const MainLayout: React.FC = () => {
const { page } = useContext(AppContext);
const { relayPool } = useContext(RelayPoolContext);
const [lastPage, setLastPage] = useState<string>(page)
const [lastPage, setLastPage] = useState<string>(page);
const styles = StyleSheet.create({
container: {
@ -38,26 +38,36 @@ export const MainLayout: React.FC = () => {
const clearSubscriptions: () => boolean = () => {
if (relayPool && lastPage && lastPage !== page) {
relayPool.unsubscribeAll()
relayPool.removeOn('event', lastPage)
setLastPage(page)
relayPool.unsubscribeAll();
relayPool.removeOn('event', lastPage);
setLastPage(page);
}
return true
}
return true;
};
return page === 'landing' ? (
<Layout style={styles.container} level='4'>
<LandingPage />
</Layout>
) : (
<>
<Layout style={styles.container} level='4'>
{clearSubscriptions() && pagination[pageToDisplay]}
</Layout>
<NavigationBar />
</>
);
const view: () => JSX.Element = () => {
if (page === '') {
return <Layout style={styles.container} level='4' />;
} else if (page === 'landing') {
return (
<Layout style={styles.container} level='4'>
<LandingPage />
</Layout>
);
} else {
return (
<>
<Layout style={styles.container} level='4'>
{clearSubscriptions() && (pagination[pageToDisplay] ?? <></>)}
</Layout>
<NavigationBar />
</>
);
}
};
return view();
};
export default MainLayout;

View File

@ -13,7 +13,7 @@ export const NavigationBar: React.FC = () => {
const getIndex: () => number = () => {
if (page.includes('profile#')) {
return page === `profile#${publicKey}` ? 2 : 1;
return publicKey && page === `profile#${publicKey}` ? 2 : 1;
} else if (page.includes('note#')) {
return 0;
} else {

View File

@ -76,7 +76,7 @@ export const NoteCard: React.FC<NoteCardProps> = ({ note }) => {
relayPool.add(note.content);
setRelayPool(relayPool);
storeRelay({ url: note.content }, database);
populateRelay(relayPool, database, publicKey)
populateRelay(relayPool, database, publicKey);
showMessage({
message: t('alerts.relayAdded'),
description: note.content,

View File

@ -34,7 +34,7 @@ export const NotePage: React.FC = () => {
getNotes(database, { filters: { id: eventId } }).then((events) => {
if (events.length > 0) {
const event = events[0];
setNote(event)
setNote(event);
getNotes(database, { filters: { reply_event_id: eventId } }).then((notes) => {
const rootReplies = getDirectReplies(notes, event);
if (rootReplies.length > 0) {
@ -62,7 +62,6 @@ export const NotePage: React.FC = () => {
}, [lastEventId, page]);
const onPressBack: () => void = () => {
console.log(breadcrump.slice(0, -1).join('%'))
setPage(breadcrump.slice(0, -1).join('%'));
};
@ -83,7 +82,7 @@ export const NotePage: React.FC = () => {
} else if (note.id) {
setPage(`${page}%note#${note.id}`);
}
setReplies([])
setReplies([]);
}
};
@ -93,7 +92,7 @@ export const NotePage: React.FC = () => {
<Layout style={styles.main} level='2'>
<NoteCard note={note} />
</Layout>
)
);
} else if (note) {
return (
<Card onPress={() => onPressNote(note)}>

View File

@ -46,8 +46,8 @@ export const ProfilePage: React.FC = () => {
const username = user?.name === '' ? user?.id : user?.name;
useEffect(() => {
setUser(null)
setNotes([])
setUser(null);
setNotes([]);
relayPool?.on('event', 'profile', (_relay: Relay, _subId?: string, event?: Event) => {
console.log('PROFILE EVENT =======>', event);
if (database && event?.id && event.pubkey === userId) {
@ -56,7 +56,7 @@ export const ProfilePage: React.FC = () => {
setContactsIds(ids);
} else if (event.kind === EventKind.meta) {
storeEvent(event, database).finally(() => {
if (event?.id) setLastEventId(event.id)
if (event?.id) setLastEventId(event.id);
});
}
}
@ -101,8 +101,8 @@ export const ProfilePage: React.FC = () => {
const removeAuthor: () => void = () => {
if (relayPool && database) {
removeContact(userId, database).then(() => {
populatePets(relayPool, database, publicKey)
setIsContact(false)
populatePets(relayPool, database, publicKey);
setIsContact(false);
});
}
};
@ -110,8 +110,8 @@ export const ProfilePage: React.FC = () => {
const addAuthor: () => void = () => {
if (relayPool && database) {
addContact(userId, database).then(() => {
populatePets(relayPool, database, publicKey)
setIsContact(true)
populatePets(relayPool, database, publicKey);
setIsContact(true);
});
}
};
@ -119,11 +119,11 @@ export const ProfilePage: React.FC = () => {
const renderOptions: () => JSX.Element = () => {
if (publicKey === userId) {
return (
<TopNavigationAction
icon={<Icon name='dna' size={16} color={theme['text-basic-color']} solid />}
onPress={() => setPage('config')}
/>
);
<TopNavigationAction
icon={<Icon name='dna' size={16} color={theme['text-basic-color']} solid />}
onPress={() => setPage('config')}
/>
);
} else {
if (user) {
if (isContact) {

View File

@ -75,7 +75,7 @@ export const SendPage: React.FC = () => {
tags,
};
relayPool?.sendEvent(event);
setNoteId(note.id)
setNoteId(note.id);
setSending(true);
});
};

View File

@ -1,13 +1,13 @@
import React, { useState } from 'react';
import React, { useEffect, useState } from 'react';
import { SQLiteDatabase } from 'react-native-sqlite-storage';
import { initDatabase } from '../Functions/DatabaseFunctions';
import { createInitDatabase } from '../Functions/DatabaseFunctions/Migrations';
import FlashMessage from 'react-native-flash-message';
import EncryptedStorage from 'react-native-encrypted-storage';
export interface AppContextProps {
page: string;
setPage: (page: string) => void;
runMigrations: () => void;
loadingDb: boolean;
database: SQLiteDatabase | null;
}
@ -17,9 +17,8 @@ export interface AppContextProviderProps {
}
export const initialAppContext: AppContextProps = {
page: 'landing',
page: '',
setPage: () => {},
runMigrations: () => {},
loadingDb: true,
database: null,
};
@ -29,13 +28,17 @@ export const AppContextProvider = ({ children }: AppContextProviderProps): JSX.E
const [database, setDatabase] = useState<SQLiteDatabase | null>(null);
const [loadingDb, setLoadingDb] = useState<boolean>(initialAppContext.loadingDb);
const runMigrations: () => void = async () => {
const db = initDatabase()
setDatabase(db)
createInitDatabase(db).then(() => {
setLoadingDb(false);
useEffect(() => {
EncryptedStorage.getItem('privateKey').then((result) => {
const db = initDatabase();
setDatabase(db);
if (!result || result === '') {
createInitDatabase(db).then(() => {
setLoadingDb(false);
});
}
});
};
}, []);
return (
<AppContext.Provider
@ -44,7 +47,6 @@ export const AppContextProvider = ({ children }: AppContextProviderProps): JSX.E
setPage,
loadingDb,
database,
runMigrations,
}}
>
{children}

View File

@ -6,19 +6,18 @@ import { AppContext } from './AppContext';
import { storeEvent } from '../Functions/DatabaseFunctions/Events';
import { getRelays, Relay as RelayEntity, storeRelay } from '../Functions/DatabaseFunctions/Relays';
import { showMessage } from 'react-native-flash-message';
import EncryptedStorage from 'react-native-encrypted-storage';
import { getPublickey } from '../lib/nostr/Bip';
export interface RelayPoolContextProps {
relayPool?: RelayPool;
setRelayPool: (relayPool: RelayPool) => void;
publicKey: string;
publicKey?: string;
setPublicKey: (privateKey: string) => void;
privateKey: string;
privateKey?: string;
setPrivateKey: (privateKey: string) => void;
lastEventId?: string;
setLastEventId: (lastEventId: string) => void;
loadingRelays: boolean;
initRelays: () => void;
loadRelays: () => void;
}
export interface RelayPoolContextProviderProps {
@ -26,56 +25,24 @@ export interface RelayPoolContextProviderProps {
}
export const initialRelayPoolContext: RelayPoolContextProps = {
publicKey: '',
setPublicKey: () => {},
privateKey: '',
setPrivateKey: () => {},
setRelayPool: () => {},
setLastEventId: () => {},
loadingRelays: true,
initRelays: () => {},
loadRelays: () => {},
};
export const RelayPoolContextProvider = ({
children,
}: RelayPoolContextProviderProps): JSX.Element => {
const { database, loadingDb } = useContext(AppContext);
const { database, loadingDb, setPage } = useContext(AppContext);
const [publicKey, setPublicKey] = useState<string>('');
const [privateKey, setPrivateKey] = useState<string>('');
const [publicKey, setPublicKey] = useState<string>();
const [privateKey, setPrivateKey] = useState<string>();
const [relayPool, setRelayPool] = useState<RelayPool>();
const [lastEventId, setLastEventId] = useState<string>();
const [loadingRelays, setLoadingRelays] = useState<boolean>(true);
const initRelays: () => void = () => {
relayPool?.on(
'notice',
'RelayPoolContextProvider',
(relay: Relay, _subId?: string, event?: Event) => {
showMessage({
message: relay.url,
description: event?.content ?? '',
type: 'info',
});
},
);
relayPool?.on(
'event',
'RelayPoolContextProvider',
(relay: Relay, _subId?: string, event?: Event) => {
console.log('RELAYPOOL EVENT =======>', relay.url, event);
if (database && event?.id && event.kind !== EventKind.petNames) {
storeEvent(event, database).finally(() => setLastEventId(event.id));
}
},
);
setLoadingRelays(false);
};
const loadRelays: () => void = () => {
if (database) {
const loadRelayPool: () => void = () => {
if (database && privateKey) {
getRelays(database).then((relays: RelayEntity[]) => {
const initRelayPool = new RelayPool([], privateKey);
if (relays.length > 0) {
@ -88,16 +55,56 @@ export const RelayPoolContextProvider = ({
storeRelay({ url: relayUrl }, database);
});
}
initRelayPool?.on(
'notice',
'RelayPoolContextProvider',
(relay: Relay, _subId?: string, event?: Event) => {
showMessage({
message: relay.url,
description: event?.content ?? '',
type: 'info',
});
},
);
initRelayPool?.on(
'event',
'RelayPoolContextProvider',
(relay: Relay, _subId?: string, event?: Event) => {
console.log('RELAYPOOL EVENT =======>', relay.url, event);
if (database && event?.id && event.kind !== EventKind.petNames) {
storeEvent(event, database).finally(() => setLastEventId(event.id));
}
},
);
setRelayPool(initRelayPool);
})
});
}
}
};
useEffect(() => {
if (privateKey !== '' && !loadingDb && loadingRelays) {
loadRelays()
if (privateKey) {
setPublicKey(getPublickey(privateKey));
}
}, [privateKey, loadingDb])
}, [privateKey]);
useEffect(() => {
if (privateKey !== '' && !loadingDb && !relayPool) {
loadRelayPool();
}
}, [privateKey, loadingDb]);
useEffect(() => {
EncryptedStorage.getItem('privateKey').then((result) => {
if (result && result !== '') {
setPage('home');
setPrivateKey(result);
} else {
setPrivateKey('');
setPage('landing');
}
});
}, []);
return (
<RelayPoolContext.Provider
@ -110,9 +117,6 @@ export const RelayPoolContextProvider = ({
setPrivateKey,
lastEventId,
setLastEventId,
loadingRelays,
initRelays,
loadRelays,
}}
>
{children}

View File

@ -40,8 +40,8 @@ export const createInitDatabase: (db: SQLiteDatabase) => Promise<void> = async (
);
`,
db,
).then(() => resolve())
})
})
})
).then(() => resolve());
});
});
});
};

View File

@ -20,7 +20,8 @@ export const insertNote: (event: Event, db: SQLiteDatabase) => Promise<void> = a
) => {
return await new Promise<void>((resolve, reject) => {
if (!verifySignature(event) || !event.id) return reject(new Error('Bad event'));
if (![EventKind.textNote, EventKind.recommendServer].includes(event.kind)) return reject(new Error('Bad Kind'));
if (![EventKind.textNote, EventKind.recommendServer].includes(event.kind))
return reject(new Error('Bad Kind'));
getNotes(db, { filters: { id: event.id } }).then((notes) => {
if (notes.length === 0 && event.id && event.sig) {

View File

@ -49,7 +49,9 @@ export const insertUserMeta: (event: Event, db: SQLiteDatabase) => Promise<void>
INSERT INTO nostros_users
(id, name, picture, about, main_relay)
VALUES
('${id}', '${name.split("'").join("''")}', '${picture.split("'").join("''")}', '${about.split("'").join("''")}', '');
('${id}', '${name.split("'").join("''")}', '${picture.split("'").join("''")}', '${about
.split("'")
.join("''")}', '');
`;
}
db.transaction((transaction) => {

View File

@ -19,26 +19,24 @@ export const getItems: (resultSet: ResultSet) => object[] = (resultSet) => {
return result;
};
export const simpleExecute: (query: string, db: SQLiteDatabase) => Promise<Transaction> = async (query, db) => {
export const simpleExecute: (query: string, db: SQLiteDatabase) => Promise<Transaction> = async (
query,
db,
) => {
return await db.transaction((transaction) => {
transaction.executeSql(query, [], () => {}, errorCallback(query));
})
});
};
export const dropTables: (db: SQLiteDatabase) => Promise<Transaction> = async (db) => {
const dropQueries = [
'DROP TABLE IF EXISTS nostros_notes;',
'DROP TABLE IF EXISTS nostros_users;',
'DROP TABLE IF EXISTS nostros_relays;'
]
'DROP TABLE IF EXISTS nostros_relays;',
];
return await db.transaction((transaction) => {
dropQueries.forEach((query) => {
transaction.executeSql(
query,
[],
() => {},
errorCallback(query),
);
})
transaction.executeSql(query, [], () => {}, errorCallback(query));
});
});
};

View File

@ -22,7 +22,7 @@ export const getReplyEventId: (event: Event) => string | null = (event) => {
if (!mainTag) {
mainTag = eTags[eTags.length - 1];
}
return mainTag ? mainTag[1] : null;
};

View File

@ -24,7 +24,11 @@ export const tagToUser: (tag: string[]) => User = (tag) => {
};
};
export const populatePets: (relayPool: RelayPool, database: SQLiteDatabase, publicKey: string) => void = (relayPool, database, publicKey) => {
export const populatePets: (
relayPool: RelayPool,
database: SQLiteDatabase,
publicKey: string,
) => void = (relayPool, database, publicKey) => {
getUsers(database, { exludeIds: [publicKey], contacts: true }).then((results) => {
if (results) {
const event: Event = {
@ -37,17 +41,21 @@ export const populatePets: (relayPool: RelayPool, database: SQLiteDatabase, publ
relayPool?.sendEvent(event);
}
});
}
};
export const populateProfile: (relayPool: RelayPool, database: SQLiteDatabase, publicKey: string) => void = (relayPool, database, publicKey) => {
export const populateProfile: (
relayPool: RelayPool,
database: SQLiteDatabase,
publicKey: string,
) => void = (relayPool, database, publicKey) => {
getUser(publicKey, database).then((result) => {
if (result) {
const profile = {
name: result.name,
main_relay: result.main_relay,
picture: result.picture,
about: result.about
}
about: result.about,
};
const event: Event = {
content: JSON.stringify(profile),
created_at: moment().unix(),
@ -58,6 +66,4 @@ export const populateProfile: (relayPool: RelayPool, database: SQLiteDatabase, p
relayPool?.sendEvent(event);
}
});
}
};

View File

@ -1,8 +1,12 @@
import { SQLiteDatabase } from "react-native-sqlite-storage"
import RelayPool from "../../lib/nostr/RelayPool/intex"
import { populatePets, populateProfile } from "./Users"
import { SQLiteDatabase } from 'react-native-sqlite-storage';
import RelayPool from '../../lib/nostr/RelayPool/intex';
import { populatePets, populateProfile } from './Users';
export const populateRelay: (relayPool: RelayPool, database: SQLiteDatabase, publicKey: string) => void = (relayPool, database, publicKey) => {
populateProfile(relayPool, database, publicKey)
populatePets(relayPool, database, publicKey)
}
export const populateRelay: (
relayPool: RelayPool,
database: SQLiteDatabase,
publicKey: string,
) => void = (relayPool, database, publicKey) => {
populateProfile(relayPool, database, publicKey);
populatePets(relayPool, database, publicKey);
};

View File

@ -110,12 +110,12 @@ class RelayPool {
relay.sendEvent(signedEvent);
});
return signedEvent
return signedEvent;
} else {
console.log('Not valid event', event);
}
return null
return null;
};
public readonly subscribe: (subId: string, filters?: RelayFilters) => void = (subId, filters) => {