Skip to content

Commit

Permalink
Merge pull request #150 from COS301-SE-2024/feat/editor-sessions
Browse files Browse the repository at this point in the history
Feat/editor sessions
  • Loading branch information
KhyalKara authored Sep 28, 2024
2 parents 0457401 + c993b75 commit 6b7ad57
Show file tree
Hide file tree
Showing 43 changed files with 7,273 additions and 4,764 deletions.
84 changes: 84 additions & 0 deletions apps/writeme/app/api/chapter/meta/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/* v8 ignore start */
import { auth } from '../../../../auth';
import { NextResponse } from 'next/server';
import { ZodError } from 'zod';
import { createChapterSchema, editChapterSchema, updateChapterSchema } from '../../../../db/chapter-schema';
import { chapters, stories, versions } from '../../../../db/schema';
import { db } from '../../../../db/db';
import { eq } from 'drizzle-orm';
import { updateStorySchema } from '../../../../db/story-schema';


type UpdadtedChapter = any;


const updateChapter = async (chapter: UpdadtedChapter) => {


const result = await db.update(chapters).set({
cover: chapter.cover,
title: chapter.title,
content: chapter.content,
order: chapter.order,
published: chapter.published,
}).where(eq(chapters.id, chapter.id)).returning({updatedId: chapters.id});

return result[0];
};

// const updateChapterMeta = async (chapter: any)=> {
// const result = await db.update(chapters).set({

// })
// }

export async function PUT(req: Request){
try {
const session = await auth();

if (!session?.user){
return new NextResponse(JSON.stringify({
status: 'fail', message: "You are not logged in",
}), { status : 401})
}

// console.log(await req.json());

const input = editChapterSchema.parse(await req.json());

// : ensure user owns story
// console.log(input);
// @ts-ignore
const chapter = await updateChapter({
...input,
});
// console.log(story);


return NextResponse.json({
chapter: {
id: chapter.updatedId,
},
});
} catch (error: any) {
console.log(error);
if (error instanceof ZodError) {
return NextResponse.json(
{
status: 'error',
message: 'Validation failed',
errors: error.errors,
},
{ status: 400 }
);
}

return NextResponse.json(
{
status: 'error',
message: error.message || 'Internal Server Error',
},
{ status: 500 }
);
}
}
7 changes: 5 additions & 2 deletions apps/writeme/app/api/chapter/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,13 @@ type UpdadtedChapter = any;

const updateChapter = async (chapter: UpdadtedChapter) => {

console.log(chapter)

let updated_chapter = await db.insert(versions).values({
chapterId: chapter.id,
blocks: chapter.blocks
})
console.log(updated_chapter);


const result = await db.update(chapters).set({
Expand All @@ -95,7 +98,7 @@ const updateChapter = async (chapter: UpdadtedChapter) => {

// const updateChapterMeta = async (chapter: any)=> {
// const result = await db.update(chapters).set({

// })
// }

Expand All @@ -111,7 +114,7 @@ export async function PUT(req: Request){

// console.log(await req.json());

const input = editChapterSchema.parse(await req.json());
const input = updateChapterSchema.parse(await req.json());

// : ensure user owns story
// console.log(input);
Expand Down
41 changes: 41 additions & 0 deletions apps/writeme/app/api/get-participant-token/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { auth } from 'apps/writeme/auth';
import { AccessToken } from 'livekit-server-sdk';
import { NextRequest, NextResponse } from 'next/server';

export async function GET(req: NextRequest) {
const room = req.nextUrl.searchParams.get('room');

const session = await auth();

// const username = req.nextUrl.searchParams.get("username");

const username = session?.user?.name || 'Guest User';
if (!room) {
return NextResponse.json(
{ error: 'Missing "room" query parameter' },
{ status: 400 }
);
} else if (!username) {
return NextResponse.json(
{ error: 'Missing "username" query parameter' },
{ status: 400 }
);
}

const apiKey = process.env.LIVEKIT_API_KEY;
const apiSecret = process.env.LIVEKIT_API_SECRET;
const wsUrl = process.env.NEXT_PUBLIC_LIVEKIT_URL;

if (!apiKey || !apiSecret || !wsUrl) {
return NextResponse.json(
{ error: 'Server misconfigured' },
{ status: 500 }
);
}

const at = new AccessToken(apiKey, apiSecret, { identity: username });

at.addGrant({ room, roomJoin: true, canPublish: true, canSubscribe: true });

return NextResponse.json({ token: await at.toJwt() });
}
100 changes: 93 additions & 7 deletions apps/writeme/app/api/session/route.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,101 @@
import { isChapterOwner } from "apps/writeme/services/chapters";
import { auth } from "../../../auth";
import { NextResponse } from "next/server";
import { NextResponse, NextRequest } from "next/server";
import { createLiveEditorSession, isLiveSessionOwner } from "apps/writeme/services/sessions";
import { z } from "zod";
import { db } from "apps/writeme/db/db";
import { liveEditorSessions } from "apps/writeme/db/schema";
import { eq } from "drizzle-orm";


export async function POST(req: NextRequest){
try {
const session = await auth();

if (!session?.user){
return NextResponse.json({
status: 'fail',
message: 'You are not logged in',
}, {
status: 401
})
}

const { chapterId} = await req.json();
const userId = session.user.id || "";

const isOwner = await isChapterOwner(userId, chapterId);

if (!isOwner){
return NextResponse.json({
status: 'fail',
message: 'Only the owner can create a session'
}, {
status: 403
})
}

const newSession = await createLiveEditorSession(chapterId, userId);
return NextResponse.json({
status: 'success',
session: newSession.sessionId
}, {
status: 200
})


} catch (error: any){
return NextResponse.json({

})
}
}

export async function DELETE(req:NextRequest) {
const session = await auth();

if (!session?.user){
return NextResponse.json({
status: 'fail',
message: 'You are not logged in',
}, {
status: 401
})
}

const { sessionId } = z.object({
sessionId: z.string()
}).parse(await req.json());

if (!sessionId){
return NextResponse.json({
status: "failed",
message: "No session Specified"
}, {status: 400})
}


const owner = await isLiveSessionOwner(sessionId);

if (owner){
await db.delete(liveEditorSessions).where(eq(liveEditorSessions.id, sessionId));
return NextResponse.json({
status: "success",
message: "Session has been deleted."
}, {status: 200})
}else {
return NextResponse.json({
status: "failed",
message: "This Session is not owned by you."
}, {status: 401})
}

}

export async function GET(_request: Request) {
const session = await auth();

// if (!session) {
// return new NextResponse(
// JSON.stringify({ status: 'fail', message: 'You are not logged in' }),
// { status: 401 }
// );
// }


return NextResponse.json({
authenticated: !!session,
Expand Down
98 changes: 98 additions & 0 deletions apps/writeme/app/api/session/viewable/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import { isChapterOwner } from "apps/writeme/services/chapters";
import { auth } from "../../../../auth";
import { NextResponse, NextRequest } from "next/server";
import { createLiveEditorSession, createViewableSession, isViewableSessionOwner } from "apps/writeme/services/sessions";
import { z } from "zod";
import { db } from "apps/writeme/db/db";
import { viewableSessions } from "apps/writeme/db/schema";
import { eq } from "drizzle-orm";


export async function POST(req: NextRequest){
try {
const session = await auth();

if (!session?.user){
return NextResponse.json({
status: 'fail',
message: 'You are not logged in',
}, {
status: 401
})
}

const { chapterId} = await req.json();
const userId = session.user.id || "";

const isOwner = await isChapterOwner(userId, chapterId);

if (!isOwner){
return NextResponse.json({
status: 'fail',
message: 'Only the owner can create a session'
}, {
status: 403
})
}

const newSession = await createViewableSession(chapterId, userId);
console.log(newSession)

return NextResponse.json({
status: 'success',
session: newSession.sessionId
}, {
status: 200
})


} catch (error: any){
console.log(error);
return NextResponse.json({

}, {
status: 500
})
}
}

export async function DELETE(req:NextRequest) {
const session = await auth();

if (!session?.user){
return NextResponse.json({
status: 'fail',
message: 'You are not logged in',
}, {
status: 401
})
}

const { sessionId } = z.object({
sessionId: z.string()
}).parse(await req.json());

if (!sessionId){
return NextResponse.json({
status: "failed",
message: "No session Specified"
}, {status: 400})
}


const owner = await isViewableSessionOwner(sessionId);

if (owner){
await db.delete(viewableSessions).where(eq(viewableSessions.id, sessionId));
return NextResponse.json({
status: "success",
message: "Session has been deleted."
}, {status: 200})
}else {
return NextResponse.json({
status: "failed",
message: "This Session is not owned by you."
}, {status: 401})
}

}
Loading

0 comments on commit 6b7ad57

Please sign in to comment.