Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Nostr Contacts to Flash App #329

Draft
wants to merge 8 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
244 changes: 87 additions & 157 deletions app/screens/nip17-chat/NIP17Chat.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { SearchBar } from "@rneui/base"
import { useTheme } from "@rneui/themed"
import * as React from "react"
import { useCallback, useState } from "react"
Expand All @@ -7,15 +6,15 @@ import { FlatList } from "react-native-gesture-handler"
import Icon from "react-native-vector-icons/Ionicons"

import { Screen } from "../../components/screen"
import { bytesToHex } from "@noble/hashes/utils"
import { testProps } from "../../utils/testProps"

import { useI18nContext } from "@app/i18n/i18n-react"
import { Event, SubCloser, getPublicKey, nip05, nip19 } from "nostr-tools"
import { getPublicKey, nip19 } from "nostr-tools"
import {
convertRumorsToGroups,
fetchNostrUsers,
fetchSecretFromLocalStorage,
getGroupId,
} from "@app/utils/nostr"
import { useStyles } from "./style"
import { SearchListItem } from "./searchListItem"
Expand All @@ -27,10 +26,14 @@ import { useAppSelector } from "@app/store/redux"
import { ImportNsecModal } from "./import-nsec"
import { useIsAuthed } from "@app/graphql/is-authed-context"
import { useHomeAuthedQuery } from "@app/graphql/generated"
import { createMaterialTopTabNavigator } from "@react-navigation/material-top-tabs"
import Contacts from "./contacts"
import { UserSearchBar } from "./UserSearchBar"

const Tab = createMaterialTopTabNavigator()

export const NIP17Chat: React.FC = () => {
const styles = useStyles()
const { appConfig } = useAppConfig()
const {
theme: { colors },
} = useTheme()
Expand All @@ -42,8 +45,6 @@ export const NIP17Chat: React.FC = () => {
errorPolicy: "all",
})
const { rumors, poolRef, addEventToProfiles, profileMap, resetChat } = useChatContext()
const [searchText, setSearchText] = useState("")
const [refreshing, setRefreshing] = useState(false)
const [initialized, setInitialized] = useState(false)
const [searchedUsers, setSearchedUsers] = useState<Chat[]>([])
const [privateKey, setPrivateKey] = useState<Uint8Array>()
Expand All @@ -52,24 +53,6 @@ export const NIP17Chat: React.FC = () => {
const { LL } = useI18nContext()
const { userData } = useAppSelector((state) => state.user)

const reset = useCallback(() => {
setSearchText("")
setSearchedUsers([])
setRefreshing(false)
setskipMismatchCheck(true)
}, [])

const searchedUsersHandler = (event: Event, closer: SubCloser) => {
let nostrProfile = JSON.parse(event.content)
addEventToProfiles(event)
let userPubkey = getPublicKey(privateKey!)
let participants = [event.pubkey, userPubkey]
setSearchedUsers([
{ ...nostrProfile, id: event.pubkey, groupId: getGroupId(participants) },
])
closer.close()
}

React.useEffect(() => {
const unsubscribe = () => {
console.log("unsubscribing")
Expand Down Expand Up @@ -114,93 +97,19 @@ export const NIP17Chat: React.FC = () => {
}
}
if (initialized) {
setSearchText("")
setSearchedUsers([])
checkSecretKey()
}
}, [setSearchText, setSearchedUsers, dataAuthed, isAuthed, skipMismatchCheck]),
)

const updateSearchResults = useCallback(
async (newSearchText: string) => {
const nip05Matching = async (alias: string) => {
let nostrUser = await nip05.queryProfile(alias.toLocaleLowerCase())
console.log("nostr user for", alias, nostrUser)
if (nostrUser) {
let nostrProfile = profileMap?.get(nostrUser.pubkey)
let userPubkey = getPublicKey(privateKey!)
let participants = [nostrUser.pubkey, userPubkey]
setSearchedUsers([
{
id: nostrUser.pubkey,
username: alias,
...nostrProfile,
groupId: getGroupId(participants),
},
])
if (!nostrProfile)
fetchNostrUsers([nostrUser.pubkey], poolRef!.current, searchedUsersHandler)
return true
}
return false
}
const aliasPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/
if (!privateKey) {
Alert.alert("User Profile not yet loaded")
return
}
if (!newSearchText) {
setRefreshing(false)
}
setRefreshing(true)
setSearchText(newSearchText)
if (newSearchText.startsWith("npub1") && newSearchText.length == 63) {
let hexPubkey = nip19.decode(newSearchText).data as string
let userPubkey = getPublicKey(privateKey)
let participants = [hexPubkey, userPubkey]
setSearchedUsers([{ id: hexPubkey, groupId: getGroupId(participants) }])
fetchNostrUsers([hexPubkey], poolRef!.current, searchedUsersHandler)
setRefreshing(false)
return
} else if (newSearchText.match(aliasPattern)) {
if (await nip05Matching(newSearchText)) {
setRefreshing(false)
return
}
} else if (!newSearchText.includes("@")) {
let modifiedSearchText =
newSearchText + "@" + appConfig.galoyInstance.lnAddressHostname
console.log("Searching for", modifiedSearchText)
if (await nip05Matching(modifiedSearchText)) {
setRefreshing(false)
return
}
}
},
[privateKey],
}, [setSearchedUsers, dataAuthed, isAuthed, skipMismatchCheck]),
)

let SearchBarContent: React.ReactNode
let ListEmptyContent: React.ReactNode

SearchBarContent = (
<SearchBar
{...testProps(LL.common.chatSearch())}
placeholder={LL.common.chatSearch()}
value={searchText}
onChangeText={updateSearchResults}
platform="default"
round
showLoading={refreshing && !!searchText}
containerStyle={styles.searchBarContainer}
inputContainerStyle={styles.searchBarInputContainerStyle}
inputStyle={styles.searchBarText}
rightIconContainerStyle={styles.searchBarRightIconStyle}
searchIcon={<Icon name="search" size={24} color={styles.icon.color} />}
clearIcon={
<Icon name="close" size={24} onPress={reset} color={styles.icon.color} />
}
/>
<>
<UserSearchBar setSearchedUsers={setSearchedUsers} />
</>
)

if (!initialized) {
Expand Down Expand Up @@ -232,63 +141,84 @@ export const NIP17Chat: React.FC = () => {
return (
<Screen style={{ ...styles.header, flex: 1 }}>
{privateKey && !showImportModal ? (
<View style={{ flex: 1 }}>
{SearchBarContent}
<Tab.Navigator
screenOptions={({ route }) => ({
// tabBarLabelStyle: { fontSize: 18, fontWeight: "600" },
// tabBarIndicatorStyle: { backgroundColor: "#60aa55" },
tabBarIndicatorStyle: { backgroundColor: "#60aa55" },
tabBarIcon: ({ color }) => {
let iconName: string
if (route.name === "Chats") {
iconName = "chatbubble-ellipses-outline" // Chat icon
} else if (route.name === "Contacts") {
iconName = "people-outline" // Contacts icon
} else {
iconName = ""
}
return <Icon name={iconName} size={24} color={color} />
},
tabBarShowLabel: false, // Hide text labels
})}
>
<Tab.Screen name="Chats">
{() => (
<View style={{ flex: 1, ...styles.header }}>
{SearchBarContent}

{searchText ? (
<FlatList
contentContainerStyle={styles.listContainer}
data={searchedUsers}
ListEmptyComponent={ListEmptyContent}
renderItem={({ item }) => (
<SearchListItem item={item} userPrivateKey={privateKey!} />
)}
keyExtractor={(item) => item.id}
/>
) : (
<View style={{ flex: 1 }}>
<Text
style={{
fontSize: 24,
marginTop: 20,
marginLeft: 20,
color: colors.primary3,
}}
>
Chats
</Text>
<Text
style={{
fontSize: 16,
margin: 10,
marginLeft: 20,
color: colors.primary3,
}}
>
signed in as:{" "}
<Text style={{ color: colors.primary, fontWeight: "bold" }}>
{userData?.username || nip19.npubEncode(getPublicKey(privateKey))}
</Text>
</Text>
<FlatList
contentContainerStyle={styles.listContainer}
data={groupIds}
ListEmptyComponent={ListEmptyContent}
scrollEnabled={true}
renderItem={({ item }) => {
return (
<HistoryListItem
item={item}
userPrivateKey={privateKey!}
groups={groups}
{searchedUsers.length !== 0 ? (
<FlatList
contentContainerStyle={styles.listContainer}
data={searchedUsers}
ListEmptyComponent={ListEmptyContent}
renderItem={({ item }) => (
<SearchListItem item={item} userPrivateKey={privateKey!} />
)}
keyExtractor={(item) => item.id}
/>
) : (
<View style={{ flex: 1 }}>
<Text
style={{
fontSize: 16,
margin: 10,
marginLeft: 20,
color: colors.primary3,
}}
>
signed in as:{" "}
<Text style={{ color: colors.primary, fontWeight: "bold" }}>
{userData?.username || nip19.npubEncode(getPublicKey(privateKey))}
</Text>
</Text>
<FlatList
contentContainerStyle={styles.listContainer}
data={groupIds}
ListEmptyComponent={ListEmptyContent}
scrollEnabled={true}
renderItem={({ item }) => {
return (
<HistoryListItem
item={item}
userPrivateKey={privateKey!}
groups={groups}
/>
)
}}
keyExtractor={(item) => item}
/>
)
}}
keyExtractor={(item) => item}
/>
</View>
)}
</View>
</View>
)}
</View>
)}
</Tab.Screen>
<Tab.Screen name="Contacts">
{() => (
<View style={{ ...styles.header, height: "100%" }}>
<Contacts userPrivateKey={bytesToHex(privateKey)} />
</View>
)}
</Tab.Screen>
</Tab.Navigator>
) : (
<Text>Loading your nostr keys...</Text>
)}
Expand Down
Loading