throwing away bunch of garbage
This commit is contained in:
@@ -1,16 +1,9 @@
|
||||
import express, { Application, Request, Response } from 'express';
|
||||
|
||||
import GetAllSocketClients from '@nirvana/core/sockets/getAllActiveSocketClients';
|
||||
import InitializeWs from './services/socket.service';
|
||||
import { NextFunction } from 'express';
|
||||
import NirvanaResponse from '@nirvana/core/responses/nirvanaResponse';
|
||||
import ReceiveSignal from '../core/sockets/receiveSignal';
|
||||
import SendSignal from '@nirvana/core/sockets/sendSignal';
|
||||
import SocketChannels from '@nirvana/core/sockets/channels';
|
||||
import { UserService } from './services/user.service';
|
||||
import { UserStatus } from '@nirvana/core/models';
|
||||
import cors from 'cors';
|
||||
import getLineRoutes from './routes/line';
|
||||
import getSearchRoutes from './routes/search';
|
||||
import getUserRoutes from './routes/user';
|
||||
import morgan from 'morgan';
|
||||
@@ -41,7 +34,7 @@ app.use('/api/status', (req: Request, res: Response) => {
|
||||
|
||||
app.use('/api/user', getUserRoutes());
|
||||
app.use('/api/search', getSearchRoutes());
|
||||
app.use('/api/lines', getLineRoutes());
|
||||
// app.use('/api/conversations', getConversationRoutes());
|
||||
|
||||
const PORT = process.env.PORT || 8080;
|
||||
const server = app.listen(PORT, () =>
|
||||
|
||||
@@ -1,216 +0,0 @@
|
||||
import { JwtClaims, authCheck } from '../middleware/auth';
|
||||
import { Line, LineMember, LineMemberState } from '@nirvana/core/models/line.model';
|
||||
import express, { Application, Request, Response } from 'express';
|
||||
|
||||
import Content from '@nirvana/core/models/content.model';
|
||||
import CreateLineRequest from '@nirvana/core/requests/createLine.request';
|
||||
import GetConversationDetailsResponse from '@nirvana/core/responses/getConversationDetails.response';
|
||||
import GetDmConversationByOtherUserIdResponse from '@nirvana/core/responses/getDmConversationByOtherUserId.response';
|
||||
import GetUserLinesResponse from '@nirvana/core/responses/getUserLines.response';
|
||||
import { LineService } from '../services/line.service';
|
||||
import MasterLineData from '@nirvana/core/models/masterLineData.model';
|
||||
import NirvanaResponse from '@nirvana/core/responses/nirvanaResponse';
|
||||
import { ObjectId } from 'mongodb';
|
||||
import Relationship from '@nirvana/core/models/relationship.model';
|
||||
import { User } from '@nirvana/core/models/user.model';
|
||||
import { UserService } from '../services/user.service';
|
||||
import { collections } from '../services/database.service';
|
||||
import UpdateLineMemberState from '@nirvana/core/requests/updateLineMemberState.request';
|
||||
|
||||
export default function getLineRoutes() {
|
||||
const router = express.Router();
|
||||
|
||||
router.use(express.json());
|
||||
|
||||
// get data for a one on one conversation
|
||||
// router.get("/:otherUserGoogleUserId", authCheck, getConversationDetails);
|
||||
|
||||
// create a line
|
||||
router.post('/', authCheck, createLine);
|
||||
|
||||
// get all of user's lines
|
||||
router.get('/', authCheck, getUserLines);
|
||||
|
||||
// toggle tune into a line
|
||||
router.post('/:lineId/state', authCheck, updateLineMemberState);
|
||||
|
||||
// get conversation between user and other user
|
||||
router.get('/dm/:otherUserId', authCheck, getDmByOtherUserId);
|
||||
|
||||
return router;
|
||||
}
|
||||
|
||||
async function getDmByOtherUserId(req: Request, res: Response) {
|
||||
try {
|
||||
const { otherUserId } = req.params;
|
||||
const userInfo = res.locals.userInfo as JwtClaims;
|
||||
|
||||
console.log(otherUserId);
|
||||
|
||||
// check db for lines between me and this other person
|
||||
// if there is one, then return it with 200 status
|
||||
// else return it with custom status that frontend will read
|
||||
|
||||
res.status(200).json();
|
||||
return;
|
||||
|
||||
res.status(205).json('no such conversation between you two');
|
||||
} catch (error) {
|
||||
res.status(500).json(error);
|
||||
}
|
||||
}
|
||||
|
||||
async function createLine(req: Request, res: Response) {
|
||||
try {
|
||||
const reqObj: CreateLineRequest = req.body as CreateLineRequest;
|
||||
console.log(req.body);
|
||||
|
||||
if (!reqObj?.otherMemberIds.length) {
|
||||
res.status(400).json('must provide member Ids');
|
||||
return;
|
||||
}
|
||||
|
||||
const userInfo = res.locals.userInfo as JwtClaims;
|
||||
|
||||
const newLine = new Line(
|
||||
new ObjectId(userInfo.userId),
|
||||
reqObj.lineName ?? undefined,
|
||||
new Date(),
|
||||
new Date(),
|
||||
new ObjectId(),
|
||||
);
|
||||
|
||||
// TODO: validate that users exists before creating line members
|
||||
const lineMembers: LineMember[] =
|
||||
reqObj.otherMemberIds.map((memId) => {
|
||||
const newLineMember = new LineMember(
|
||||
newLine._id!,
|
||||
new ObjectId(memId),
|
||||
LineMemberState.INBOX,
|
||||
);
|
||||
|
||||
return newLineMember;
|
||||
}) ?? [];
|
||||
|
||||
lineMembers.push(
|
||||
new LineMember(newLine._id!, new ObjectId(userInfo.userId), LineMemberState.INBOX),
|
||||
);
|
||||
|
||||
const transactionResult = await LineService.createLine(newLine, lineMembers);
|
||||
|
||||
transactionResult
|
||||
? res.status(200).json(new NirvanaResponse(newLine))
|
||||
: res.status(400).json(new NirvanaResponse(undefined, new Error('unable to create line')));
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
res.status(500).json(error);
|
||||
}
|
||||
}
|
||||
|
||||
async function updateLineMemberState(req: Request, res: Response) {
|
||||
try {
|
||||
const userInfo = res.locals.userInfo as JwtClaims;
|
||||
const { lineId } = req.params;
|
||||
const request = req.body as UpdateLineMemberState;
|
||||
|
||||
// TODO: validation to check if user is actually a member of the line
|
||||
|
||||
const result = await LineService.updateLineMemberState(
|
||||
lineId,
|
||||
userInfo.userId,
|
||||
request.newState,
|
||||
);
|
||||
|
||||
return result?.ok
|
||||
? res.status(200).json(new NirvanaResponse("successfully updated line member's state"))
|
||||
: res
|
||||
.status(400)
|
||||
.json(new NirvanaResponse(undefined, new Error('not updated...something went wrong')));
|
||||
} catch (error) {
|
||||
res.status(500).json(new NirvanaResponse(undefined, error as Error));
|
||||
}
|
||||
}
|
||||
|
||||
async function getUserLines(req: Request, res: Response) {
|
||||
try {
|
||||
const userInfo = res.locals.userInfo as JwtClaims;
|
||||
|
||||
// get all of user's lineMember entries
|
||||
const userLineMembers = await LineService.getLineMembersByUserId(userInfo.userId);
|
||||
|
||||
if (!userLineMembers?.length) {
|
||||
const resObj = new GetUserLinesResponse([]);
|
||||
|
||||
res.json(new NirvanaResponse(resObj, undefined, 'this user is not in any lines'));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const lineIds = userLineMembers?.map((lineMember) => lineMember.lineId) ?? [];
|
||||
|
||||
// this will include the current user lineMember association to the line
|
||||
const allLineMembers = await LineService.getLineMembersInLines(lineIds);
|
||||
|
||||
const allLinesUsersIds: ObjectId[] = [];
|
||||
allLineMembers?.map((currentLineMember) => {
|
||||
if (currentLineMember?.userId) allLinesUsersIds.push(currentLineMember.userId);
|
||||
}) ?? [];
|
||||
|
||||
// get all users relevant here
|
||||
const allRelevantUsers = await UserService.getUsersByIds(allLinesUsersIds);
|
||||
|
||||
// get all lines from the list of relevant lines
|
||||
const lines = (await LineService.getLinesByIds(lineIds)) ?? [];
|
||||
|
||||
const masterLines: MasterLineData[] = [];
|
||||
|
||||
// TODO: get the latest audio blocks for this line...maybe like today and yesterday or by block count
|
||||
|
||||
lines.map((currentLine) => {
|
||||
let associatedLineMembersForLine: LineMember[] = [];
|
||||
|
||||
// get all of the line members for this Line
|
||||
// make sure that we don't add line member if it's the current user
|
||||
allLineMembers?.map((lineMember) => {
|
||||
if (currentLine._id) {
|
||||
if (lineMember.lineId.equals(currentLine._id))
|
||||
associatedLineMembersForLine.push(lineMember);
|
||||
}
|
||||
}) ?? [];
|
||||
|
||||
// get the user lineMember assoc out of the list of the lineMembers for this line
|
||||
const userLineMember = associatedLineMembersForLine?.find(
|
||||
(currentLineMemberForLine) =>
|
||||
currentLineMemberForLine.userId.toString() === userInfo.userId,
|
||||
);
|
||||
|
||||
if (userLineMember) {
|
||||
// take out the current user from the "other" line members list now
|
||||
|
||||
associatedLineMembersForLine = associatedLineMembersForLine.filter(
|
||||
(currentLineMember) => currentLineMember.userId.toString() !== userInfo.userId,
|
||||
);
|
||||
|
||||
// get the user objects for all of the other members
|
||||
const otherUsers: User[] = [];
|
||||
associatedLineMembersForLine.forEach((currentLineMember) => {
|
||||
const foundUserObject = allRelevantUsers?.find((currentUser) =>
|
||||
currentUser._id?.equals(currentLineMember.userId),
|
||||
);
|
||||
|
||||
if (foundUserObject) otherUsers.push(foundUserObject);
|
||||
});
|
||||
|
||||
masterLines.push(
|
||||
new MasterLineData(currentLine, userLineMember, associatedLineMembersForLine, otherUsers),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
const resObj = new GetUserLinesResponse(masterLines);
|
||||
|
||||
res.json(new NirvanaResponse<GetUserLinesResponse>(resObj));
|
||||
} catch (error) {
|
||||
res.status(500).json(error);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { GoogleUserInfo, User } from '@nirvana/core/models';
|
||||
import { JwtClaims, authCheck } from '../middleware/auth';
|
||||
import User, { GoogleUserInfo, UserStatus } from '@nirvana/core/models/user.model';
|
||||
import express, { Application, Request, Response } from 'express';
|
||||
|
||||
import LoginResponse from '../../core/responses/login.response';
|
||||
@@ -8,7 +8,6 @@ import { ObjectID } from 'bson';
|
||||
import { ObjectId } from 'mongodb';
|
||||
import UserDetailsResponse from '../../core/responses/userDetails.response';
|
||||
import { UserService } from '../services/user.service';
|
||||
import { UserStatus } from '../../core/models/user.model';
|
||||
import { collections } from '../services/database.service';
|
||||
import environmentVariables from '../config/config';
|
||||
|
||||
|
||||
@@ -1,148 +0,0 @@
|
||||
import {
|
||||
Line,
|
||||
LineMember,
|
||||
LineMemberState,
|
||||
} from "@nirvana/core/models/line.model";
|
||||
import { client, collections } from "./database.service";
|
||||
|
||||
import NirvanaResponse from "@nirvana/core/responses/nirvanaResponse";
|
||||
import { ObjectId } from "mongodb";
|
||||
|
||||
export class LineService {
|
||||
static async getLineByOtherUserId(otherUserId: ObjectId) {
|
||||
// get all of the conversations for this user that have exactly two conversation members
|
||||
// get all of the conversationMembers for this user
|
||||
// get all of the conversations for this user
|
||||
// get all of the conversations
|
||||
// const query = { googleId: userId };
|
||||
// const res = await collections.users?.findOne(query);
|
||||
// // exists
|
||||
// if (res?._id) {
|
||||
// return res as User;
|
||||
// }
|
||||
// return null;
|
||||
}
|
||||
|
||||
static async getLinesByIds(convoIds: ObjectId[]) {
|
||||
const query = { _id: { $in: convoIds } };
|
||||
|
||||
const convosRes = await collections.lines?.find(query).toArray();
|
||||
|
||||
// exists
|
||||
if (convosRes?.length) {
|
||||
return convosRes as Line[];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
static async getLineMembersByUserId(userId: string) {
|
||||
const query = { userId: new ObjectId(userId) };
|
||||
|
||||
const convoMembersRes = await collections.lineMembers
|
||||
?.find(query)
|
||||
.toArray();
|
||||
|
||||
// exists
|
||||
if (convoMembersRes?.length) {
|
||||
return convoMembersRes as LineMember[];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Get all of the members associated to the given list of lines */
|
||||
static async getLineMembersInLines(lineIds: ObjectId[]) {
|
||||
const query = { lineId: { $in: lineIds } };
|
||||
|
||||
const lineMembersRes = await collections.lineMembers?.find(query).toArray();
|
||||
|
||||
// exists
|
||||
if (lineMembersRes?.length) {
|
||||
return lineMembersRes as LineMember[];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
static async createLine(line: Line, lineMembers: LineMember[]) {
|
||||
const session = client.startSession();
|
||||
try {
|
||||
const transactionResults = await session.withTransaction(async () => {
|
||||
// todo: check if convoMembers userId's actually exist
|
||||
|
||||
const insertLineRes = await collections.lines?.insertOne(line);
|
||||
if (!insertLineRes?.insertedId) {
|
||||
await session.abortTransaction();
|
||||
console.error("failed to create line");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const insertConvoMembersRes = await collections.lineMembers?.insertMany(
|
||||
lineMembers
|
||||
);
|
||||
if (!insertConvoMembersRes?.insertedCount) {
|
||||
await session.abortTransaction();
|
||||
console.error("failed to create line members");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
console.log("success");
|
||||
return insertConvoMembersRes;
|
||||
});
|
||||
|
||||
console.log(transactionResults);
|
||||
|
||||
return "success";
|
||||
|
||||
// if (transactionResults) {
|
||||
// console.log("The convo was successfully created.");
|
||||
// return transactionResults;
|
||||
// } else {
|
||||
// console.log("The convo was intentionally aborted.");
|
||||
// return null;
|
||||
// }
|
||||
} catch (e) {
|
||||
console.log(
|
||||
"The transaction was aborted due to an unexpected error: " + e
|
||||
);
|
||||
} finally {
|
||||
await session.endSession();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
static async updateLineMemberState(
|
||||
lineId: string,
|
||||
userId: string,
|
||||
newState: LineMemberState
|
||||
) {
|
||||
const query = {
|
||||
lineId: new ObjectId(lineId),
|
||||
userId: new ObjectId(userId),
|
||||
};
|
||||
const updateSet = { $set: { state: newState, lastVisitDate: new Date() } };
|
||||
|
||||
const updateRes = await collections.lineMembers?.findOneAndUpdate(
|
||||
query,
|
||||
updateSet
|
||||
);
|
||||
|
||||
return updateRes;
|
||||
}
|
||||
|
||||
static async updateLineMemberVisitDate(lineId: string, userId: string) {
|
||||
const query = { lineId, userId: new ObjectId(userId) };
|
||||
const updateSet = { $set: { lastVisitDate: new Date() } };
|
||||
|
||||
const updateRes = await collections.lineMembers?.findOneAndUpdate(
|
||||
query,
|
||||
updateSet
|
||||
);
|
||||
|
||||
return updateRes;
|
||||
}
|
||||
}
|
||||
@@ -18,15 +18,7 @@ import {
|
||||
UserStoppedBroadcastingResponse,
|
||||
} from '@nirvana/core/sockets/channels';
|
||||
|
||||
import GetAllSocketClients from '@nirvana/core/sockets/getAllActiveSocketClients';
|
||||
import { JwtClaims } from '../middleware/auth';
|
||||
import { LineMemberState } from '@nirvana/core/models/line.model';
|
||||
import { LineService } from './line.service';
|
||||
import ReceiveSignal from '@nirvana/core/sockets/receiveSignal';
|
||||
import SendSignal from '@nirvana/core/sockets/sendSignal';
|
||||
import { UserService } from './user.service';
|
||||
import { UserStatus } from '@nirvana/core/models/user.model';
|
||||
import { client } from './database.service';
|
||||
import environmentVariables from '../config/config';
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { GoogleUserInfo, User } from "@nirvana/core/models";
|
||||
import User, { GoogleUserInfo } from '@nirvana/core/models/user.model';
|
||||
|
||||
import { ObjectId } from "mongodb";
|
||||
import { UserStatus } from "../../core/models/user.model";
|
||||
import axios from "axios";
|
||||
import { collections } from "./database.service";
|
||||
import { ObjectId } from 'mongodb';
|
||||
import { UserStatus } from '../../core/models/user.model';
|
||||
import axios from 'axios';
|
||||
import { collections } from './database.service';
|
||||
|
||||
export class UserService {
|
||||
static async getUserById(userId: string) {
|
||||
@@ -62,11 +62,11 @@ export class UserService {
|
||||
// based on index defined in Mongo atlas
|
||||
const query = {
|
||||
$search: {
|
||||
index: "basic user search",
|
||||
index: 'basic user search',
|
||||
text: {
|
||||
query: searchQuery,
|
||||
path: {
|
||||
wildcard: "*",
|
||||
wildcard: '*',
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -95,13 +95,9 @@ export class UserService {
|
||||
return null;
|
||||
}
|
||||
|
||||
static async getGoogleUserInfoWithAccessToken(
|
||||
accessToken: string
|
||||
): Promise<GoogleUserInfo> {
|
||||
static async getGoogleUserInfoWithAccessToken(accessToken: string): Promise<GoogleUserInfo> {
|
||||
return (
|
||||
await axios.get(
|
||||
`https://www.googleapis.com/oauth2/v1/userinfo?access_token=${accessToken}`
|
||||
)
|
||||
await axios.get(`https://www.googleapis.com/oauth2/v1/userinfo?access_token=${accessToken}`)
|
||||
).data;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user