Commit 888e41c8 authored by Malsha Rathnasiri's avatar Malsha Rathnasiri

major changes

parent bcf49e15
// export const BACKEND_URL = "http://192.168.8.103:8000" // export const BACKEND_URL = "http://192.168.8.103:8000"
import { Platform } from 'react-native' import { Platform } from 'react-native'
export const BACKEND_ADDRESS = Platform.OS == 'web' ? "http://127.0.0.1:8000" : "https://4c61-2401-dd00-10-20-7542-a875-30e7-8931.ap.ngrok.io" export const BACKEND_ADDRESS = Platform.OS == 'web' ? "http://127.0.0.1:8000" : "https://21a1-112-134-220-172.ap.ngrok.io"
export const BACKEND_URL = `${BACKEND_ADDRESS}` export const BACKEND_URL = `${BACKEND_ADDRESS}`
{ {
"expo": { "expo": {
"name": "MobileApp", "name": "DriverApp",
"slug": "MobileApp", "slug": "DriverApp",
"version": "1.0.0", "version": "1.0.0",
"orientation": "portrait", "orientation": "portrait",
"icon": "./assets/images/icon.png", "icon": "./assets/images/icon.png",
......
...@@ -14,43 +14,43 @@ ...@@ -14,43 +14,43 @@
"preset": "jest-expo" "preset": "jest-expo"
}, },
"dependencies": { "dependencies": {
"@expo/vector-icons": "^12.0.0", "@expo/vector-icons": "^13.0.0",
"@react-native-async-storage/async-storage": "~1.15.0", "@react-native-async-storage/async-storage": "~1.17.3",
"@react-native-community/slider": "4.1.12", "@react-native-community/slider": "4.2.1",
"@react-navigation/bottom-tabs": "^6.0.5", "@react-navigation/bottom-tabs": "^6.0.5",
"@react-navigation/native": "^6.0.2", "@react-navigation/native": "^6.0.2",
"@react-navigation/native-stack": "^6.1.0", "@react-navigation/native-stack": "^6.1.0",
"axios": "^0.27.2", "axios": "^0.27.2",
"expo": "~44.0.0", "expo": "^45.0.0",
"expo-asset": "~8.4.4", "expo-asset": "~8.5.0",
"expo-av": "~10.2.0", "expo-av": "~11.2.3",
"expo-constants": "~13.0.0", "expo-constants": "~13.1.1",
"expo-file-system": "~13.1.4", "expo-file-system": "~14.0.0",
"expo-font": "~10.0.4", "expo-font": "~10.1.0",
"expo-linking": "~3.0.0", "expo-linking": "~3.1.0",
"expo-media-library": "~14.0.0", "expo-media-library": "~14.1.0",
"expo-speech": "~10.1.0", "expo-speech": "~10.2.0",
"expo-splash-screen": "~0.14.0", "expo-splash-screen": "~0.15.1",
"expo-status-bar": "~1.2.0", "expo-status-bar": "~1.3.0",
"expo-web-browser": "~10.1.0", "expo-web-browser": "~10.2.1",
"jwt-decode": "^3.1.2", "jwt-decode": "^3.1.2",
"native-base": "^3.4.11", "native-base": "^3.4.11",
"react": "17.0.1", "react": "17.0.2",
"react-dom": "17.0.1", "react-dom": "17.0.2",
"react-native": "0.64.3", "react-native": "0.68.2",
"react-native-multi-selectbox": "^1.5.0", "react-native-multi-selectbox": "^1.5.0",
"react-native-safe-area-context": "3.3.2", "react-native-safe-area-context": "4.2.4",
"react-native-screens": "~3.10.1", "react-native-screens": "~3.11.1",
"react-native-svg": "12.1.1", "react-native-svg": "12.3.0",
"react-native-web": "0.17.1", "react-native-web": "0.17.7",
"styled-system": "^5.1.5" "styled-system": "^5.1.5"
}, },
"devDependencies": { "devDependencies": {
"@babel/core": "^7.12.9", "@babel/core": "^7.12.9",
"@types/react": "~17.0.21", "@types/react": "~17.0.21",
"@types/react-native": "~0.64.12", "@types/react-native": "~0.67.6",
"jest": "^26.6.3", "jest": "^26.6.3",
"jest-expo": "~44.0.1", "jest-expo": "^45.0.0",
"react-test-renderer": "17.0.1", "react-test-renderer": "17.0.1",
"typescript": "~4.3.5" "typescript": "~4.3.5"
}, },
......
import React, { useEffect, useState } from 'react' import React, { useEffect, useState } from "react";
import { FlatList, StyleSheet, TextInput, SectionList, Button, ActivityIndicator, View, Text, SafeAreaView } from 'react-native'; import {
import { AudioRecorder } from '../components/AudioRecorder'; FlatList,
import _ from 'lodash' StyleSheet,
TextInput,
SectionList,
import EditScreenInfo from '../components/EditScreenInfo'; Button,
ActivityIndicator,
View,
Text,
SafeAreaView,
TouchableOpacity,
} from "react-native";
import { AudioRecorder } from "../components/AudioRecorder";
import _ from "lodash";
import EditScreenInfo from "../components/EditScreenInfo";
// import { Text, View } from '../components/Themed'; // import { Text, View } from '../components/Themed';
import { RootTabScreenProps } from '../types'; import { RootTabScreenProps } from "../types";
import { addChats, create, getList, getOne } from '../api/api'; import { addChats, create, getList, getOne } 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 { CONVO_DEFAULT_ICON_COLOR, 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, Input } from 'native-base'; import { Toast, Input, PresenceTransition } from "native-base";
import { ERROR_TOAST_PROPS } from '../util/util'; import { ERROR_TOAST_PROPS } from "../util/util";
import AsyncStorage from '@react-native-async-storage/async-storage'; import AsyncStorage from "@react-native-async-storage/async-storage";
export default function ChatScreen({ navigation }) { export default function ChatScreen({ navigation }) {
const currentTime = new Date();
const currentTime = new Date()
const defaultChatData = [
const defaultChatData = [{ id: 1, from_user: 2, to_user: 1, message: 'How many passengers?', timestamp: currentTime.setMinutes(currentTime.getMinutes() - 1).valueOf() }, {
{ id: 2, from_user: 1, to_user: 2, message: 'Three', timestamp: currentTime.setMinutes(currentTime.getMinutes() - 2).valueOf(), is_detected: true }, id: 1,
{ id: 3, from_user: 2, to_user: 1, message: 'Should i turn left or right here?', timestamp: currentTime.setMinutes(currentTime.getMinutes() - 3).valueOf(), is_detected: false }, from_user: 2,
{ id: 4, from_user: 1, to_user: 2, message: 'Left', timestamp: currentTime.setMinutes(currentTime.getMinutes() - 4).valueOf(), is_detected: true }, to_user: 1,
{ id: 5, from_user: 1, to_user: 2, message: 'Please hurry', timestamp: currentTime.setMinutes(currentTime.getMinutes() - 5).valueOf() }, message: "How many passengers?",
{ id: 6, from_user: 2, to_user: 1, message: 'Ok', timestamp: currentTime.setMinutes(currentTime.getMinutes() - 6).valueOf() }, timestamp: currentTime.setMinutes(currentTime.getMinutes() - 1).valueOf(),
},
{
id: 2,
from_user: 1,
to_user: 2,
message: "Three",
timestamp: currentTime.setMinutes(currentTime.getMinutes() - 2).valueOf(),
is_detected: true,
},
{
id: 3,
from_user: 2,
to_user: 1,
message: "Should i turn left or right here?",
timestamp: currentTime.setMinutes(currentTime.getMinutes() - 3).valueOf(),
is_detected: false,
},
{
id: 4,
from_user: 1,
to_user: 2,
message: "Left",
timestamp: currentTime.setMinutes(currentTime.getMinutes() - 4).valueOf(),
is_detected: true,
},
{
id: 5,
from_user: 1,
to_user: 2,
message: "Please hurry",
timestamp: currentTime.setMinutes(currentTime.getMinutes() - 5).valueOf(),
},
{
id: 6,
from_user: 2,
to_user: 1,
message: "Ok",
timestamp: currentTime.setMinutes(currentTime.getMinutes() - 6).valueOf(),
},
// { from_user: 1, to_user: 2, message: 'msg1', timestamp: currentTime.setDate(currentTime.getDate() - 1).valueOf() }, // { from_user: 1, to_user: 2, message: 'msg1', timestamp: currentTime.setDate(currentTime.getDate() - 1).valueOf() },
// { from_user: 1, to_user: 2, message: 'msg2', timestamp: currentTime.setDate(currentTime.getDate() - 2).valueOf() }, // { from_user: 1, to_user: 2, message: 'msg2', timestamp: currentTime.setDate(currentTime.getDate() - 2).valueOf() },
// { from_user: 2, to_user: 1, message: 'msg3', timestamp: currentTime.setDate(currentTime.getDate() - 3).valueOf() }, // { from_user: 2, to_user: 1, message: 'msg3', timestamp: currentTime.setDate(currentTime.getDate() - 3).valueOf() },
// { from_user: 1, to_user: 2, message: 'msg4', timestamp: currentTime.setDate(currentTime.getDate() - 4).valueOf() }, // { from_user: 1, to_user: 2, message: 'msg4', timestamp: currentTime.setDate(currentTime.getDate() - 4).valueOf() },
// { from_user: 2, to_user: 1, message: 'msg5', timestamp: currentTime.setDate(currentTime.getDate() - 5).valueOf() }, // { from_user: 2, to_user: 1, message: 'msg5', timestamp: currentTime.setDate(currentTime.getDate() - 5).valueOf() },
] ];
const [detectedText, setDetectedText] = useState("") const [detectedText, setDetectedText] = useState("");
const [playinId, setPlayingId] = useState(3) const [playinId, setPlayingId] = useState();
const [chatDetails, setChatDetails] = useState() const [chatDetails, setChatDetails] = useState(null);
const [chats, setChats] = useState([]) const [conversations, setConversations] = useState([]);
const [input, setInput] = useState('test') const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true) const [chats, setChats] = useState([]);
const [input, setInput] = useState("test");
const [loading, setLoading] = useState(true);
const loadSampleChats = () => { const loadSampleChats = () => {
const chats_ = defaultChatData//res.results const chats_ = defaultChatData; //res.results
const sections = [...new Set(chats_.map(chat => new Date(chat.timestamp).setHours(0, 0, 0, 0)))]; const sections = [
const sectionChats = sections.map(section => { ...new Set(
console.log({ section }) chats_.map((chat) => new Date(chat.timestamp).setHours(0, 0, 0, 0))
return ({ ),
title: section, data: chats_.filter(chat => { ];
console.log({ chat }) const sectionChats = sections.map((section) => {
return (new Date(chat.timestamp).setHours(0, 0, 0, 0).valueOf() == section) console.log({ section });
}).sort((a, b) => { return (a.timestamp - b.timestamp) }) return {
}) title: section,
data: chats_
.filter((chat) => {
console.log({ chat });
return (
new Date(chat.timestamp).setHours(0, 0, 0, 0).valueOf() == section
);
}) })
console.log({ chats_, sections, sectionChats }) .sort((a, b) => {
setChats(sectionChats) return a.timestamp - b.timestamp;
console.log({ chats }) }),
} };
});
console.log({ chats_, sections, sectionChats });
setChats(sectionChats);
useEffect(() => { if (chatDetails) { loadChats(); setLoading(false) } }, [chatDetails]) console.log({ chats });
};
useEffect(() => {
if (chatDetails) {
loadChats();
// setLoading(false);
}
}, [chatDetails]);
// const ws = new WebSocket(`ws://${BACKEND_ADDRESS}/chatSocket/`) // const ws = new WebSocket(`ws://${BACKEND_ADDRESS}/chatSocket/`)
useEffect(() => { useEffect(() => {
loadChatDetails() loadChatDetails();
// startWebsocket() // startWebsocket()
// loadSampleChats() // loadSampleChats()
}, []) }, []);
// const startWebsocket = () => { // const startWebsocket = () => {
// ws.onopen = () => { // ws.onopen = () => {
...@@ -94,55 +158,156 @@ export default function ChatScreen({ navigation }) { ...@@ -94,55 +158,156 @@ export default function ChatScreen({ navigation }) {
// } // }
useEffect(() => {
const interval = setInterval(() => {
loadChats();
}, 2000);
return () => {
clearInterval(interval);
};
}, []);
const loadChatDetails = async () => { const loadChatDetails = async () => {
await getOne('conversations', 1).then(res => { await getList("users")
return res.json() .then((res) => res.json())
}).then(res => { .then((res) => {
console.log(res) console.log({ users: res });
AsyncStorage.getItem('user_id').then((user_id) => { setUsers(res.results);
console.log('chat details', user_id) });
await getList("conversations")
//change from user and to user depending on the current user .then((res) => {
return res.json();
})
.then((res) => {
console.log({ res });
AsyncStorage.getItem("user_id").then((user_id) => {
console.log("chat details", user_id);
const converted = res.results.map((res) => {
if (res.from_user == user_id) { if (res.from_user == user_id) {
setChatDetails(res) return res;
} } else {
else { const n_res = {
const n_res = { ...res, from_user: res.to_user, to_user: res.from_user } ...res,
setChatDetails(n_res) from_user: res.to_user,
to_user: res.from_user,
};
return n_res;
} }
});
setConversations(converted);
// //change from user and to user depending on the current user
// if (res[0].from_user == user_id) {
// setChatDetails(res)
// }
// else {
// const n_res = { ...res[0], from_user: res[0].to_user, to_user: res[0].from_user }
// setChatDetails(n_res)
// }
});
});
};
const loadChats = () => {
// setLoading(true);
getList("chats", { conversation: chatDetails?.id })
.then((res) => {
return res.json();
}) })
.then((res) => {
console.log("load chats", res.results);
const chats = res.results.slice(-20) || [];
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);
}) })
} .then(() => {
setLoading(false);
const loadChats = async () => {
await getList('chats').then(res => {
return res.json()
}).then(res => {
console.log("load chats")
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)
}) })
.catch((e) => {
setLoading(false) console.log(e);
} });
};
const onSendPress = () => { const onSendPress = () => {
try { try {
addChats({message: input, from_user: chatDetails.from_user, to_user: chatDetails.to_user, conversation: chatDetails.id }).then(response => { addChats({
message: input,
from_user: chatDetails.from_user,
to_user: chatDetails.to_user,
conversation: chatDetails?.id,
}).then((response) => {
// console.log(response) // console.log(response)
}) });
setLoading(true) setLoading(true);
setInput('') setInput("");
loadChats() loadChats();
} catch (e) {
Toast.show({
title: "Error sending message. try again!",
...ERROR_TOAST_PROPS,
});
} }
catch (e) { };
Toast.show({ title: 'Error sending message. try again!', ...ERROR_TOAST_PROPS }) if (!chatDetails && users) {
return (
<View>
<PresenceTransition
initial={{
opacity: 0,
}}
animate={{
opacity: 1,
transition: {
duration: 500,
},
}}
visible={!chatDetails}
>
<Text
style={{
backgroundColor: "grey",
padding: 20,
borderRadius: 10,
fontSize: 20,
fontWeight: "bold",
}}
>
Passengers
</Text>
<FlatList
data={conversations}
renderItem={({ item }) => {
return (
<TouchableOpacity
onPress={() => {
setChatDetails(item);
setChats([]);
}}
>
<Text style={{ padding: 20 }}>
{
users?.find((user) => {
// console.log({ user }, user.id == item.to_user);
return user?.id == item?.to_user;
})?.username
} }
</Text>
</TouchableOpacity>
);
}}
/>
</PresenceTransition>
</View>
);
} }
return ( return (
...@@ -153,112 +318,214 @@ export default function ChatScreen({ navigation }) { ...@@ -153,112 +318,214 @@ export default function ChatScreen({ navigation }) {
<EditScreenInfo path="/screens/TabOneScreen.tsx" /> */} <EditScreenInfo path="/screens/TabOneScreen.tsx" /> */}
<View style={{ flex: 1, width: '100%' }}> <PresenceTransition
<View style={{ display: 'flex', flex: 0.9, justifyContent: 'space-between' }}> initial={{
opacity: 0,
}}
animate={{
opacity: 1,
transition: {
duration: 100,
},
}}
visible={!!chatDetails}
style={{ flex: 1, width: "100%" }}
>
<View
style={{
display: "flex",
flex: 0.9,
justifyContent: "space-between",
// backgroundColor: "red",
}}
>
<TouchableOpacity
style={{
backgroundColor: "gray",
padding: 5,
margin: 5,
borderRadius: 5,
flexDirection: "row",
justifyContent: "space-between",
}}
onPress={() => {
setChatDetails();
}}
>
<View
style={{
flex: 0.25,
alignContent: "center",
justifyContent: "center",
}}
>
<Ionicons name="chevron-back-outline" size={20} />
</View>
{/* <Text>Back to chats</Text> */}
<View style={{ justifyContent: "center" }}>
<Text style={{ fontSize: 20 }}>
{
users.find((user) => user.id == chatDetails?.to_user)
?.username
}
</Text>
</View>
<View style={{ flex: 0.25 }}></View>
</TouchableOpacity>
<StatusBar /> <StatusBar />
{loading ? <ActivityIndicator /> : {loading ? (
<ActivityIndicator />
) : (
<SectionList <SectionList
initialNumToRender={10}
refreshing={loading} refreshing={loading}
onRefresh={() => { onRefresh={() => {
// loadChatDetails() //remove // loadChatDetails() //remove
loadChats() loadChats();
}} }}
sections={chats} sections={chats.slice(-10)}
keyExtractor={(item, index) => item + index} keyExtractor={(item, index) => item + index}
renderItem={({ item }) => { renderItem={({ item }) => {
// console.log({ item }) // console.log({ item })
const timeString = new Date(item.timestamp).toLocaleTimeString() const timeString = new Date(
const time = timeString.slice(-11, -6) + " " + timeString.slice(-2) item.timestamp
).toLocaleTimeString();
const time = timeString.slice(0, 5);
return ( return (
<View style={{ margin: 5, padding: 5 }}><Text <View style={{ margin: 5, padding: 5 }}>
style={[{ textAlign: chatDetails.from_user == item.from_user ? 'right' : 'left', backgroundColor: chatDetails.from_user == item.from_user ? 'lightgray' : '#FFDE03', borderRadius: 5, padding: 5 }, <Text
chatDetails.from_user == item.from_user ? { marginLeft: 'auto' } : { marginRight: 'auto' } style={[
{
textAlign:
chatDetails.from_user == item.from_user
? "right"
: "left",
backgroundColor:
chatDetails.from_user == item.from_user
? "lightgray"
: "#FFDE03",
borderRadius: 5,
padding: 5,
},
chatDetails.from_user == item.from_user
? { marginLeft: "auto" }
: { marginRight: "auto" },
]} ]}
key={item.timestamp}>{item.message}</Text> key={item.timestamp}
<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 }}>{time}</Text> {item.message}
{item.is_detected && <Ionicons name="mic" size={15} color={CONVO_DEFAULT_ICON_COLOR} />} </Text>
{/* {chatDetails.to_user == item.from_user && item.id != playinId && <Ionicons name="play" size={15} style={styles.chatIcon} />} <View
{chatDetails.to_user == item.from_user && item.id == playinId && <Ionicons name="pause" size={15} style={styles.chatIcon} />} */} style={{
{chatDetails.to_user == item.from_user && <PlayMessage message={item.message} />} flex: 1,
</View> flexDirection:
{/* {item.id == playinId ? chatDetails.from_user == item.from_user
<Slider ? "row-reverse"
style={{ width: 200, height: 40, FborderRadius: 5, padding: 0, margin: 0 }} : "row",
minimumValue={0} textAlign:
maximumValue={1} chatDetails.from_user == item.from_user
value={0.67} ? "right"
: "left",
}}
>
<Text
style={{
textAlign:
chatDetails.from_user == item.from_user
? "right"
: "left",
color: "gray",
fontSize: 11,
}}
>
{time}
</Text>
{item.is_detected && (
<Ionicons
name="mic"
size={15}
color={CONVO_DEFAULT_ICON_COLOR}
/>
)}
minimumTrackTintColor="black" {chatDetails.to_user == item.from_user && (
maximumTrackTintColor="grey" <PlayMessage message={item.message} />
/> : null )}
} */}
</View> </View>
) </View>
);
}} }}
invertStickyHeaders invertStickyHeaders
inverted inverted
contentContainerStyle={{ flexDirection: 'column-reverse' }} contentContainerStyle={{ flexDirection: "column-reverse" }}
renderSectionHeader={({ section: { title } }) => { renderSectionHeader={({ section: { title } }) => {
var date = "" var date = "";
if (new Date(title).toLocaleDateString() == new Date().toLocaleDateString()) { if (
date = "Today" new Date(title).toLocaleDateString() ==
new Date().toLocaleDateString()
) {
date = "Today";
} else {
date = new Date(title).toLocaleDateString();
} }
// else if (new Date(title).toLocaleDateString() == new Date().setDate(new Date().getDate() - 1).toLocaleDateString()){ return <Text style={styles.header}>{date}</Text>;
// date = "Yesterday"
// }
else {
date = new Date(title).toLocaleDateString()
}
return (
<Text style={styles.header}>{date}</Text>
)
}} }}
/> />
} )}
{/* <FlatList
inverted={true}
style={{ alignContent: 'flex-end' }}
data={chats}
keyExtractor={(item) => item.currentTime}
renderItem={({ item }) => {
console.log({ item })
return (
<View style={{ margin: 5, padding: 5 }}><Text
style={[{ textAlign: chatDetails.from == item.from ? 'right' : 'left', backgroundColor: 'blue', borderRadius: 5, padding: 5 },
chatDetails.from == item.from ? { marginLeft: 'auto' } : { marginRight: 'auto' }
]}
key={item.time}>{item.message}</Text>
<Text style={{ textAlign: chatDetails.from == item.from ? 'right' : 'left', color: 'gray' }}>{new Date(item.time).toLocaleTimeString().slice(0, 5)}</Text></View>
)
}} /> */}
</View> </View>
<View style={{ flex: 0.075, padding: 0, backgroundColor: 'white' }}> <View style={{ flex: 0.075, padding: 0, backgroundColor: "white" }}>
<View style={{ flexDirection: 'row', display: 'flex', height: '100%' }}> <View
<SafeAreaView style={{ flex: 0.8, height: '100%', flexDirection: 'column-reverse' }}> style={{ flexDirection: "row", display: "flex", height: "100%" }}
>
<SafeAreaView
style={{
flex: 0.8,
height: "100%",
flexDirection: "column-reverse",
}}
>
{/* <TextInput {/* <TextInput
style={{ borderWidth: 2, borderColor: 'gray', color: 'black', marginHorizontal: 5, paddingHorizontal: 10, borderRadius: 5 }} style={{ borderWidth: 2, borderColor: 'gray', color: 'black', marginHorizontal: 5, paddingHorizontal: 10, borderRadius: 5 }}
defaultValue={input} defaultValue={input}
onChange={(e) => setInput(e.target.value)}></TextInput> */} onChange={(e) => setInput(e.target.value)}></TextInput> */}
<Input style={{}} value={input} w="100%" onChangeText={setInput} placeholder="" /> <Input
style={{ height: 30 }}
value={input}
w="100%"
onChangeText={setInput}
placeholder=""
/>
</SafeAreaView> </SafeAreaView>
{input ? {input ? (
<View style={{ flex: 0.2, height: '100%', flexDirection: 'column-reverse' }}> <View
<Button style={{ width: '100%', height: '100%' }} title='Send' onPress={onSendPress} /> style={{
flex: 0.2,
height: "100%",
flexDirection: "column-reverse",
}}
>
<Button
style={{ width: "100%", height: "100%" }}
title="Send"
onPress={onSendPress}
/>
</View> </View>
: ) : (
<View style={{ flex: 0.2, height: '100%', flexDirection: 'column-reverse' }}><AudioRecorder setDetectedText={setInput} /></View> <View
} style={{
flex: 0.2,
height: "100%",
flexDirection: "column-reverse",
}}
>
<AudioRecorder setDetectedText={setInput} />
</View> </View>
)}
</View> </View>
</View> </View>
</PresenceTransition>
</View> </View>
); );
} }
import React, { useState } from 'react' import React, { useState } from "react";
import { StyleSheet, TextInput, Button, Image, Dimensions, View, Text, ActivityIndicator } from 'react-native'; import {
import EditScreenInfo from '../components/EditScreenInfo'; StyleSheet,
TextInput,
Button,
Image,
Dimensions,
View,
Text,
ActivityIndicator,
} from "react-native";
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";
import { ScrollView, Toast } from 'native-base'; import { ScrollView, Toast } from "native-base";
import { ERROR_TOAST_PROPS } from '../util/util'; import { ERROR_TOAST_PROPS } from "../util/util";
import { screenWidth, styles } from '../util/styles'; import { screenWidth, styles } from "../util/styles";
import TTS_logo from '../assets/images/TTS_logo.jpeg' import TTS_logo from "../assets/images/TTS_logo.jpeg";
export const LoginScreen = ({ onLogin, navigation }) => { export const LoginScreen = ({ onLogin, navigation }) => {
return ( return (
<ScrollView style={styles.loginScreenContainer}> <ScrollView 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' }} /> <Text
style={{
padding: 10,
textAlign: "center",
fontWeight: "bold",
fontSize: 30,
}}
>
Driver App
</Text>
<Image
source={TTS_logo}
style={{
height: screenWidth - 30,
width: screenWidth - 30,
margin: "auto",
}}
/>
</View> </View>
<Text style={{ <Text
style={{
padding: 10, padding: 10,
textAlign: 'center', textAlign: "center",
// fontWeight: 'bold', // fontWeight: 'bold',
fontSize: 40 fontSize: 40,
}}>Login</Text> }}
<View style={{ flexDirection: 'row', padding: 10, justifyContent: 'center' }}> >
<Text style={{ textAlign: 'center' }}>Don't have an account? </Text> Login
<Text style={{ fontWeight: 'bold', textAlign: 'center', }} onPress={() => navigation.replace('Signup')}>Sign up</Text> </Text>
<View
style={{ flexDirection: "row", padding: 10, justifyContent: "center" }}
>
<Text style={{ textAlign: "center" }}>Don't have an account? </Text>
<Text
style={{ fontWeight: "bold", textAlign: "center" }}
onPress={() => navigation.replace("Signup")}
>
Sign up
</Text>
</View> </View>
<View style={styles.formContainer}> <View style={styles.formContainer}>
<LoginForm onLogin={onLogin} /> <LoginForm onLogin={onLogin} />
</View> </View>
</ScrollView> </ScrollView>
); );
} };
const LoginForm = ({ onLogin, navigation }) => { const LoginForm = ({ onLogin, navigation }) => {
var passwordInput;
var passwordInput const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [username, setUsername] = useState('') const [loading, setLoading] = useState(false);
const [password, setPassword] = useState('')
const [loading, setLoading] = useState(false)
const onSubmit = () => { const onSubmit = () => {
console.log({ username, password }) console.log({ username, password });
setLoading(true) setLoading(true);
if (!username || !password) { if (!username || !password) {
Toast.show({ title: 'Please fill in all the fields!', ...ERROR_TOAST_PROPS }) Toast.show({
title: "Please fill in all the fields!",
...ERROR_TOAST_PROPS,
});
} else { } else {
onLogin(username, password) onLogin(username, password);
}
setLoading(false)
} }
setLoading(false);
};
return ( return (
<View > <View>
<TextInput style={styles.input} <TextInput
style={styles.input}
defaultValue={username} defaultValue={username}
onChangeText={(e) => { onChangeText={(e) => {
console.log(e); console.log(e);
setUsername(e) setUsername(e);
}} }}
autoCapitalize="none" autoCapitalize="none"
onSubmitEditing={() => passwordInput.focus()} onSubmitEditing={() => passwordInput.focus()}
autoCorrect={false} autoCorrect={false}
keyboardType='email-address' keyboardType="email-address"
returnKeyType="next" returnKeyType="next"
placeholder='Email' placeholder="Email"
// placeholderTextColor='rgba(225,225,225,0.7)' // placeholderTextColor='rgba(225,225,225,0.7)'
/> />
<TextInput style={styles.input} <TextInput
style={styles.input}
defaultValue={password} defaultValue={password}
onChangeText={(e) => setPassword(e)} onChangeText={(e) => setPassword(e)}
returnKeyType="go" returnKeyType="go"
autoCapitalize="none" autoCapitalize="none"
ref={(input) => passwordInput = input} ref={(input) => (passwordInput = input)}
placeholder='Password' placeholder="Password"
onSubmitEditing={onSubmit} 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={onSubmit} onPress={onSubmit}
disabled={loading} disabled={loading}
>{loading ? <ActivityIndicator /> : <Text style={styles.buttonText}>LOGIN</Text>} >
{loading ? (
<ActivityIndicator />
) : (
<Text style={styles.buttonText}>LOGIN</Text>
)}
</TouchableOpacity> </TouchableOpacity>
</View> </View>
// define your styles // define your styles
) );
} };
This source diff could not be displayed because it is too large. You can view the blob instead.
// export const BACKEND_URL = "http://192.168.8.103:8000" // export const BACKEND_URL = "http://192.168.8.103:8000"
import { Platform } from 'react-native' import { Platform } from 'react-native'
export const BACKEND_ADDRESS = Platform.OS == 'web' ? "http://127.0.0.1:8000" : "https://4c61-2401-dd00-10-20-7542-a875-30e7-8931.ap.ngrok.io" export const BACKEND_ADDRESS = Platform.OS == 'web' ? "http://127.0.0.1:8000" : "https://21a1-112-134-220-172.ap.ngrok.io"
export const BACKEND_URL = `${BACKEND_ADDRESS}` export const BACKEND_URL = `${BACKEND_ADDRESS}`
...@@ -94,7 +94,7 @@ export default function ChatScreen({ navigation }) { ...@@ -94,7 +94,7 @@ export default function ChatScreen({ navigation }) {
const [detectedText, setDetectedText] = useState(""); const [detectedText, setDetectedText] = useState("");
const [playinId, setPlayingId] = useState(3); const [playinId, setPlayingId] = useState(3);
const [chatDetails, setChatDetails] = useState(); const [chatDetails, setChatDetails] = useState(null);
const [chats, setChats] = useState([]); const [chats, setChats] = useState([]);
const [input, setInput] = useState("test"); const [input, setInput] = useState("test");
...@@ -172,13 +172,14 @@ export default function ChatScreen({ navigation }) { ...@@ -172,13 +172,14 @@ export default function ChatScreen({ navigation }) {
}, []); }, []);
const loadChatDetails = async () => { const loadChatDetails = async () => {
await getOne("conversations", 1) await AsyncStorage.getItem("user_id").then((user_id) => {
getOne("conversations", 1)
.then((res) => { .then((res) => {
return res.json(); return res.json();
}) })
.then((res) => { .then((res) => {
console.log(res); console.log(res);
AsyncStorage.getItem("user_id").then((user_id) => {
console.log("chat details", user_id); console.log("chat details", user_id);
//change from user and to user depending on the current user //change from user and to user depending on the current user
...@@ -203,9 +204,11 @@ export default function ChatScreen({ navigation }) { ...@@ -203,9 +204,11 @@ export default function ChatScreen({ navigation }) {
from_user: chatDetails.from_user, from_user: chatDetails.from_user,
to_user: chatDetails.to_user, to_user: chatDetails.to_user,
conversation: chatDetails.id, conversation: chatDetails.id,
}).then((response) => { })
.then((response) => {
// console.log(response) // console.log(response)
}).catch(e => { })
.catch((e) => {
// console.log({e}) // console.log({e})
}); });
...@@ -214,11 +217,13 @@ export default function ChatScreen({ navigation }) { ...@@ -214,11 +217,13 @@ export default function ChatScreen({ navigation }) {
from_user: chatDetails.to_user, from_user: chatDetails.to_user,
to_user: chatDetails.from_user, to_user: chatDetails.from_user,
conversation: chatDetails.id, conversation: chatDetails.id,
}).then((response) => { })
.then((response) => {
// console.log(response) // console.log(response)
}).catch(e => {
// console.log({e})
}) })
.catch((e) => {
// console.log({e})
});
setLoading(true); setLoading(true);
setInput(""); setInput("");
...@@ -231,8 +236,8 @@ export default function ChatScreen({ navigation }) { ...@@ -231,8 +236,8 @@ export default function ChatScreen({ navigation }) {
} }
}; };
const loadChats = async () => { const loadChats = () => {
await getList("chats") getList("chats", { conversation: chatDetails?.id })
.then((res) => { .then((res) => {
return res.json(); return res.json();
}) })
...@@ -251,7 +256,7 @@ export default function ChatScreen({ navigation }) { ...@@ -251,7 +256,7 @@ export default function ChatScreen({ navigation }) {
), ),
})); }));
setChats(sectionChats); setChats(sectionChats);
}); }).catch(e => {console.log(e)});
setLoading(false); setLoading(false);
}; };
...@@ -299,7 +304,7 @@ export default function ChatScreen({ navigation }) { ...@@ -299,7 +304,7 @@ export default function ChatScreen({ navigation }) {
<ActivityIndicator /> <ActivityIndicator />
) : ( ) : (
<SectionList <SectionList
style={{ flex: 1 }} // style={{ flex: 1 }}
refreshing={loading} refreshing={loading}
onRefresh={() => { onRefresh={() => {
// loadChatDetails() //remove // loadChatDetails() //remove
......
...@@ -31,7 +31,7 @@ class MyTokenObtainPairSerializer(TokenObtainPairSerializer): ...@@ -31,7 +31,7 @@ class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
class UserSerializer(serializers.HyperlinkedModelSerializer): class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta: class Meta:
model = User model = User
fields = ['url', 'username', 'email', 'groups'] fields = ['username', 'id']
class GroupSerializer(serializers.HyperlinkedModelSerializer): class GroupSerializer(serializers.HyperlinkedModelSerializer):
......
...@@ -74,7 +74,7 @@ class MlModelViewSet(viewsets.ViewSet): ...@@ -74,7 +74,7 @@ class MlModelViewSet(viewsets.ViewSet):
# Custom api to add sample chats # Custom api to add sample chats
@action(detail=False) @action(detail=False)
def addChats(*args, **kwargs): def add_default_chats(*args, **kwargs):
admin = User.objects.get(username='admin') admin = User.objects.get(username='admin')
user2 = User.objects.get(username='user2') user2 = User.objects.get(username='user2')
...@@ -160,9 +160,10 @@ class ChatViewSet(viewsets.ModelViewSet): ...@@ -160,9 +160,10 @@ class ChatViewSet(viewsets.ModelViewSet):
# ovveride defualt list action to get chats of specific user conversation # ovveride defualt list action to get chats of specific user conversation
def list(self, request, pk=None): def list(self, request, pk=None):
conv_id = request.query_params.get("conversation")
if pk == None: if pk == None:
chats = Chat.objects \ chats = Chat.objects \
.filter(conversation_id=1) \ .filter(conversation_id=int(conv_id)) \
.filter(Q(from_user_id=request.user.id) | Q( .filter(Q(from_user_id=request.user.id) | Q(
to_user_id=request.user.id)) to_user_id=request.user.id))
else: else:
......
No preview for this file type
No preview for this file type
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