Commit 21820ebf authored by Malsha Rathnasiri's avatar Malsha Rathnasiri

WIP chat

parent cf4c555d
// export const BACKEND_URL = "http://192.168.8.103:8000" // export const BACKEND_URL = "http://192.168.8.103:8000"
export const BACKEND_URL = "https://675d-123-231-127-199.in.ngrok.io" export const BACKEND_ADDRESS = "0be4-123-231-126-225.in.ngrok.io"
\ No newline at end of file export const BACKEND_URL = `https:/${BACKEND_ADDRESS}`
\ No newline at end of file
...@@ -7,37 +7,44 @@ import EditScreenInfo from '../components/EditScreenInfo'; ...@@ -7,37 +7,44 @@ 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 { create, getList } from '../api/api'; import { create, getList } from '../api/api';
import { BACKEND_ADDRESS } from '../api/constants';
import Ionicons from '@expo/vector-icons/Ionicons';
export default function ChatScreen({ navigation }) { export default function ChatScreen({ navigation }) {
const currentTime = new Date() const currentTime = new Date()
const defaultChatData = [{ from: 'esh', to: "dri", message: 'msg1', time: currentTime.setMinutes(currentTime.getMinutes() - 1) }, const defaultChatData = [{ from_user: 1, to_user: 2, message: 'msg1', timestamp: currentTime.setMinutes(currentTime.getMinutes() - 1) },
{ from: 'esh', to: "dri", message: 'msg2', time: currentTime.setMinutes(currentTime.getMinutes() - 2) }, { from_user: 1, to_user: 2, message: 'msg2', timestamp: currentTime.setMinutes(currentTime.getMinutes() - 2) },
{ from: 'dri', to: "esh", message: 'msg3', time: currentTime.setMinutes(currentTime.getMinutes() - 3) }, { from_user: 2, to_user: 1, message: 'msg3', timestamp: currentTime.setMinutes(currentTime.getMinutes() - 3), is_detected: false },
{ from: 'esh', to: "dri", message: 'msg4', time: currentTime.setMinutes(currentTime.getMinutes() - 4) }, { from_user: 1, to_user: 2, message: 'left', timestamp: currentTime.setMinutes(currentTime.getMinutes() - 4), is_detected: true },
{ from: 'dri', to: "esh", message: 'msg5', time: currentTime.setMinutes(currentTime.getMinutes() - 5) }, { from_user: 2, to_user: 1, message: 'msg5', timestamp: currentTime.setMinutes(currentTime.getMinutes() - 5) },
{ from: 'esh', to: "dri", message: 'msg1', time: currentTime.setDate(currentTime.getDate() - 1) }, { from_user: 1, to_user: 2, message: 'msg1', timestamp: currentTime.setDate(currentTime.getDate() - 1) },
{ from: 'esh', to: "dri", message: 'msg2', time: currentTime.setDate(currentTime.getDate() - 2) }, { from_user: 1, to_user: 2, message: 'msg2', timestamp: currentTime.setDate(currentTime.getDate() - 2) },
{ from: 'dri', to: "esh", message: 'msg3', time: currentTime.setDate(currentTime.getDate() - 3) }, { from_user: 2, to_user: 1, message: 'msg3', timestamp: currentTime.setDate(currentTime.getDate() - 3) },
{ from: 'esh', to: "dri", message: 'msg4', time: currentTime.setDate(currentTime.getDate() - 4) }, { from_user: 1, to_user: 2, message: 'msg4', timestamp: currentTime.setDate(currentTime.getDate() - 4) },
{ from: 'dri', to: "esh", message: 'msg5', time: currentTime.setDate(currentTime.getDate() - 5) }, { from_user: 2, to_user: 1, message: 'msg5', timestamp: currentTime.setDate(currentTime.getDate() - 5) },
] ]
const [detectedText, setDetectedText] = useState("") const [detectedText, setDetectedText] = useState("")
const [chatDetails, setChatDetails] = useState({ from_user: 1, to_user: 2, conversation_id: 1 }) const [chatDetails, setChatDetails] = useState({ from_user: 1, to_user: 2, conversation_id: 1 })
const [chats, setChats] = useState([]) const [chats, setChats] = useState([])
const [input, setInput] = useState('test') const [input, setInput] = useState('test')
const [loading, setLoading] = useState(true) const [loading, setLoading] = useState(true)
const ws = new WebSocket('ws://localhost:3000/ws') const ws = new WebSocket(`ws://${BACKEND_ADDRESS}/chatSocket/`)
useEffect(() => { useEffect(() => {
loadChats() // loadChats()
// startWebsocket() // startWebsocket()
loadSampleChats()
setLoading(false)
}, []) }, [])
const startWebsocket = () => { const startWebsocket = () => {
...@@ -61,6 +68,14 @@ export default function ChatScreen({ navigation }) { ...@@ -61,6 +68,14 @@ export default function ChatScreen({ navigation }) {
} }
const loadSampleChats = () => {
const chats_ = defaultChatData//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)
console.log({chats})
}
const loadChats = async () => { const loadChats = async () => {
await getList('chats').then(res => { await getList('chats').then(res => {
return res.json() return res.json()
......
...@@ -11,6 +11,17 @@ import os ...@@ -11,6 +11,17 @@ import os
from django.core.asgi import get_asgi_application from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings') # os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')
application = get_asgi_application() # application = get_asgi_application()
from channels.routing import ProtocolTypeRouter, URLRouter # noqa isort:skip
from .routing import websocket_urlpatterns# noqa isort:skip
application = ProtocolTypeRouter(
{
"http": get_asgi_application(),
"websocket": URLRouter(websocket_urlpatterns),
}
)
# Generated by Django 4.1 on 2022-08-18 03:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cms', '0002_conversation_chat'),
]
operations = [
migrations.AddField(
model_name='chat',
name='is_detected',
field=models.BooleanField(default=False),
),
]
...@@ -32,3 +32,4 @@ class Chat(models.Model): ...@@ -32,3 +32,4 @@ class Chat(models.Model):
User, related_name='to_convo', on_delete=models.PROTECT) User, related_name='to_convo', on_delete=models.PROTECT)
message = models.TextField() message = models.TextField()
timestamp = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now=True)
is_detected = models.BooleanField(default=False)
from channels.generic.websocket import JsonWebsocketConsumer
class ChatConsumer(JsonWebsocketConsumer):
"""
This consumer is used to show user's online status,
and send notifications.
"""
def __init__(self, *args, **kwargs):
super().__init__(args, kwargs)
self.room_name = None
def connect(self):
print("Connected!")
self.room_name = "home"
self.accept()
self.send_json(
{
"type": "welcome_message",
"message": "Hey there! You've successfully connected!",
}
)
def disconnect(self, code):
print("Disconnected!")
return super().disconnect(code)
def receive_json(self, content, **kwargs):
print(content)
return super().receive_json(content, **kwargs)
\ No newline at end of file
from django.urls import path
from backend.consumers import ChatConsumer
websocket_urlpatterns = [
path("/chatSocket", ChatConsumer.as_asgi())
]
\ No newline at end of file
...@@ -42,6 +42,7 @@ INSTALLED_APPS = [ ...@@ -42,6 +42,7 @@ INSTALLED_APPS = [
'rest_framework', 'rest_framework',
'backend.cms', 'backend.cms',
'corsheaders', 'corsheaders',
'channels'
] ]
MIDDLEWARE = [ MIDDLEWARE = [
...@@ -159,4 +160,6 @@ SIMPLE_JWT = { ...@@ -159,4 +160,6 @@ SIMPLE_JWT = {
'SLIDING_TOKEN_REFRESH_LIFETIME': datetime.timedelta(days=1), 'SLIDING_TOKEN_REFRESH_LIFETIME': datetime.timedelta(days=1),
} }
CORS_ORIGIN_ALLOW_ALL = True CORS_ORIGIN_ALLOW_ALL = True
\ No newline at end of file
ASGI_APPLICATION = "backend.asgi.application"
\ No newline at end of file
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