Commit 3c541e56 authored by Malsha Rathnasiri's avatar Malsha Rathnasiri

fix api issues

parent 06fd6461
......@@ -50,8 +50,7 @@ import { Platform } from 'react-native'
export const isLoggedIn = async () => {
const token = await AsyncStorage.getItem('access_token')
console.log({ token })
console.log({ token, has: !!token })
return !!token
}
......@@ -75,19 +74,13 @@ export const login = async (username, password) => {
axios.defaults.headers.common.Authorization = `Token ${access}`;
if (Platform.OS = 'web') {
await AsyncStorage.setItem('user_id', user.id)
await AsyncStorage.setItem('username', user.username)
await AsyncStorage.setItem('user_email', user.email)
await AsyncStorage.setItem('access_token', access)
await AsyncStorage.setItem('refresh_token', refresh)
} else {
await AsyncStorage.setItem('user_id', user.id)
await AsyncStorage.setItem('username', user.username)
await AsyncStorage.setItem('user_email', user.email)
await AsyncStorage.setitem('access_token', access)
await AsyncStorage.setItem('refresh_token', refresh)
}
await AsyncStorage.setItem('user_id', String(user.id))
await AsyncStorage.setItem('username', user.username)
await AsyncStorage.setItem('user_email', user.email)
await AsyncStorage.setItem('access_token', access)
await AsyncStorage.setItem('refresh_token', refresh)
console.log("login successful")
......
......@@ -11,10 +11,9 @@ const getHeaders = async () => {
return new Headers({ authorization: `Bearer ${token}`, 'Content-Type': 'application/json' })
}
export const create = async (resource, values) => {
const headers = await getHeaders()
console.log({headers})
try {
return fetch(`${BACKEND_URL}/${resource}/`, { method: 'POST', body: JSON.stringify(values), headers })
}
......
// export const BACKEND_URL = "http://192.168.8.103:8000"
export const BACKEND_ADDRESS = "127.0.0.1:8000"
export const BACKEND_URL = `http://${BACKEND_ADDRESS}`
\ No newline at end of file
export const BACKEND_ADDRESS = "dcf1-2402-d000-a500-101a-cd9c-120b-91b8-7774.in.ngrok.io"
export const BACKEND_URL = `http://${BACKEND_ADDRESS}`
import { Ionicons } from "@expo/vector-icons";
import React, { useState } from "react";
import { View } from "react-native";
import { styles } from "../util/styles";
import { CONVO_DEFAULT_ICON_COLOR, CONVO_STOP_ICON_COLOR, styles } from "../util/styles";
import * as Speech from 'expo-speech';
......@@ -41,12 +41,12 @@ export const PlayMessage = ({ message }) => {
if (!isPlaying) {
return (
<Ionicons name="play" size={15} style={styles.chatIcon} onPress={onPlayPress} />
<Ionicons name="play" size={15} style={styles.chatIcon} onPress={onPlayPress} color={CONVO_DEFAULT_ICON_COLOR} />
)
}
else {
return (
<Ionicons name="stop" size={15} style={styles.chatIcon} onPress={onStopPress} />
<Ionicons name="stop" size={15} style={styles.chatIcon} onPress={onStopPress} color={CONVO_STOP_ICON_COLOR} />
)
}
......
......@@ -26,6 +26,7 @@ import { ERROR_TOAST_PROPS } from '../util/util';
import LinkingConfiguration from './LinkingConfiguration';
import Small_logo from '../assets/images/Logo_small.jpeg'
import { PRIMARY_COLOR } from '../util/styles';
export default function Navigation({ colorScheme }) {
return (
......@@ -45,14 +46,22 @@ const Stack = createNativeStackNavigator();
function RootNavigator() {
const [isAuthenticated, setIsAutheticated] = React.useState(false)
isLoggedIn().then((res) => setIsAutheticated(true))
// console.log({ isLogged })
React.useEffect(() => {
isLoggedIn().then((res) => { setIsAutheticated(res), console.log({ setIs: res }) })
}, [])
const onLogin = async (username, password) => {
await login(username, password).then(() => setIsAutheticated(true)).catch(e => {
console.log(e)
Toast.show({ title: 'Error logging in! Try again', ...ERROR_TOAST_PROPS })
})
// setTimeout(() => setIsAutheticated(true), 2000)
}
const onLogout = () => {
......@@ -88,10 +97,10 @@ function BottomTabNavigator({ onLogout }) {
<BottomTab.Navigator
initialRouteName="TabOne"
screenOptions={{
tabBarActiveBackgroundColor: 'lightgray',
tabBarActiveTintColor: 'blue' //Colors[colorScheme].tint,
// tabBarActiveBackgroundColor: 'lightgray',
tabBarActiveTintColor: PRIMARY_COLOR //Colors[colorScheme].tint,
}}>
<BottomTab.Screen
<BottomTab.Screen
name="TabTwo"
component={TabTwoScreen}
options={{
......@@ -106,7 +115,7 @@ function BottomTabNavigator({ onLogout }) {
title: 'Chat',
headerTitleAlign: 'center',
tabBarIcon: ({ color }) => <TabBarIcon name="comments" color={color} />,
headerLeft: () => (<Image source={Small_logo} style={{height: 40, width: 70, marginLeft: 20}}/>),
headerLeft: () => (<Image source={Small_logo} style={{ height: 40, width: 70, marginLeft: 20 }} />),
headerRight: () => (
<Pressable
// onPress={() => navigation.navigate('Modal')}
......@@ -124,7 +133,7 @@ function BottomTabNavigator({ onLogout }) {
),
})}
/>
</BottomTab.Navigator>
);
}
......
......@@ -9,10 +9,12 @@ import { RootTabScreenProps } from '../types';
import { create, getList } from '../api/api';
import { BACKEND_ADDRESS } from '../api/constants';
import Ionicons from '@expo/vector-icons/Ionicons';
import { styles } from '../util/styles';
import { CONVO_DEFAULT_ICON_COLOR, styles } from '../util/styles';
import { StatusBar } from 'expo-status-bar';
import Slider from '@react-native-community/slider';
import { PlayMessage } from '../components/PlayMessage';
import { Toast } from 'native-base';
import { ERROR_TOAST_PROPS } from '../util/util';
export default function ChatScreen({ navigation }) {
......@@ -57,12 +59,11 @@ export default function ChatScreen({ navigation }) {
console.log({ chats })
}
// const ws = new WebSocket(`ws://${BACKEND_ADDRESS}/chatSocket/`)
useEffect(() => {
loadChats()
// startWebsocket()
loadSampleChats()
// loadSampleChats()
setLoading(false)
}, [])
......@@ -71,7 +72,6 @@ export default function ChatScreen({ navigation }) {
// // on connecting, do nothing but log it to the console
// console.log('connected')
// }
// ws.onmessage = evt => {
// // listen to data sent from the websocket server
// const message = JSON.parse(evt.data)
......@@ -87,22 +87,22 @@ export default function ChatScreen({ navigation }) {
// }
const loadChats = async () => {
// await getList('chats').then(res => {
// return res.json()
// }).then(res => {
// // console.log(res)
// const chats = res.results
// const sections = [...new Set(chats.map(chat => new Date(chat.timestamp).setHours(0, 0, 0, 0)))];
// const sectionChats = sections.map(section => ({ title: section, data: chats.filter(chat => new Date(chat.timestamp).setHours(0, 0, 0, 0) == section) }))
// setChats(sectionChats)
// })
await getList('chats').then(res => {
return res.json()
}).then(res => {
// console.log(res)
const chats = res.results
const sections = [...new Set(chats.map(chat => new Date(chat.timestamp).setHours(0, 0, 0, 0)))];
const sectionChats = sections.map(section => ({ title: section, data: chats.filter(chat => new Date(chat.timestamp).setHours(0, 0, 0, 0) == section) }))
setChats(sectionChats)
})
setLoading(false)
}
const onSendPress = () => {
try {
create('chats', { message: input, from_user: chatDetails.from_user, to_user: chatDetails.to_user, conversation: chatDetails.conversation_id }).then(response => {
// console.log(response)
})
......@@ -110,6 +110,10 @@ export default function ChatScreen({ navigation }) {
setInput('')
loadChats()
}
catch(e){
Toast.show({title: 'Error sending message. try again!', ...ERROR_TOAST_PROPS})
}
}
return (
<View style={styles.container}>
......@@ -126,7 +130,7 @@ export default function ChatScreen({ navigation }) {
{loading ? <ActivityIndicator /> :
<SectionList
refreshing={loading}
// onRefresh={() => loadChats()}
onRefresh={() => loadChats()}
inverted={true}
sections={chats}
keyExtractor={(item, index) => item + index}
......@@ -140,7 +144,7 @@ export default function ChatScreen({ navigation }) {
key={item.timestamp}>{item.message}</Text>
<View style={{ flex: 1, flexDirection: chatDetails.from_user == item.from_user ? 'row-reverse' : 'row', textAlign: chatDetails.from_user == item.from_user ? 'right' : 'left' }}>
<Text style={{ textAlign: chatDetails.from_user == item.from_user ? 'right' : 'left', color: 'gray', fontSize: 11 }}>{new Date(item.timestamp).toLocaleTimeString()}</Text>
{item.is_detected && <Ionicons name="mic" size={15} style={{}} />}
{item.is_detected && <Ionicons name="mic" size={15} color={CONVO_DEFAULT_ICON_COLOR}/>}
{/* {chatDetails.to_user == item.from_user && item.id != playinId && <Ionicons name="play" size={15} style={styles.chatIcon} />}
{chatDetails.to_user == item.from_user && item.id == playinId && <Ionicons name="pause" size={15} style={styles.chatIcon} />} */}
{chatDetails.to_user == item.from_user && <PlayMessage message={item.message} />}
......
import React, { useState } from 'react'
import { StyleSheet, TextInput, Button, Image, Dimensions, View, Text } from 'react-native';
import { StyleSheet, TextInput, Button, Image, Dimensions, View, Text, ActivityIndicator } from 'react-native';
import EditScreenInfo from '../components/EditScreenInfo';
// import { Text, View } from '../components/Themed';
import { TouchableOpacity } from 'react-native';
......@@ -16,8 +16,22 @@ const LoginForm = ({ onLogin, navigation }) => {
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const [loading, setLoading] = useState(false)
const onSubmit = () => {
console.log({ username, password })
setLoading(true)
if (!username || !password) {
Toast.show({ title: 'Please fill in all the fields!', ...ERROR_TOAST_PROPS })
} else {
onLogin(username, password)
}
setLoading(false)
}
return (
<>
<View>
<TextInput style={styles.input}
defaultValue={username}
onChangeText={(e) => {
......@@ -37,34 +51,30 @@ const LoginForm = ({ onLogin, navigation }) => {
defaultValue={password}
onChangeText={(e) => setPassword(e)}
returnKeyType="go"
autoCapitalize="none"
ref={(input) => passwordInput = input}
placeholder='Password'
onSubmitEditing={onSubmit}
// placeholderTextColor='rgba(225,225,225,0.7)'
secureTextEntry />
<TouchableOpacity style={styles.buttonContainer}
// onPress={onButtonPress}
// disabled={!username || !password}
onPress={() => {
console.log({ username, password })
if (!username || !password) {
Toast.show({ title: 'Please fill in all the fields!', ...ERROR_TOAST_PROPS })
} else {
onLogin(username, password)
}
}}
>
<Text style={styles.buttonText}>LOGIN</Text>
onPress={onSubmit}
disabled={loading}
>{loading ? <ActivityIndicator /> : <Text style={styles.buttonText}>LOGIN</Text> }
</TouchableOpacity>
</>
</View>
// define your styles
)
}
export const LoginScreen = ({ onLogin, navigation }) => {
return (
<View style={styles.container}>
<View style={styles.loginScreenContainer}>
<View style={{ alignContent: 'center', justifyContent: 'center' }}>
<Image source={TTS_logo} style={{ height: screenWidth - 30, width: screenWidth - 30, margin: 'auto' }} />
</View>
......
......@@ -2,11 +2,17 @@ import { StyleSheet, Dimensions } from "react-native"
export const screenWidth = Dimensions.get('window').width
export const PRIMARY_COLOR = '#2f95dc'
export const COLOR1 = '#fff'//'#2c3e50'
export const CONVO_DEFAULT_ICON_COLOR = '#000'
export const CONVO_STOP_ICON_COLOR = '#f00'
export const styles = StyleSheet.create({
// container: {
// flex: 1,
// backgroundColor: '#2c3e50',
// },
container: {
flex: 1,
backgroundColor: COLOR1,
},
loginContainer: {
alignItems: 'center',
flexGrow: 1,
......@@ -17,7 +23,7 @@ export const styles = StyleSheet.create({
width: 300,
height: 100
},
container: {
loginScreenContainer: {
padding: 20,
backgroundColor: 'white'
},
......@@ -42,11 +48,11 @@ export const styles = StyleSheet.create({
chatIcon: {
paddingHorizontal: 4
},
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
// container: {
// flex: 1,
// alignItems: 'center',
// justifyContent: 'center',
// },
title: {
fontSize: 20,
fontWeight: 'bold',
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment