cleaning a bunch of the auth stuff but not done
This commit is contained in:
@@ -25,7 +25,7 @@ app.get("/", (req: Request, res: Response) => {
|
|||||||
res.send("hello world.");
|
res.send("hello world.");
|
||||||
});
|
});
|
||||||
|
|
||||||
app.use("/api/users", getUserRoutes());
|
app.use("/api/user", getUserRoutes());
|
||||||
app.use("/api/search", getSearchRoutes());
|
app.use("/api/search", getSearchRoutes());
|
||||||
app.use("/api/conversations", getConversationRoutes());
|
app.use("/api/conversations", getConversationRoutes());
|
||||||
app.use("/api/contacts", getContactsRoutes());
|
app.use("/api/contacts", getContactsRoutes());
|
||||||
|
|||||||
@@ -14,21 +14,23 @@ export const authCheck = async (
|
|||||||
) => {
|
) => {
|
||||||
const { authorization } = req.headers;
|
const { authorization } = req.headers;
|
||||||
|
|
||||||
|
// verify jwt token
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const ticket = await client.verifyIdToken({
|
// const ticket = await client.verifyIdToken({
|
||||||
idToken: authorization ?? "",
|
// idToken: authorization ?? "",
|
||||||
audience:
|
// audience:
|
||||||
"423533244953-banligobgbof8hg89i6cr1l7u0p7c2pk.apps.googleusercontent.com", // Specify the CLIENT_ID of the app that accesses the backend
|
// "423533244953-banligobgbof8hg89i6cr1l7u0p7c2pk.apps.googleusercontent.com", // Specify the CLIENT_ID of the app that accesses the backend
|
||||||
});
|
// });
|
||||||
const userId = ticket.getPayload()?.sub;
|
// const userId = ticket.getPayload()?.sub;
|
||||||
const email = ticket.getPayload()?.email;
|
// const email = ticket.getPayload()?.email;
|
||||||
|
|
||||||
if (!userId) throw new Error("No google user Id found");
|
// if (!userId) throw new Error("No google user Id found");
|
||||||
|
|
||||||
// used in subsequent handlers
|
// // used in subsequent handlers
|
||||||
// todo: have to get our database id for the user instead of google's id
|
// // todo: have to get our database id for the user instead of google's id
|
||||||
res.locals.userId = userId;
|
// res.locals.userId = userId;
|
||||||
res.locals.email = email;
|
// res.locals.email = email;
|
||||||
|
|
||||||
next();
|
next();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
+33
-12
@@ -1,6 +1,7 @@
|
|||||||
import { GoogleUserInfo, User } from "@nirvana/core/models";
|
import { GoogleUserInfo, User } from "@nirvana/core/models";
|
||||||
import express, { Application, Request, Response } from "express";
|
import express, { Application, Request, Response } from "express";
|
||||||
|
|
||||||
|
import { OAuth2Client } from "google-auth-library";
|
||||||
import { ObjectID } from "bson";
|
import { ObjectID } from "bson";
|
||||||
import { ObjectId } from "mongodb";
|
import { ObjectId } from "mongodb";
|
||||||
import { UserService } from "../services/user.service";
|
import { UserService } from "../services/user.service";
|
||||||
@@ -8,31 +9,48 @@ import { UserStatus } from "../../core/models/user.model";
|
|||||||
import { authCheck } from "../middleware/auth";
|
import { authCheck } from "../middleware/auth";
|
||||||
import { collections } from "../services/database.service";
|
import { collections } from "../services/database.service";
|
||||||
|
|
||||||
|
const client = new OAuth2Client(
|
||||||
|
"423533244953-banligobgbof8hg89i6cr1l7u0p7c2pk.apps.googleusercontent.com"
|
||||||
|
);
|
||||||
|
|
||||||
export default function getUserRoutes() {
|
export default function getUserRoutes() {
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
|
|
||||||
router.use(express.json());
|
router.use(express.json());
|
||||||
|
|
||||||
// get user details based on id token
|
// get user details based on id token
|
||||||
router.get("/", authCheck, getUserDetails);
|
// router.get("/", authCheck, getUserDetails);
|
||||||
|
|
||||||
|
router.get("/login", login);
|
||||||
|
|
||||||
|
router.get("/authCheck", authCheck);
|
||||||
|
|
||||||
return router;
|
return router;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** Create user if doesn't exist
|
||||||
* Use token from middleware and get user properties
|
* Returns jwt token for client and user details
|
||||||
* create user if doesn't exist
|
|
||||||
*/
|
*/
|
||||||
async function getUserDetails(req: Request, res: Response) {
|
async function login(req: Request, res: Response) {
|
||||||
const email: string = res.locals.email;
|
|
||||||
const userId: string = res.locals.userId;
|
|
||||||
|
|
||||||
// passed in accesstoken no matter what
|
// passed in accesstoken no matter what
|
||||||
const { access_token } = req.query;
|
const { access_token, id_token } = req.query;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
const ticket = await client.verifyIdToken({
|
||||||
|
idToken: (id_token as string) ?? "",
|
||||||
|
audience:
|
||||||
|
"423533244953-banligobgbof8hg89i6cr1l7u0p7c2pk.apps.googleusercontent.com", // Specify the CLIENT_ID of the app that accesses the backend
|
||||||
|
});
|
||||||
|
const googleUserId = ticket.getPayload()?.sub as string;
|
||||||
|
const email = ticket.getPayload()?.email as string;
|
||||||
|
|
||||||
|
if (!googleUserId || !email) {
|
||||||
|
res.status(401).send("no google account found");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
// return user details if it passed auth middleware
|
// return user details if it passed auth middleware
|
||||||
const user = await UserService.getUserByGoogleId(userId);
|
const user = await UserService.getUserByEmail(email);
|
||||||
|
|
||||||
// if no user found, then go ahead and create user
|
// if no user found, then go ahead and create user
|
||||||
if (!user) {
|
if (!user) {
|
||||||
@@ -49,7 +67,7 @@ async function getUserDetails(req: Request, res: Response) {
|
|||||||
|
|
||||||
// create initial user model object
|
// create initial user model object
|
||||||
const newUser = new User(
|
const newUser = new User(
|
||||||
userId,
|
googleUserId,
|
||||||
userInfo.email,
|
userInfo.email,
|
||||||
userInfo.verifiedEmail,
|
userInfo.verifiedEmail,
|
||||||
userInfo.name,
|
userInfo.name,
|
||||||
@@ -67,6 +85,8 @@ async function getUserDetails(req: Request, res: Response) {
|
|||||||
|
|
||||||
newUser._id = insertResult?.insertedId;
|
newUser._id = insertResult?.insertedId;
|
||||||
|
|
||||||
|
// create jwt token with new user info
|
||||||
|
|
||||||
insertResult
|
insertResult
|
||||||
? res.status(200).send(newUser)
|
? res.status(200).send(newUser)
|
||||||
: res.status(500).send("Failed to create account, already exists");
|
: res.status(500).send("Failed to create account, already exists");
|
||||||
@@ -74,7 +94,8 @@ async function getUserDetails(req: Request, res: Response) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// otherwise, just return the user details
|
// create jwt token with existing user info
|
||||||
|
|
||||||
res.status(200).send(user);
|
res.status(200).send(user);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log(error);
|
console.log(error);
|
||||||
|
|||||||
@@ -6,8 +6,8 @@ export class User {
|
|||||||
public email: string,
|
public email: string,
|
||||||
public verifiedEmail: boolean,
|
public verifiedEmail: boolean,
|
||||||
public name: string,
|
public name: string,
|
||||||
public given_name: string,
|
public givenName: string,
|
||||||
public family_name: string,
|
public familyName: string,
|
||||||
public picture: string,
|
public picture: string,
|
||||||
public locale: string,
|
public locale: string,
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import { User } from "../models/user.model";
|
||||||
|
|
||||||
|
export default class LoginResponse {
|
||||||
|
constructor(public jwtToken: string, public userDetails: User) {}
|
||||||
|
}
|
||||||
@@ -1,8 +1,10 @@
|
|||||||
import { $authTokens } from "../../controller/recoil";
|
import { $authTokens } from "../../controller/recoil";
|
||||||
import Login from "../../pages/Login";
|
import Login from "../../pages/Login";
|
||||||
|
import NirvanaApi from "../../controller/nirvanaApi";
|
||||||
|
import { STORE_ITEMS } from "../../electron/constants";
|
||||||
import SkeletonLoader from "../loading/skeleton";
|
import SkeletonLoader from "../loading/skeleton";
|
||||||
import { useEffect } from "react";
|
import { useEffect } from "react";
|
||||||
import { useGetUserDetails } from "../../controller/index";
|
import { useLogin } from "../../controller/index";
|
||||||
import { useRecoilValue } from "recoil";
|
import { useRecoilValue } from "recoil";
|
||||||
|
|
||||||
export default function ProtectedRoute({
|
export default function ProtectedRoute({
|
||||||
@@ -10,26 +12,37 @@ export default function ProtectedRoute({
|
|||||||
}: {
|
}: {
|
||||||
children?: React.ReactNode;
|
children?: React.ReactNode;
|
||||||
}) {
|
}) {
|
||||||
const { data, isLoading, isError, refetch } = useGetUserDetails();
|
const { mutateAsync } = useLogin();
|
||||||
|
|
||||||
const authTokens = useRecoilValue($authTokens);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!authTokens) {
|
// on load of this, if we already have jwt tokens in store,
|
||||||
refetch();
|
// then try using them with auth check, and if successful with simple dime call, then let them continue
|
||||||
}
|
window.electronAPI.store
|
||||||
}, [authTokens]);
|
.get(STORE_ITEMS.AUTH_SESSION_JWT)
|
||||||
|
.then((jwtToken: string) => {
|
||||||
|
if (jwtToken) {
|
||||||
|
// todo use this to do an auth check...set the necessary things to make react query run the check
|
||||||
|
// check if the jwt token is good
|
||||||
|
|
||||||
if (isLoading)
|
// then pass onto the api and such
|
||||||
return (
|
|
||||||
<div className="container h-screen w-screen flex flex-col justify-center mx-10">
|
|
||||||
<SkeletonLoader />
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
|
|
||||||
if (isError) {
|
NirvanaApi._jwtToken = jwtToken;
|
||||||
return <Login onReady={() => refetch()} />;
|
}
|
||||||
}
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return <Login />;
|
||||||
|
|
||||||
|
// if (isLoading || isIdle)
|
||||||
|
// return (
|
||||||
|
// <div className="container h-screen w-screen flex flex-col justify-center mx-10">
|
||||||
|
// <SkeletonLoader />
|
||||||
|
// </div>
|
||||||
|
// );
|
||||||
|
|
||||||
|
// if (isError) {
|
||||||
|
// return <Login />;
|
||||||
|
// }
|
||||||
|
|
||||||
// if we can successfully get user details, we are good to continue
|
// if we can successfully get user details, we are good to continue
|
||||||
return <>{children}</>;
|
return <>{children}</>;
|
||||||
|
|||||||
@@ -1,175 +1,40 @@
|
|||||||
import { $authTokens, $searchQuery } from "./recoil";
|
import NirvanaApi, { login } from "./nirvanaApi";
|
||||||
import axios, { AxiosResponse } from "axios";
|
|
||||||
import { queryClient, socket } from "../nirvanaApp";
|
|
||||||
import { useEffect, useState } from "react";
|
|
||||||
import { useMutation, useQuery } from "react-query";
|
import { useMutation, useQuery } from "react-query";
|
||||||
|
|
||||||
import GetContactsResponse from "../../../core/responses/getContacts.response";
|
import { $authTokens } from "./recoil";
|
||||||
import GetConversationDetailsResponse from "@nirvana/core/responses/getConversationDetails.response";
|
|
||||||
import { ObjectId } from "mongodb";
|
|
||||||
import { RelationshipState } from "@nirvana/core/models/relationship.model";
|
|
||||||
import SearchResponse from "@nirvana/core/responses/search.response";
|
|
||||||
import SocketChannels from "@nirvana/core/sockets/channels";
|
|
||||||
import UpdateRelationshipStateRequest from "../../../core/requests/updateRelationshipState.request";
|
|
||||||
import { User } from "@nirvana/core/models";
|
|
||||||
import { nirvanaApi } from "./nirvanaApi";
|
|
||||||
import { useRecoilValue } from "recoil";
|
import { useRecoilValue } from "recoil";
|
||||||
|
|
||||||
// =========== API
|
|
||||||
export const localHost = "http://localhost:5000/api";
|
|
||||||
|
|
||||||
const getUserDetails = async (accessToken: string, idToken: string) => {
|
|
||||||
const response = await axios.get<User>(
|
|
||||||
localHost + `/users?access_token=${accessToken}`,
|
|
||||||
{
|
|
||||||
headers: { Authorization: idToken },
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
return response.data;
|
|
||||||
};
|
|
||||||
|
|
||||||
const search = async (idToken: string, searchQuery: string) => {
|
|
||||||
const response = await axios.get<SearchResponse>(
|
|
||||||
localHost + `/search?query=${searchQuery}`,
|
|
||||||
{
|
|
||||||
headers: { Authorization: idToken },
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
return response.data;
|
|
||||||
};
|
|
||||||
|
|
||||||
const getConversationDetails = async (
|
|
||||||
idToken: string,
|
|
||||||
otherUserGoogleId: string
|
|
||||||
) => {
|
|
||||||
const response = await axios.get<GetConversationDetailsResponse>(
|
|
||||||
localHost + `/conversations/${otherUserGoogleId}`,
|
|
||||||
{
|
|
||||||
headers: { Authorization: idToken },
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
return response.data;
|
|
||||||
};
|
|
||||||
|
|
||||||
const sendContactRequest = async (
|
|
||||||
idToken: string,
|
|
||||||
otherUserGoogleId: string
|
|
||||||
) => {
|
|
||||||
const response = await axios.post(
|
|
||||||
localHost + `/contacts/${otherUserGoogleId}`,
|
|
||||||
null,
|
|
||||||
{
|
|
||||||
headers: { Authorization: idToken },
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
return response.data;
|
|
||||||
};
|
|
||||||
|
|
||||||
const updateContactRequestState = async (
|
|
||||||
idToken: string,
|
|
||||||
reqObj: UpdateRelationshipStateRequest
|
|
||||||
) => {
|
|
||||||
const response = await axios.put(localHost + `/contacts`, reqObj, {
|
|
||||||
headers: { Authorization: idToken },
|
|
||||||
});
|
|
||||||
|
|
||||||
return response.data;
|
|
||||||
};
|
|
||||||
|
|
||||||
const getContactsBasicDetails = async (idToken: string) => {
|
|
||||||
const response = await axios.get<GetContactsResponse>(
|
|
||||||
localHost + `/contacts`,
|
|
||||||
{
|
|
||||||
headers: { Authorization: idToken },
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
return response.data;
|
|
||||||
};
|
|
||||||
|
|
||||||
// ====== QUERIES
|
// ====== QUERIES
|
||||||
export enum Querytypes {
|
|
||||||
GET_USER_DETAILS = "GET_USER_DETAILS",
|
export function useLogin() {
|
||||||
GET_SEARCH_RESULTS = "GET_SEARCH_RESULTS",
|
return useMutation("LOGIN", login, {});
|
||||||
GET_CONVERSATION_DETAILS = "GET_CONVERSATION_DETAILS",
|
|
||||||
GET_CONTACTS_RELATIONSHIPS = "GET_CONTACTS_RELATIONSHIPS",
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useGetUserDetails() {
|
// export function useGetUserDetails() {
|
||||||
const authTokens = useRecoilValue($authTokens);
|
// const authTokens = useRecoilValue($authTokens);
|
||||||
|
|
||||||
return useQuery(
|
// return useQuery(
|
||||||
Querytypes.GET_USER_DETAILS,
|
// Querytypes.GET_USER_DETAILS,
|
||||||
() => getUserDetails(authTokens?.accessToken, authTokens?.idToken),
|
// () => getUserDetails(authTokens?.accessToken, authTokens?.idToken),
|
||||||
{
|
// {
|
||||||
retry: false,
|
// retry: false,
|
||||||
refetchOnWindowFocus: false,
|
// refetchOnWindowFocus: false,
|
||||||
onError: (err) => {
|
// onError: (err) => {
|
||||||
console.log(err);
|
// console.log(err);
|
||||||
},
|
// },
|
||||||
}
|
// }
|
||||||
);
|
// );
|
||||||
}
|
// }
|
||||||
|
|
||||||
export function useSearch() {
|
// export function useSearch() {
|
||||||
const authTokens = useRecoilValue($authTokens);
|
// const authTokens = useRecoilValue($authTokens);
|
||||||
const searchQuery = useRecoilValue($searchQuery);
|
// const searchQuery = useRecoilValue($searchQuery);
|
||||||
|
|
||||||
return useQuery(
|
// return useQuery(
|
||||||
Querytypes.GET_SEARCH_RESULTS,
|
// Querytypes.GET_SEARCH_RESULTS,
|
||||||
() => search(authTokens.idToken, searchQuery),
|
// () => search(authTokens.idToken, searchQuery),
|
||||||
{ enabled: searchQuery ? true : false, refetchOnWindowFocus: false }
|
// { enabled: searchQuery ? true : false, refetchOnWindowFocus: false }
|
||||||
);
|
// );
|
||||||
}
|
// }
|
||||||
|
|
||||||
export function useConversationDetails(otherUserGoogleId: string) {
|
|
||||||
const authTokens = useRecoilValue($authTokens);
|
|
||||||
|
|
||||||
return useQuery(
|
|
||||||
Querytypes.GET_CONVERSATION_DETAILS + "/" + otherUserGoogleId,
|
|
||||||
() => getConversationDetails(authTokens.idToken, otherUserGoogleId),
|
|
||||||
{ enabled: otherUserGoogleId ? true : false }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useGetAllContactBasicDetails() {
|
|
||||||
const authTokens = useRecoilValue($authTokens);
|
|
||||||
|
|
||||||
return useQuery(
|
|
||||||
Querytypes.GET_CONTACTS_RELATIONSHIPS,
|
|
||||||
() => getContactsBasicDetails(authTokens.idToken),
|
|
||||||
{
|
|
||||||
refetchOnWindowFocus: false,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// =========== MUTATIONS
|
// =========== MUTATIONS
|
||||||
|
|
||||||
export function useSendContactRequest() {
|
|
||||||
const authTokens = useRecoilValue($authTokens);
|
|
||||||
|
|
||||||
return useMutation((otherGoogleUserId: string) =>
|
|
||||||
sendContactRequest(authTokens.idToken, otherGoogleUserId)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useUpdateRelationshipState() {
|
|
||||||
const authTokens = useRecoilValue($authTokens);
|
|
||||||
|
|
||||||
return useMutation(
|
|
||||||
(updateReqObj: UpdateRelationshipStateRequest) =>
|
|
||||||
updateContactRequestState(authTokens.idToken, updateReqObj),
|
|
||||||
{
|
|
||||||
onSettled: (data, error) => {
|
|
||||||
return queryClient.invalidateQueries(
|
|
||||||
Querytypes.GET_CONVERSATION_DETAILS + "/" + ""
|
|
||||||
);
|
|
||||||
},
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,20 +1,17 @@
|
|||||||
import axios, { AxiosRequestConfig, AxiosResponse } from "axios";
|
import axios, { AxiosRequestConfig, AxiosResponse, Method } from "axios";
|
||||||
|
|
||||||
|
import LoginResponse from "../../../core/responses/login.response";
|
||||||
import { User } from "@nirvana/core/models";
|
import { User } from "@nirvana/core/models";
|
||||||
|
|
||||||
// export const localHost = process.env.REACT_APP_API_DOMAIN;
|
// export const localHost = process.env.REACT_APP_API_DOMAIN;
|
||||||
|
|
||||||
export const localHost = "http://localhost:5000/api";
|
export const localHost = "http://localhost:5000/api";
|
||||||
|
|
||||||
class NirvanaApi {
|
export default class NirvanaApi {
|
||||||
// auth token from google that our backend will use
|
// auth token from google that our backend will use
|
||||||
private _authToken?: string;
|
static _jwtToken?: string;
|
||||||
|
|
||||||
setGoogleIdToken(_googleIdToken: string) {
|
static async fetch(url: string, method: Method, privateRoute = false) {
|
||||||
this._authToken = _googleIdToken;
|
|
||||||
}
|
|
||||||
|
|
||||||
async fetch(url: string, method: string, privateRoute = false) {
|
|
||||||
// use the auth token if it's a private route
|
// use the auth token if it's a private route
|
||||||
// error if no auth token and it's a private route
|
// error if no auth token and it's a private route
|
||||||
// throw error and show message on anything that is an error from the backend
|
// throw error and show message on anything that is an error from the backend
|
||||||
@@ -22,16 +19,22 @@ class NirvanaApi {
|
|||||||
try {
|
try {
|
||||||
const fullUrl = localHost + url;
|
const fullUrl = localHost + url;
|
||||||
|
|
||||||
var res;
|
let res;
|
||||||
if (privateRoute && this._authToken) {
|
if (privateRoute && this._jwtToken) {
|
||||||
res = await fetch(fullUrl, {
|
res = await fetch(fullUrl, {
|
||||||
method: method,
|
method: method,
|
||||||
headers: { Authorization: this._authToken },
|
headers: { Authorization: this._jwtToken },
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
res = await fetch(fullUrl);
|
res = await fetch(fullUrl);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
if (res.status === 401) throw Error("You are not authorized here");
|
||||||
|
|
||||||
|
throw Error("Something went wrong");
|
||||||
|
}
|
||||||
|
|
||||||
return await res.json();
|
return await res.json();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log(error);
|
console.log(error);
|
||||||
@@ -39,19 +42,19 @@ class NirvanaApi {
|
|||||||
throw Error(error);
|
throw Error(error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
user = {
|
|
||||||
async getUserDetails(accessToken: string): Promise<User> {
|
|
||||||
return await axios.get(localHost + `/users?access_token=${accessToken}`, {
|
|
||||||
headers: { Authorization: this._authToken },
|
|
||||||
});
|
|
||||||
},
|
|
||||||
async createUser(accessToken: string) {
|
|
||||||
return await axios.post(
|
|
||||||
localHost + `/users/create?access_token=${accessToken}`
|
|
||||||
);
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const nirvanaApi = new NirvanaApi();
|
export async function login(reqLoginTokens: {
|
||||||
|
accessToken: string;
|
||||||
|
idToken: string;
|
||||||
|
}): Promise<LoginResponse> {
|
||||||
|
return await NirvanaApi.fetch(
|
||||||
|
`/user/login?access_token=${reqLoginTokens.accessToken}&id_token=${reqLoginTokens.idToken}`,
|
||||||
|
"GET",
|
||||||
|
false
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function authCheck(jwtToken: string) {
|
||||||
|
return await NirvanaApi.fetch(`/user/authCheck`, "GET", true);
|
||||||
|
}
|
||||||
|
|||||||
@@ -14,12 +14,7 @@ export const $searchQuery = atom<string>({
|
|||||||
default: "",
|
default: "",
|
||||||
});
|
});
|
||||||
|
|
||||||
export const $authFailureCount = atom<number>({
|
// conversation id
|
||||||
key: "AUTH_FAILURE_COUNT",
|
|
||||||
default: 0,
|
|
||||||
});
|
|
||||||
|
|
||||||
// google Id of the selected person/conversation
|
|
||||||
export const $selectedConversation = atom<string>({
|
export const $selectedConversation = atom<string>({
|
||||||
key: "SELECTED_CONVERSATION",
|
key: "SELECTED_CONVERSATION",
|
||||||
default: null,
|
default: null,
|
||||||
|
|||||||
@@ -3,26 +3,27 @@ import { useEffect, useState } from "react";
|
|||||||
import SocketChannels from "@nirvana/core/sockets/channels";
|
import SocketChannels from "@nirvana/core/sockets/channels";
|
||||||
import { UserStatus } from "../../../core/models/user.model";
|
import { UserStatus } from "../../../core/models/user.model";
|
||||||
import { socket } from "../nirvanaApp";
|
import { socket } from "../nirvanaApp";
|
||||||
import { useGetAllContactBasicDetails } from "./index";
|
|
||||||
|
// import { useGetAllContactBasicDetails } from "./index";
|
||||||
|
|
||||||
export default function useSocketData() {
|
export default function useSocketData() {
|
||||||
// relationshipId's of the conversations where there is someone speaking
|
// relationshipId's of the conversations where there is someone speaking
|
||||||
const [speakingRooms, setSpeakingRooms] = useState<string[]>([]);
|
const [speakingRooms, setSpeakingRooms] = useState<string[]>([]);
|
||||||
|
|
||||||
const { data: allConvosDetsResponse, isFetched } =
|
// const { data: allConvosDetsResponse, isFetched } =
|
||||||
useGetAllContactBasicDetails();
|
// useGetAllContactBasicDetails();
|
||||||
|
|
||||||
useEffect(() => {
|
// useEffect(() => {
|
||||||
if (allConvosDetsResponse) {
|
// if (allConvosDetsResponse) {
|
||||||
allConvosDetsResponse.contactsDetails.map((contactDet) => {
|
// allConvosDetsResponse.contactsDetails.map((contactDet) => {
|
||||||
// join the right rooms based on the relevant contacts/conversations returned here
|
// // join the right rooms based on the relevant contacts/conversations returned here
|
||||||
socket.emit(
|
// socket.emit(
|
||||||
SocketChannels.JOIN_ROOM,
|
// SocketChannels.JOIN_ROOM,
|
||||||
contactDet.relationship._id.toString()
|
// contactDet.relationship._id.toString()
|
||||||
);
|
// );
|
||||||
});
|
// });
|
||||||
}
|
// }
|
||||||
}, [isFetched]);
|
// }, [isFetched]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
socket.on(
|
socket.on(
|
||||||
|
|||||||
@@ -3,12 +3,13 @@
|
|||||||
|
|
||||||
enum Channels {
|
enum Channels {
|
||||||
ACTIVATE_LOG_IN = "ACTIVATE_LOG_IN",
|
ACTIVATE_LOG_IN = "ACTIVATE_LOG_IN",
|
||||||
AUTH_TOKENS = "AUTH_TOKENS",
|
GOOGLE_AUTH_TOKENS = "GOOGLE_AUTH_TOKENS",
|
||||||
RESIZE_WINDOW = "RESIZE_WINDOW",
|
RESIZE_WINDOW = "RESIZE_WINDOW",
|
||||||
}
|
}
|
||||||
|
|
||||||
export enum STORE_ITEMS {
|
export enum STORE_ITEMS {
|
||||||
AUTH_TOKENS = "AUTH_TOKENS",
|
GOOGLE_AUTH_TOKENS = "GOOGLE_AUTH_TOKENS",
|
||||||
|
AUTH_SESSION_JWT = "AUTH_SESSION_JWT",
|
||||||
}
|
}
|
||||||
|
|
||||||
export const Dimensions = {
|
export const Dimensions = {
|
||||||
|
|||||||
@@ -9,36 +9,14 @@ const myApiOauth = new ElectronGoogleOAuth2(
|
|||||||
"423533244953-banligobgbof8hg89i6cr1l7u0p7c2pk.apps.googleusercontent.com",
|
"423533244953-banligobgbof8hg89i6cr1l7u0p7c2pk.apps.googleusercontent.com",
|
||||||
"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",
|
"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",
|
||||||
[""],
|
[""],
|
||||||
{ successRedirectURL: "https://usenirvana.com" }
|
{ successRedirectURL: "http://localhost:3000/auth/success" }
|
||||||
);
|
);
|
||||||
|
|
||||||
// FRESH LOGIN...either tokens of user expired or never had them
|
// FRESH GOOGLE LOGIN...either no json web tokens or trying to sign in with another account.
|
||||||
export async function handleLogin() {
|
export async function handleGoogleLogin() {
|
||||||
// read saved refresh token if any
|
|
||||||
// todo: fix this...should be working
|
|
||||||
const authTokens = await store.get(STORE_ITEMS.AUTH_TOKENS);
|
|
||||||
|
|
||||||
// todo: remove this when I have way of getting access token from a refresh token
|
|
||||||
// if (refreshToken) {
|
|
||||||
// console.log("have a refresh token from user auth previously", refreshToken);
|
|
||||||
// // myApiOauth.setTokens({ refresh_token: refreshToken });
|
|
||||||
|
|
||||||
// // send token to client
|
|
||||||
// browserWindow.webContents.send(Channels.AUTH_TOKENS, refreshToken);
|
|
||||||
// } else {
|
|
||||||
// const token = await myApiOauth.openAuthWindowAndGetTokens();
|
|
||||||
|
|
||||||
// // store the refresh token in cookies for app reopen
|
|
||||||
// store.set("tokens", token);
|
|
||||||
|
|
||||||
// // todo: send the access token to the renderer
|
|
||||||
// // send token to client
|
|
||||||
// browserWindow.webContents.send(Channels.AUTH_TOKENS, token);
|
|
||||||
// }
|
|
||||||
|
|
||||||
const tokens = await myApiOauth.openAuthWindowAndGetTokens();
|
const tokens = await myApiOauth.openAuthWindowAndGetTokens();
|
||||||
|
|
||||||
store.set(STORE_ITEMS.AUTH_TOKENS, tokens);
|
store.set(STORE_ITEMS.GOOGLE_AUTH_TOKENS, tokens);
|
||||||
|
|
||||||
browserWindow.webContents.send(Channels.AUTH_TOKENS, tokens);
|
browserWindow.webContents.send(Channels.GOOGLE_AUTH_TOKENS, tokens);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { BrowserWindow, app, dialog, ipcMain } from "electron";
|
import { BrowserWindow, app, dialog, ipcMain } from "electron";
|
||||||
import Channels, { Dimensions } from "./electron/constants";
|
import Channels, { Dimensions } from "./electron/constants";
|
||||||
|
|
||||||
import { handleLogin } from "./electron/handleLogin";
|
import { handleGoogleLogin } from "./electron/handleLogin";
|
||||||
import path from "path";
|
import path from "path";
|
||||||
import store from "./electron/store";
|
import store from "./electron/store";
|
||||||
|
|
||||||
@@ -49,7 +49,7 @@ app
|
|||||||
// activate login
|
// activate login
|
||||||
ipcMain.on(Channels.ACTIVATE_LOG_IN, async (event, arg) => {
|
ipcMain.on(Channels.ACTIVATE_LOG_IN, async (event, arg) => {
|
||||||
console.log("initiating log in");
|
console.log("initiating log in");
|
||||||
await handleLogin();
|
await handleGoogleLogin();
|
||||||
});
|
});
|
||||||
|
|
||||||
// access storage/cookies
|
// access storage/cookies
|
||||||
|
|||||||
@@ -7,13 +7,12 @@ import { FaVolumeUp } from "react-icons/fa";
|
|||||||
import SkeletonLoader from "../../../components/loading/skeleton";
|
import SkeletonLoader from "../../../components/loading/skeleton";
|
||||||
import UserAvatarWithStatus from "../../../components/User/userAvatarWithStatus";
|
import UserAvatarWithStatus from "../../../components/User/userAvatarWithStatus";
|
||||||
import UserStatusText from "../../../components/User/userStatusText";
|
import UserStatusText from "../../../components/User/userStatusText";
|
||||||
import { useGetAllContactBasicDetails } from "../../../controller";
|
|
||||||
import { useRecoilState } from "recoil";
|
import { useRecoilState } from "recoil";
|
||||||
import useSocketData from "../../../controller/sockets";
|
import useSocketData from "../../../controller/sockets";
|
||||||
|
|
||||||
export default function Conversations() {
|
export default function Conversations() {
|
||||||
const { data: contactDetailsListResponse, isLoading } =
|
// const { data: contactDetailsListResponse, isLoading } =
|
||||||
useGetAllContactBasicDetails();
|
// useGetAllContactBasicDetails();
|
||||||
const { speakingRooms } = useSocketData();
|
const { speakingRooms } = useSocketData();
|
||||||
const [selectedConvo, setSelectedConvo] = useRecoilState(
|
const [selectedConvo, setSelectedConvo] = useRecoilState(
|
||||||
$selectedConversation
|
$selectedConversation
|
||||||
@@ -45,7 +44,7 @@ export default function Conversations() {
|
|||||||
</Tooltip>
|
</Tooltip>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{isLoading ? (
|
{/* {isLoading ? (
|
||||||
<SkeletonLoader />
|
<SkeletonLoader />
|
||||||
) : (
|
) : (
|
||||||
<div className="flex flex-col m-5 p-4">
|
<div className="flex flex-col m-5 p-4">
|
||||||
@@ -84,7 +83,7 @@ export default function Conversations() {
|
|||||||
}
|
}
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)} */}
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,100 +1,100 @@
|
|||||||
import { $authTokens, $searchQuery } from "../../../controller/recoil";
|
// import { $authTokens, $searchQuery } from "../../../controller/recoil";
|
||||||
import { Dropdown, Menu } from "antd";
|
// import { Dropdown, Menu } from "antd";
|
||||||
import Logo, { LogoType } from "../../../components/Logo";
|
// import Logo, { LogoType } from "../../../components/Logo";
|
||||||
import { useRecoilState, useSetRecoilState } from "recoil";
|
// import { useRecoilState, useSetRecoilState } from "recoil";
|
||||||
|
|
||||||
import { GlobalHotKeys } from "react-hotkeys";
|
// import { GlobalHotKeys } from "react-hotkeys";
|
||||||
import { STORE_ITEMS } from "../../../electron/constants";
|
// import { STORE_ITEMS } from "../../../electron/constants";
|
||||||
import SocketChannels from "@nirvana/core/sockets/channels";
|
// import SocketChannels from "@nirvana/core/sockets/channels";
|
||||||
import UserAvatarWithStatus from "../../../components/User/userAvatarWithStatus";
|
// import UserAvatarWithStatus from "../../../components/User/userAvatarWithStatus";
|
||||||
import { UserStatus } from "@nirvana/core/models";
|
// import { UserStatus } from "@nirvana/core/models";
|
||||||
import { socket } from "../../../nirvanaApp";
|
// import { socket } from "../../../nirvanaApp";
|
||||||
import { useGetUserDetails } from "../../../controller/index";
|
// // import { useGetUserDetails } from "../../../controller/index";
|
||||||
import { useRef } from "react";
|
// import { useRef } from "react";
|
||||||
|
|
||||||
export default function Header() {
|
// export default function Header() {
|
||||||
const { data: user, isLoading } = useGetUserDetails();
|
// // const { data: user, isLoading } = useGetUserDetails();
|
||||||
const [searchQuery, setSearchQuery] = useRecoilState($searchQuery);
|
// const [searchQuery, setSearchQuery] = useRecoilState($searchQuery);
|
||||||
|
|
||||||
const inputRef = useRef(null);
|
// const inputRef = useRef(null);
|
||||||
|
|
||||||
const setAuthTokens = useSetRecoilState($authTokens);
|
// const setAuthTokens = useSetRecoilState($authTokens);
|
||||||
|
|
||||||
if (isLoading) {
|
// if (isLoading) {
|
||||||
return <span>getting data</span>;
|
// return <span>getting data</span>;
|
||||||
}
|
// }
|
||||||
|
|
||||||
const logOut = () => {
|
// const logOut = () => {
|
||||||
window.electronAPI.store.set(STORE_ITEMS.AUTH_TOKENS, null);
|
// window.electronAPI.store.set(STORE_ITEMS.GOOGLE_AUTH_TOKENS, null);
|
||||||
setAuthTokens(null);
|
// setAuthTokens(null);
|
||||||
};
|
// };
|
||||||
|
|
||||||
const updateStatus = (newStatus: UserStatus) => {
|
// const updateStatus = (newStatus: UserStatus) => {
|
||||||
// send update in socket
|
// // send update in socket
|
||||||
socket.emit(
|
// socket.emit(
|
||||||
SocketChannels.SEND_USER_STATUS_UPDATE,
|
// SocketChannels.SEND_USER_STATUS_UPDATE,
|
||||||
user.googleId,
|
// user.googleId,
|
||||||
newStatus
|
// newStatus
|
||||||
);
|
// );
|
||||||
};
|
// };
|
||||||
|
|
||||||
const ProfileMenu = (
|
// const ProfileMenu = (
|
||||||
<Menu>
|
// <Menu>
|
||||||
<Menu.Item key="0">
|
// <Menu.Item key="0">
|
||||||
<button onClick={logOut}>Log Out</button>
|
// <button onClick={logOut}>Log Out</button>
|
||||||
</Menu.Item>
|
// </Menu.Item>
|
||||||
<Menu.Item key="1">
|
// <Menu.Item key="1">
|
||||||
{user.status === UserStatus.ONLINE ? (
|
// {user.status === UserStatus.ONLINE ? (
|
||||||
<button onClick={() => updateStatus(UserStatus.OFFLINE)}>
|
// <button onClick={() => updateStatus(UserStatus.OFFLINE)}>
|
||||||
Set status as away
|
// Set status as away
|
||||||
</button>
|
// </button>
|
||||||
) : (
|
// ) : (
|
||||||
<button onClick={() => updateStatus(UserStatus.ONLINE)}>
|
// <button onClick={() => updateStatus(UserStatus.ONLINE)}>
|
||||||
Set status as online
|
// Set status as online
|
||||||
</button>
|
// </button>
|
||||||
)}
|
// )}
|
||||||
</Menu.Item>
|
// </Menu.Item>
|
||||||
</Menu>
|
// </Menu>
|
||||||
);
|
// );
|
||||||
|
|
||||||
// hot keys for selecting search
|
// // hot keys for selecting search
|
||||||
const handleSearch = () => {
|
// const handleSearch = () => {
|
||||||
if (inputRef?.current) {
|
// if (inputRef?.current) {
|
||||||
inputRef?.current?.focus();
|
// inputRef?.current?.focus();
|
||||||
setSearchQuery("");
|
// setSearchQuery("");
|
||||||
}
|
// }
|
||||||
};
|
// };
|
||||||
|
|
||||||
const keyMap = { START_SEARCH: "/" };
|
// const keyMap = { START_SEARCH: "/" };
|
||||||
const handlers = { START_SEARCH: handleSearch };
|
// const handlers = { START_SEARCH: handleSearch };
|
||||||
|
|
||||||
return (
|
// return (
|
||||||
<>
|
// <>
|
||||||
<GlobalHotKeys handlers={handlers} keyMap={keyMap}></GlobalHotKeys>
|
// <GlobalHotKeys handlers={handlers} keyMap={keyMap}></GlobalHotKeys>
|
||||||
|
|
||||||
<div className="flex flex-row items-center bg-zinc-800 h-20 px-5">
|
// <div className="flex flex-row items-center bg-zinc-800 h-20 px-5">
|
||||||
<Logo type={LogoType.small} className="scale-[0.4]" />
|
// <Logo type={LogoType.small} className="scale-[0.4]" />
|
||||||
<input
|
// <input
|
||||||
ref={inputRef}
|
// ref={inputRef}
|
||||||
placeholder="type / to search"
|
// placeholder="type / to search"
|
||||||
className="placeholder:text-zinc-400 bg-transparent outline-none text-zinc-100"
|
// className="placeholder:text-zinc-400 bg-transparent outline-none text-zinc-100"
|
||||||
value={searchQuery}
|
// value={searchQuery}
|
||||||
onChange={(e) => setSearchQuery(e.target.value)}
|
// onChange={(e) => setSearchQuery(e.target.value)}
|
||||||
/>
|
// />
|
||||||
|
|
||||||
<button
|
// <button
|
||||||
onClick={() => updateStatus(UserStatus.FLOW_STATE)}
|
// onClick={() => updateStatus(UserStatus.FLOW_STATE)}
|
||||||
className="ml-auto mr-2 hover:scale-110 bg-zinc-600 text-teal-500 py-1 px-2 rounded-lg text-sm"
|
// className="ml-auto mr-2 hover:scale-110 bg-zinc-600 text-teal-500 py-1 px-2 rounded-lg text-sm"
|
||||||
>
|
// >
|
||||||
flow state
|
// flow state
|
||||||
</button>
|
// </button>
|
||||||
|
|
||||||
<Dropdown overlay={ProfileMenu} trigger={["click"]}>
|
// <Dropdown overlay={ProfileMenu} trigger={["click"]}>
|
||||||
<span className="px-5">
|
// <span className="px-5">
|
||||||
<UserAvatarWithStatus user={user} />
|
// <UserAvatarWithStatus user={user} />
|
||||||
</span>
|
// </span>
|
||||||
</Dropdown>
|
// </Dropdown>
|
||||||
</div>
|
// </div>
|
||||||
</>
|
// </>
|
||||||
);
|
// );
|
||||||
}
|
// }
|
||||||
|
|||||||
@@ -2,29 +2,28 @@ import Logo, { LogoType } from "../../components/Logo";
|
|||||||
|
|
||||||
import { $searchQuery } from "../../controller/recoil";
|
import { $searchQuery } from "../../controller/recoil";
|
||||||
import Conversations from "./conversations";
|
import Conversations from "./conversations";
|
||||||
import Header from "./header";
|
// import Header from "./header";
|
||||||
import Search from "./search";
|
import Search from "./search";
|
||||||
import SelectedConversation from "./selectedConversation";
|
// import SelectedConversation from "./selectedConversation";
|
||||||
import { useEffect } from "react";
|
import { useEffect } from "react";
|
||||||
import { useGetUserDetails } from "../../controller/";
|
|
||||||
import { useRecoilValue } from "recoil";
|
import { useRecoilValue } from "recoil";
|
||||||
|
|
||||||
export default function Home() {
|
export default function Home() {
|
||||||
const { data: user } = useGetUserDetails();
|
// const { data: user } = useGetUserDetails();
|
||||||
const searchQuery = useRecoilValue($searchQuery);
|
const searchQuery = useRecoilValue($searchQuery);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="h-screen bg-zinc-700 flex flex-row">
|
<div className="h-screen bg-zinc-700 flex flex-row">
|
||||||
<div className="flex-1">
|
<div className="flex-1">
|
||||||
{/* header */}
|
{/* header */}
|
||||||
<Header />
|
{/* <Header /> */}
|
||||||
|
|
||||||
{/* main content */}
|
{/* main content */}
|
||||||
|
|
||||||
{searchQuery ? <Search /> : <Conversations />}
|
{searchQuery ? <Search /> : <Conversations />}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<SelectedConversation />
|
{/* <SelectedConversation /> */}
|
||||||
|
|
||||||
<button></button>
|
<button></button>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import {
|
|||||||
$searchQuery,
|
$searchQuery,
|
||||||
$selectedConversation,
|
$selectedConversation,
|
||||||
} from "../../../controller/recoil";
|
} from "../../../controller/recoil";
|
||||||
import { useGetUserDetails, useSearch } from "../../../controller";
|
|
||||||
|
|
||||||
import { FaAngleRight } from "react-icons/fa";
|
import { FaAngleRight } from "react-icons/fa";
|
||||||
import { Tooltip } from "@mui/material";
|
import { Tooltip } from "@mui/material";
|
||||||
@@ -22,21 +21,22 @@ export default function Search() {
|
|||||||
$selectedConversation
|
$selectedConversation
|
||||||
);
|
);
|
||||||
|
|
||||||
const { data: userDetails } = useGetUserDetails();
|
// const { data: userDetails } = useGetUserDetails();
|
||||||
|
|
||||||
const { data, isLoading, isError, refetch } = useSearch();
|
// const { data, isLoading, isError, refetch } = useSearch();
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
refetch();
|
// todo debounce after three seconds and show debounce loading while
|
||||||
|
// refetch();
|
||||||
}, [searchQuery]);
|
}, [searchQuery]);
|
||||||
|
|
||||||
if (!data?.users) {
|
// if (!data?.users) {
|
||||||
return (
|
// return (
|
||||||
<span className="text-white">
|
// <span className="text-white">
|
||||||
no results. please try someone's email or name.
|
// no results. please try someone's email or name.
|
||||||
</span>
|
// </span>
|
||||||
);
|
// );
|
||||||
}
|
// }
|
||||||
|
|
||||||
const goBack = () => {
|
const goBack = () => {
|
||||||
// implicity takes user back
|
// implicity takes user back
|
||||||
@@ -97,10 +97,10 @@ export default function Search() {
|
|||||||
Go back
|
Go back
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
{data?.users?.map((user) => {
|
{/* {data?.users?.map((user) => {
|
||||||
if (user.googleId === userDetails.googleId) return <></>;
|
if (user.googleId === userDetails.googleId) return <></>;
|
||||||
return renderUserRow(user);
|
return renderUserRow(user);
|
||||||
})}
|
})} */}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,331 +1,325 @@
|
|||||||
import { FaMicrophone, FaPlay, FaWindowClose } from "react-icons/fa";
|
// import { FaMicrophone, FaPlay, FaWindowClose } from "react-icons/fa";
|
||||||
import { GlobalHotKeys, KeyMap } from "react-hotkeys";
|
// import { GlobalHotKeys, KeyMap } from "react-hotkeys";
|
||||||
import {
|
// import { useEffect, useState } from "react";
|
||||||
Querytypes,
|
|
||||||
useConversationDetails,
|
|
||||||
useGetUserDetails,
|
|
||||||
useSendContactRequest,
|
|
||||||
useUpdateRelationshipState,
|
|
||||||
} from "../../../controller";
|
|
||||||
import { useEffect, useState } from "react";
|
|
||||||
|
|
||||||
import { $selectedConversation } from "../../../controller/recoil";
|
// import { $selectedConversation } from "../../../controller/recoil";
|
||||||
import { Dimensions } from "../../../electron/constants";
|
// import { Dimensions } from "../../../electron/constants";
|
||||||
import { RelationshipState } from "@nirvana/core/models/relationship.model";
|
// import { Querytypes } from "../../../controller";
|
||||||
import SocketChannels from "@nirvana/core/sockets/channels";
|
// import { RelationshipState } from "@nirvana/core/models/relationship.model";
|
||||||
import UpdateRelationshipStateRequest from "@nirvana/core/requests/updateRelationshipState.request";
|
// import SocketChannels from "@nirvana/core/sockets/channels";
|
||||||
import UserStatusText from "../../../components/User/userStatusText";
|
// import UpdateRelationshipStateRequest from "@nirvana/core/requests/updateRelationshipState.request";
|
||||||
import moment from "moment";
|
// import UserStatusText from "../../../components/User/userStatusText";
|
||||||
import { queryClient } from "../../../nirvanaApp";
|
// import moment from "moment";
|
||||||
import { socket } from "../../../nirvanaApp";
|
// import { queryClient } from "../../../nirvanaApp";
|
||||||
import toast from "react-hot-toast";
|
// import { socket } from "../../../nirvanaApp";
|
||||||
import { useRecoilState } from "recoil";
|
// import toast from "react-hot-toast";
|
||||||
|
// import { useRecoilState } from "recoil";
|
||||||
|
|
||||||
let audioChunks: any = [];
|
// let audioChunks: any = [];
|
||||||
|
|
||||||
const constraints = {
|
// const constraints = {
|
||||||
audio: true,
|
// audio: true,
|
||||||
// {
|
// // {
|
||||||
// // mandatory: {
|
// // // mandatory: {
|
||||||
// // chromeMediaSource: "desktop",
|
// // // chromeMediaSource: "desktop",
|
||||||
// // },
|
// // // },
|
||||||
// autoGainControl: true,
|
// // autoGainControl: true,
|
||||||
// echoCancellation: true,
|
// // echoCancellation: true,
|
||||||
// } as MediaTrackConstraints,
|
// // } as MediaTrackConstraints,
|
||||||
};
|
// };
|
||||||
|
|
||||||
export default function SelectedConversation() {
|
// export default function SelectedConversation() {
|
||||||
const [selectedConvo, setSelectedConvo] = useRecoilState(
|
// const [selectedConvo, setSelectedConvo] = useRecoilState(
|
||||||
$selectedConversation
|
// $selectedConversation
|
||||||
);
|
// );
|
||||||
const { data: userDetailsData } = useGetUserDetails();
|
// const { data: userDetailsData } = useGetUserDetails();
|
||||||
const { data: convoDetailsResponse, isLoading } =
|
// const { data: convoDetailsResponse, isLoading } =
|
||||||
useConversationDetails(selectedConvo);
|
// useConversationDetails(selectedConvo);
|
||||||
const { mutate: sendContactRequest } = useSendContactRequest();
|
// const { mutate: sendContactRequest } = useSendContactRequest();
|
||||||
const { mutate: updateRelationshipState } = useUpdateRelationshipState();
|
// const { mutate: updateRelationshipState } = useUpdateRelationshipState();
|
||||||
const [isRecording, setIsRecording] = useState<boolean>(false);
|
// const [isRecording, setIsRecording] = useState<boolean>(false);
|
||||||
|
|
||||||
const [hasMicPermissions, sethasMicPermissions] = useState<boolean>(false);
|
// const [hasMicPermissions, sethasMicPermissions] = useState<boolean>(false);
|
||||||
const [mediaRecorder, setMediaRecorder] = useState<MediaRecorder>();
|
// const [mediaRecorder, setMediaRecorder] = useState<MediaRecorder>();
|
||||||
|
|
||||||
// audio handling
|
// // audio handling
|
||||||
// setting up recording permissions
|
// // setting up recording permissions
|
||||||
useEffect(() => {
|
// useEffect(() => {
|
||||||
try {
|
// try {
|
||||||
// checking for permissions for recording
|
// // checking for permissions for recording
|
||||||
// won't work in https!!!
|
// // won't work in https!!!
|
||||||
navigator.mediaDevices
|
// navigator.mediaDevices
|
||||||
.getUserMedia(constraints)
|
// .getUserMedia(constraints)
|
||||||
.then((stream) => {
|
// .then((stream) => {
|
||||||
const mediaRecorder = new MediaRecorder(stream);
|
// const mediaRecorder = new MediaRecorder(stream);
|
||||||
setMediaRecorder(mediaRecorder);
|
// setMediaRecorder(mediaRecorder);
|
||||||
|
|
||||||
console.log(mediaRecorder);
|
// console.log(mediaRecorder);
|
||||||
|
|
||||||
console.log("Permission Granted");
|
// console.log("Permission Granted");
|
||||||
sethasMicPermissions(true);
|
// sethasMicPermissions(true);
|
||||||
})
|
// })
|
||||||
.catch((e: any) => {
|
// .catch((e: any) => {
|
||||||
console.log("Permission Denied");
|
// console.log("Permission Denied");
|
||||||
|
|
||||||
toast.error(
|
// toast.error(
|
||||||
"Please make sure that you have connected a microphone and given permissions."
|
// "Please make sure that you have connected a microphone and given permissions."
|
||||||
);
|
// );
|
||||||
|
|
||||||
console.log(e);
|
// console.log(e);
|
||||||
sethasMicPermissions(false);
|
// sethasMicPermissions(false);
|
||||||
});
|
// });
|
||||||
} catch (error) {
|
// } catch (error) {
|
||||||
console.log(error);
|
// console.log(error);
|
||||||
toast.error("something went wrong");
|
// toast.error("something went wrong");
|
||||||
}
|
// }
|
||||||
}, []);
|
// }, []);
|
||||||
|
|
||||||
// todo: hacky way of re-linking event listeners once we have the relationship id
|
// // todo: hacky way of re-linking event listeners once we have the relationship id
|
||||||
useEffect(() => {
|
// useEffect(() => {
|
||||||
if (mediaRecorder && convoDetailsResponse) {
|
// if (mediaRecorder && convoDetailsResponse) {
|
||||||
mediaRecorder.addEventListener(
|
// mediaRecorder.addEventListener(
|
||||||
"dataavailable",
|
// "dataavailable",
|
||||||
mediaRecorderDataAvailable
|
// mediaRecorderDataAvailable
|
||||||
);
|
// );
|
||||||
mediaRecorder.addEventListener("stop", mediaRecorderStop);
|
// mediaRecorder.addEventListener("stop", mediaRecorderStop);
|
||||||
}
|
// }
|
||||||
|
|
||||||
return () => {
|
// return () => {
|
||||||
if (mediaRecorder) {
|
// if (mediaRecorder) {
|
||||||
mediaRecorder.removeEventListener(
|
// mediaRecorder.removeEventListener(
|
||||||
"dataavailable",
|
// "dataavailable",
|
||||||
mediaRecorderDataAvailable
|
// mediaRecorderDataAvailable
|
||||||
);
|
// );
|
||||||
mediaRecorder.removeEventListener("stop", mediaRecorderStop);
|
// mediaRecorder.removeEventListener("stop", mediaRecorderStop);
|
||||||
}
|
// }
|
||||||
};
|
// };
|
||||||
}, [mediaRecorder, convoDetailsResponse]);
|
// }, [mediaRecorder, convoDetailsResponse]);
|
||||||
|
|
||||||
const mediaRecorderDataAvailable = (event: any) => {
|
// const mediaRecorderDataAvailable = (event: any) => {
|
||||||
audioChunks.push(event.data);
|
// audioChunks.push(event.data);
|
||||||
};
|
// };
|
||||||
|
|
||||||
const mediaRecorderStop = () => {
|
// const mediaRecorderStop = () => {
|
||||||
socket.emit(
|
// socket.emit(
|
||||||
SocketChannels.SEND_AUDIO_CLIP,
|
// SocketChannels.SEND_AUDIO_CLIP,
|
||||||
convoDetailsResponse.ourRelationship._id.toString(),
|
// convoDetailsResponse.ourRelationship._id.toString(),
|
||||||
audioChunks
|
// audioChunks
|
||||||
);
|
// );
|
||||||
|
|
||||||
// testing playing before sending off
|
// // testing playing before sending off
|
||||||
// const audioBlob = new Blob(audioChunks);
|
// // const audioBlob = new Blob(audioChunks);
|
||||||
// const audioUrl = URL.createObjectURL(audioBlob);
|
// // const audioUrl = URL.createObjectURL(audioBlob);
|
||||||
// const audio = new Audio(audioUrl);
|
// // const audio = new Audio(audioUrl);
|
||||||
// audio.play();
|
// // audio.play();
|
||||||
|
|
||||||
audioChunks = [];
|
// audioChunks = [];
|
||||||
};
|
// };
|
||||||
|
|
||||||
useEffect(() => {
|
// useEffect(() => {
|
||||||
// if selected, then change the bounds of this window as well
|
// // if selected, then change the bounds of this window as well
|
||||||
if (selectedConvo) {
|
// if (selectedConvo) {
|
||||||
window.electronAPI.window.resizeWindow(Dimensions.selectedConvo);
|
// window.electronAPI.window.resizeWindow(Dimensions.selectedConvo);
|
||||||
} else {
|
// } else {
|
||||||
// change bounds back
|
// // change bounds back
|
||||||
window.electronAPI.window.resizeWindow(Dimensions.default);
|
// window.electronAPI.window.resizeWindow(Dimensions.default);
|
||||||
}
|
// }
|
||||||
}, [selectedConvo]);
|
// }, [selectedConvo]);
|
||||||
|
|
||||||
// if no convo selected, don't show this
|
// // if no convo selected, don't show this
|
||||||
if (!selectedConvo) {
|
// if (!selectedConvo) {
|
||||||
return <></>;
|
// return <></>;
|
||||||
}
|
// }
|
||||||
|
|
||||||
// todo: add cancel request option
|
// // todo: add cancel request option
|
||||||
|
|
||||||
const sendRequest = () => {
|
// const sendRequest = () => {
|
||||||
const otherUserGoogleId = convoDetailsResponse.contactUser.googleId;
|
// const otherUserGoogleId = convoDetailsResponse.contactUser.googleId;
|
||||||
|
|
||||||
// todo mutation to create a user
|
// // todo mutation to create a user
|
||||||
sendContactRequest(otherUserGoogleId, {
|
// sendContactRequest(otherUserGoogleId, {
|
||||||
onSettled: (data, error) => {
|
// onSettled: (data, error) => {
|
||||||
return queryClient.invalidateQueries(
|
// return queryClient.invalidateQueries(
|
||||||
Querytypes.GET_CONVERSATION_DETAILS + "/" + otherUserGoogleId
|
// Querytypes.GET_CONVERSATION_DETAILS + "/" + otherUserGoogleId
|
||||||
);
|
// );
|
||||||
},
|
// },
|
||||||
});
|
// });
|
||||||
};
|
// };
|
||||||
|
|
||||||
const acceptRequest = () => {
|
// const acceptRequest = () => {
|
||||||
const otherUserGoogleId = convoDetailsResponse.contactUser.googleId;
|
// const otherUserGoogleId = convoDetailsResponse.contactUser.googleId;
|
||||||
|
|
||||||
updateRelationshipState(
|
// updateRelationshipState(
|
||||||
new UpdateRelationshipStateRequest(
|
// new UpdateRelationshipStateRequest(
|
||||||
convoDetailsResponse.ourRelationship._id,
|
// convoDetailsResponse.ourRelationship._id,
|
||||||
RelationshipState.ACTIVE
|
// RelationshipState.ACTIVE
|
||||||
),
|
// ),
|
||||||
{
|
// {
|
||||||
onSettled: (data, error) => {
|
// onSettled: (data, error) => {
|
||||||
return queryClient.invalidateQueries(
|
// return queryClient.invalidateQueries(
|
||||||
Querytypes.GET_CONVERSATION_DETAILS + "/" + otherUserGoogleId
|
// Querytypes.GET_CONVERSATION_DETAILS + "/" + otherUserGoogleId
|
||||||
);
|
// );
|
||||||
},
|
// },
|
||||||
}
|
// }
|
||||||
);
|
// );
|
||||||
};
|
// };
|
||||||
|
|
||||||
if (isLoading) return <span>Please wait</span>;
|
// if (isLoading) return <span>Please wait</span>;
|
||||||
|
|
||||||
const renderMainContent = () => {
|
// const renderMainContent = () => {
|
||||||
// if there's no relationship, then don't show messages, show "send request" button
|
// // if there's no relationship, then don't show messages, show "send request" button
|
||||||
if (!convoDetailsResponse?.ourRelationship) {
|
// if (!convoDetailsResponse?.ourRelationship) {
|
||||||
return <button onClick={sendRequest}>Send Request</button>;
|
// return <button onClick={sendRequest}>Send Request</button>;
|
||||||
}
|
// }
|
||||||
|
|
||||||
// if the relationship is pending and I am the receiver, then I should see an accept or deny button
|
// // if the relationship is pending and I am the receiver, then I should see an accept or deny button
|
||||||
if (
|
// if (
|
||||||
convoDetailsResponse.ourRelationship.state ===
|
// convoDetailsResponse.ourRelationship.state ===
|
||||||
RelationshipState.PENDING &&
|
// RelationshipState.PENDING &&
|
||||||
userDetailsData.googleId ===
|
// userDetailsData.googleId ===
|
||||||
convoDetailsResponse.ourRelationship.receiverUserId
|
// convoDetailsResponse.ourRelationship.receiverUserId
|
||||||
) {
|
// ) {
|
||||||
return (
|
// return (
|
||||||
<span>
|
// <span>
|
||||||
please accept this request by clicking here:{" "}
|
// please accept this request by clicking here:{" "}
|
||||||
<button onClick={acceptRequest}>accept</button>
|
// <button onClick={acceptRequest}>accept</button>
|
||||||
</span>
|
// </span>
|
||||||
);
|
// );
|
||||||
}
|
// }
|
||||||
|
|
||||||
// when i sent a request to this person, just tell me that I have to wait
|
// // when i sent a request to this person, just tell me that I have to wait
|
||||||
if (
|
// if (
|
||||||
convoDetailsResponse.ourRelationship.state ===
|
// convoDetailsResponse.ourRelationship.state ===
|
||||||
RelationshipState.PENDING &&
|
// RelationshipState.PENDING &&
|
||||||
userDetailsData.googleId ===
|
// userDetailsData.googleId ===
|
||||||
convoDetailsResponse.ourRelationship.senderUserId
|
// convoDetailsResponse.ourRelationship.senderUserId
|
||||||
) {
|
// ) {
|
||||||
return <span>Waiting on request to be accepted</span>;
|
// return <span>Waiting on request to be accepted</span>;
|
||||||
}
|
// }
|
||||||
|
|
||||||
if (
|
// if (
|
||||||
convoDetailsResponse.ourRelationship.state === RelationshipState.ACTIVE
|
// convoDetailsResponse.ourRelationship.state === RelationshipState.ACTIVE
|
||||||
) {
|
// ) {
|
||||||
return <span>this is all of the content</span>;
|
// return <span>this is all of the content</span>;
|
||||||
}
|
// }
|
||||||
|
|
||||||
if (
|
// if (
|
||||||
convoDetailsResponse.ourRelationship.state === RelationshipState.DENIED
|
// convoDetailsResponse.ourRelationship.state === RelationshipState.DENIED
|
||||||
) {
|
// ) {
|
||||||
return <span>this request was denied</span>;
|
// return <span>this request was denied</span>;
|
||||||
}
|
// }
|
||||||
};
|
// };
|
||||||
|
|
||||||
const startRecording = async () => {
|
// const startRecording = async () => {
|
||||||
socketStartedSpeaking();
|
// socketStartedSpeaking();
|
||||||
setIsRecording(true);
|
// setIsRecording(true);
|
||||||
|
|
||||||
mediaRecorder.start();
|
// mediaRecorder.start();
|
||||||
};
|
// };
|
||||||
|
|
||||||
const stopRecording = () => {
|
// const stopRecording = () => {
|
||||||
socketStopSpeaking();
|
// socketStopSpeaking();
|
||||||
setIsRecording(false);
|
// setIsRecording(false);
|
||||||
|
|
||||||
mediaRecorder.stop();
|
// mediaRecorder.stop();
|
||||||
};
|
// };
|
||||||
|
|
||||||
// emit to room/conversation that someone started speaking
|
// // emit to room/conversation that someone started speaking
|
||||||
const socketStartedSpeaking = () => {
|
// const socketStartedSpeaking = () => {
|
||||||
// send the room name and the update type
|
// // send the room name and the update type
|
||||||
|
|
||||||
// only send if we are in a relationship
|
// // only send if we are in a relationship
|
||||||
if (convoDetailsResponse.ourRelationship._id.toString())
|
// if (convoDetailsResponse.ourRelationship._id.toString())
|
||||||
socket.emit(
|
// socket.emit(
|
||||||
SocketChannels.SEND_STARTED_SPEAKING,
|
// SocketChannels.SEND_STARTED_SPEAKING,
|
||||||
convoDetailsResponse.ourRelationship._id.toString()
|
// convoDetailsResponse.ourRelationship._id.toString()
|
||||||
);
|
// );
|
||||||
};
|
// };
|
||||||
|
|
||||||
const socketStopSpeaking = () => {
|
// const socketStopSpeaking = () => {
|
||||||
// send the room name and the update type
|
// // send the room name and the update type
|
||||||
|
|
||||||
// only send if we are in a relationship
|
// // only send if we are in a relationship
|
||||||
if (convoDetailsResponse.ourRelationship._id.toString())
|
// if (convoDetailsResponse.ourRelationship._id.toString())
|
||||||
socket.emit(
|
// socket.emit(
|
||||||
SocketChannels.SEND_STOPPED_SPEAKING,
|
// SocketChannels.SEND_STOPPED_SPEAKING,
|
||||||
convoDetailsResponse.ourRelationship._id.toString()
|
// convoDetailsResponse.ourRelationship._id.toString()
|
||||||
);
|
// );
|
||||||
};
|
// };
|
||||||
|
|
||||||
// hot keys for closing this window
|
// // hot keys for closing this window
|
||||||
const handleClose = () => {
|
// const handleClose = () => {
|
||||||
setSelectedConvo(null);
|
// setSelectedConvo(null);
|
||||||
};
|
// };
|
||||||
const keyMap: KeyMap = {
|
// const keyMap: KeyMap = {
|
||||||
CLOSE_SELECTED_CONVO: "esc",
|
// CLOSE_SELECTED_CONVO: "esc",
|
||||||
START_RECORDING: {
|
// START_RECORDING: {
|
||||||
name: "START RECORDING",
|
// name: "START RECORDING",
|
||||||
sequence: "`",
|
// sequence: "`",
|
||||||
action: "keydown",
|
// action: "keydown",
|
||||||
},
|
// },
|
||||||
STOP_RECORDING: {
|
// STOP_RECORDING: {
|
||||||
name: "STOP RECORDING",
|
// name: "STOP RECORDING",
|
||||||
sequence: "`",
|
// sequence: "`",
|
||||||
action: "keyup",
|
// action: "keyup",
|
||||||
},
|
// },
|
||||||
};
|
// };
|
||||||
|
|
||||||
const handlers = {
|
// const handlers = {
|
||||||
CLOSE_SELECTED_CONVO: handleClose,
|
// CLOSE_SELECTED_CONVO: handleClose,
|
||||||
START_RECORDING: startRecording,
|
// START_RECORDING: startRecording,
|
||||||
STOP_RECORDING: stopRecording,
|
// STOP_RECORDING: stopRecording,
|
||||||
};
|
// };
|
||||||
|
|
||||||
return (
|
// return (
|
||||||
<>
|
// <>
|
||||||
<GlobalHotKeys handlers={handlers} keyMap={keyMap} />
|
// <GlobalHotKeys handlers={handlers} keyMap={keyMap} />
|
||||||
|
|
||||||
<div className="bg-zinc-800 flex-1 flex flex-col relative">
|
// <div className="bg-zinc-800 flex-1 flex flex-col relative">
|
||||||
{/* close marker */}
|
// {/* close marker */}
|
||||||
<FaWindowClose
|
// <FaWindowClose
|
||||||
onClick={handleClose}
|
// onClick={handleClose}
|
||||||
className="text-zinc-400 text-xl hover:text-zinc-200 hover:scale-110 absolute top-0 right-0 m-1 cursor-pointer"
|
// className="text-zinc-400 text-xl hover:text-zinc-200 hover:scale-110 absolute top-0 right-0 m-1 cursor-pointer"
|
||||||
/>
|
// />
|
||||||
|
|
||||||
{/* top header/profile information */}
|
// {/* top header/profile information */}
|
||||||
<span className="flex flex-row justify-start items-center p-2">
|
// <span className="flex flex-row justify-start items-center p-2">
|
||||||
<img
|
// <img
|
||||||
className="rounded"
|
// className="rounded"
|
||||||
src={convoDetailsResponse.contactUser.picture}
|
// src={convoDetailsResponse.contactUser.picture}
|
||||||
/>
|
// />
|
||||||
<span className="flex flex-col items-start pl-2">
|
// <span className="flex flex-col items-start pl-2">
|
||||||
<span className="flex flex-row space-x-2 items-center">
|
// <span className="flex flex-row space-x-2 items-center">
|
||||||
<span className="text-white font-semibold text-lg">
|
// <span className="text-white font-semibold text-lg">
|
||||||
{convoDetailsResponse.contactUser.name}
|
// {convoDetailsResponse.contactUser.name}
|
||||||
</span>
|
// </span>
|
||||||
<UserStatusText
|
// <UserStatusText
|
||||||
status={convoDetailsResponse.contactUser.status}
|
// status={convoDetailsResponse.contactUser.status}
|
||||||
/>
|
// />
|
||||||
</span>
|
// </span>
|
||||||
|
|
||||||
<span className="text-zinc-300 text-sm">{`joined ${moment(
|
// <span className="text-zinc-300 text-sm">{`joined ${moment(
|
||||||
convoDetailsResponse.contactUser.createdDate
|
// convoDetailsResponse.contactUser.createdDate
|
||||||
).fromNow()}`}</span>
|
// ).fromNow()}`}</span>
|
||||||
</span>
|
// </span>
|
||||||
</span>
|
// </span>
|
||||||
|
|
||||||
{renderMainContent()}
|
// {renderMainContent()}
|
||||||
|
|
||||||
<span className="flex flex-row my-5 items-center justify-center space-x-5">
|
// <span className="flex flex-row my-5 items-center justify-center space-x-5">
|
||||||
<span className="flex flex-row justify-center items-center p-1 rounded shadow-lg h-10 w-10 bg-zinc-500 cursor-pointer">
|
// <span className="flex flex-row justify-center items-center p-1 rounded shadow-lg h-10 w-10 bg-zinc-500 cursor-pointer">
|
||||||
{isRecording ? (
|
// {isRecording ? (
|
||||||
<FaMicrophone className="text-red-600 text-xl animate-pulse" />
|
// <FaMicrophone className="text-red-600 text-xl animate-pulse" />
|
||||||
) : (
|
// ) : (
|
||||||
<FaMicrophone className="text-red-600 text-lg" />
|
// <FaMicrophone className="text-red-600 text-lg" />
|
||||||
)}
|
// )}
|
||||||
</span>
|
// </span>
|
||||||
|
|
||||||
<span className="flex flex-row justify-center items-center p-1 rounded shadow-lg h-10 w-10 bg-zinc-500 cursor-pointer">
|
// <span className="flex flex-row justify-center items-center p-1 rounded shadow-lg h-10 w-10 bg-zinc-500 cursor-pointer">
|
||||||
<FaPlay className="text-blue-600 text-lg" />
|
// <FaPlay className="text-blue-600 text-lg" />
|
||||||
</span>
|
// </span>
|
||||||
</span>
|
// </span>
|
||||||
</div>
|
// </div>
|
||||||
</>
|
// </>
|
||||||
);
|
// );
|
||||||
}
|
// }
|
||||||
|
|||||||
Reference in New Issue
Block a user