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

fix api issues

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