Skip to content

Commit

Permalink
finally
Browse files Browse the repository at this point in the history
  • Loading branch information
dhrumilp12 committed Jun 26, 2024
1 parent 179f04d commit e2eca63
Show file tree
Hide file tree
Showing 11 changed files with 169 additions and 206 deletions.

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion client/dist/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
content="This AI-Driven Mental Health Companion app provides mental health support through conversational AI, offering personalized advice, mood tracking, and mental health resources based on user inputs and interaction history. "
/>
<title>Earlent - Mental Health Companion</title>
<script type="module" crossorigin src="/assets/index-D2qPeAMt.js"></script>
<script type="module" crossorigin src="/assets/index-CX7orlQh.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-B_Zi3VXB.css">
</head>
<body>
Expand Down
7 changes: 4 additions & 3 deletions client/src/Components/authComponent.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -173,13 +173,14 @@ function AuthComponent() {
try {
const response = await axios.post('/api/user/anonymous_signin');
if (response && response.data) {
const userId = null;
const userId = "0";
const isAnon = true;
localStorage.setItem('token', response.data.access_token); // Ensure this is correctly saving the token
console.log('Token stored:', localStorage.getItem('token')); // Confirm the token is stored
setMessage('Anonymous sign-in successful!');
setSeverity('success');
setIsAuthenticated(true);
setUser({ userId });
setUser({ userId, isAnon });
navigate('/');
} else {
throw new Error('Invalid response from server');
Expand Down Expand Up @@ -325,4 +326,4 @@ function getStressorDescription(stressorId) {
}
}

export default AuthComponent
export default AuthComponent
2 changes: 1 addition & 1 deletion client/src/Components/navBar.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ function Navbar({ toggleSidebar }) {
Earlent
</Typography>

{user?.userId &&(
{!user?.isAnon &&(
<IconButton color="inherit" onClick={handleNotificationClick}>
<Badge badgeContent={notifications.length} color="secondary">
<NotificationsIcon />
Expand Down
2 changes: 1 addition & 1 deletion client/src/Components/sideBar.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ function Sidebar() {

const items = [
{ text: "Mind Chat", icon: <DeckIcon />, path: "/" },
...(user?.userId ? [
...(!user?.isAnon ? [
{ text: "Track Your Vibes", icon: <InsertEmoticonIcon />, path: "/user/mood_logging" },
{ text: "Mood Logs", icon: <ListAltIcon />, path: "/user/mood_logs" },
{ text: "Schedule Check-In", icon: <ScheduleIcon />, path: "/user/check_in" }, // New item for check-in page
Expand Down
98 changes: 4 additions & 94 deletions client/src/main.jsx
Original file line number Diff line number Diff line change
@@ -1,106 +1,16 @@
import React from 'react'
import ReactDOM from 'react-dom/client'

import App from './App.jsx'
import { BrowserRouter } from 'react-router-dom';
import { UserProvider } from './Components/userContext';

function urlBase64ToUint8Array(base64String) {
const padding = '='.repeat((4 - base64String.length % 4) % 4);
const base64 = (base64String + padding)
.replace(/-/g, '+')
.replace(/_/g, '/');

const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);

for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}

return outputArray;
}

function getToken() {
// Implement a function to retrieve the JWT token
return localStorage.getItem('token');
}

const VAPID_PUBLIC_KEY = "BJO2lvL7cXXdg0MqKdCtQyWOz3Nb1Ny-X8x_67MKdRtQOLLl3FRpAPJOUJEzjaQGNBcIOqwjeS165Rb3Pl0x2ZI";

if ('serviceWorker' in navigator) {
window.addEventListener('load', function () {
navigator.serviceWorker.register('../service-worker.js')
.then(function (registration) {
console.log('Service Worker registered with scope:', registration.scope);

// Request notification permission
return Notification.requestPermission().then(permission => {
if (permission !== 'granted') {
throw new Error('Permission not granted for Notification');
}

// Check for permission and subscribe for push notifications
return registration.pushManager.getSubscription();
}).then(function (subscription) {
if (!subscription) {
return registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array(VAPID_PUBLIC_KEY)
});
}
return subscription;

})
.then(function (subscription) {
console.log('Subscription:', subscription);

// Ensure the keys are properly encoded
const keys = {
p256dh: btoa(String.fromCharCode.apply(null, new Uint8Array(subscription.getKey('p256dh')))),
auth: btoa(String.fromCharCode.apply(null, new Uint8Array(subscription.getKey('auth'))))
};
console.log('Subscription keys:', keys);

if (!keys.p256dh || !keys.auth) {
console.error('Subscription object:', subscription);
throw new Error('Subscription keys are missing');
}
const subscriptionData = {
endpoint: subscription.endpoint,
keys: keys
};

const token = getToken();

if (!token) {
throw new Error('No token found');
}

return fetch('/api/subscribe', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify(subscriptionData),
});
})
.then(response => response.json())
.then(data => console.log('Subscription response:', data))
.catch(err => console.error('Subscription failed:', err));


})
.catch(function (err) {
console.error('Service Worker registration failed:', err);
});
});
}
import { UserProvider } from './Components/userContext';
import './serviceWorker.js'

ReactDOM.createRoot(document.getElementById('root')).render(
<BrowserRouter>
<UserProvider>
<App />
</UserProvider>
</BrowserRouter>
)
);
93 changes: 93 additions & 0 deletions client/src/serviceWorker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
function urlBase64ToUint8Array(base64String) {
const padding = '='.repeat((4 - base64String.length % 4) % 4);
const base64 = (base64String + padding)
.replace(/-/g, '+')
.replace(/_/g, '/');

const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);

for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}

return outputArray;
}

function getToken() {
// Implement a function to retrieve the JWT token
return localStorage.getItem('token');
}

const VAPID_PUBLIC_KEY = "BJO2lvL7cXXdg0MqKdCtQyWOz3Nb1Ny-X8x_67MKdRtQOLLl3FRpAPJOUJEzjaQGNBcIOqwjeS165Rb3Pl0x2ZI";

if ('serviceWorker' in navigator) {
window.addEventListener('load', function () {
navigator.serviceWorker.register('../service-worker.js')
.then(function (registration) {
console.log('Service Worker registered with scope:', registration.scope);

// Request notification permission
return Notification.requestPermission().then(permission => {
if (permission !== 'granted') {
throw new Error('Permission not granted for Notification');
}

// Check for permission and subscribe for push notifications
return registration.pushManager.getSubscription();
}).then(function (subscription) {
if (!subscription) {
return registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array(VAPID_PUBLIC_KEY)
});
}
return subscription;

})
.then(function (subscription) {
console.log('Subscription:', subscription);

// Ensure the keys are properly encoded
const keys = {
p256dh: btoa(String.fromCharCode.apply(null, new Uint8Array(subscription.getKey('p256dh')))),
auth: btoa(String.fromCharCode.apply(null, new Uint8Array(subscription.getKey('auth'))))
};
console.log('Subscription keys:', keys);

if (!keys.p256dh || !keys.auth) {
console.error('Subscription object:', subscription);
throw new Error('Subscription keys are missing');
}
const subscriptionData = {
endpoint: subscription.endpoint,
keys: keys
};

const token = getToken();

if (!token) {
throw new Error('No token found');
}

return fetch('/api/subscribe', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify(subscriptionData),
});
})
.then(response => response.json())
.then(data => console.log('Subscription response:', data))
.catch(err => console.error('Subscription failed:', err));


})
.catch(function (err) {
console.error('Service Worker registration failed:', err);
});
});
}

10 changes: 5 additions & 5 deletions server/agents/ai_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,10 +162,10 @@ def _create_agent_tools(self, tool_names=[]) -> list[Tool]:
StructuredTool.from_function(func)
)
continue

if tool_dict.get("retriever", False):
elif tool_dict.get("retriever", False):
retriever = self._get_cosmosdb_vector_store_retriever(
f"{db_name}.{tool_name}"
tool_name
)

retriever_chain = retriever | format_docs
Expand All @@ -180,12 +180,12 @@ def _create_agent_tools(self, tool_names=[]) -> list[Tool]:
else:
custom_tools.append(
Tool(
name=f"vector_search_{tool_name}",
name=f"{tool_name}",
func=func,
description=description
)
)

result_tools = community_tools + custom_tools

return result_tools
return result_tools
Loading

0 comments on commit e2eca63

Please sign in to comment.