reset drizzle, get DMs working (partly, usernames aren't resolved)
This commit is contained in:
parent
3a0f096ade
commit
bf679f9ee0
32 changed files with 1150 additions and 2867 deletions
|
|
@ -1,7 +1,59 @@
|
|||
import { fail, json } from '@sveltejs/kit';
|
||||
import { json } from '@sveltejs/kit';
|
||||
import type { RequestHandler } from './$types';
|
||||
import { GroupID, ServerID, UserID } from '$lib';
|
||||
import { db } from '$lib/server/db';
|
||||
import * as table from '$lib/server/db/schema';
|
||||
import { DirectMessageID, GroupID, ServerID } from '$lib';
|
||||
import { eq, or } from 'drizzle-orm';
|
||||
import { _sendToSubscribers } from '../../../../updates/+server';
|
||||
import { and } from 'drizzle-orm';
|
||||
|
||||
interface Message {
|
||||
id: string;
|
||||
authorId: string;
|
||||
content: string;
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
export async function _findDm(member_one: string, member_two: string) {
|
||||
return await db
|
||||
.select()
|
||||
.from(table.directMessage)
|
||||
.where(
|
||||
or(
|
||||
and(
|
||||
eq(table.directMessage.secondMember, member_two),
|
||||
eq(table.directMessage.firstMember, member_one)
|
||||
),
|
||||
and(
|
||||
eq(table.directMessage.firstMember, member_two),
|
||||
eq(table.directMessage.secondMember, member_one)
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
export async function _findDmId(
|
||||
member_one: string,
|
||||
member_two: string
|
||||
): Promise<string | undefined> {
|
||||
return (
|
||||
await db
|
||||
.select({ id: table.directMessage.id })
|
||||
.from(table.directMessage)
|
||||
.where(
|
||||
or(
|
||||
and(
|
||||
eq(table.directMessage.secondMember, member_two),
|
||||
eq(table.directMessage.firstMember, member_one)
|
||||
),
|
||||
and(
|
||||
eq(table.directMessage.firstMember, member_two),
|
||||
eq(table.directMessage.secondMember, member_one)
|
||||
)
|
||||
)
|
||||
)
|
||||
.limit(1)
|
||||
)?.[0]?.id;
|
||||
}
|
||||
export const GET: RequestHandler = async ({ params, locals }) => {
|
||||
if (!locals.user) {
|
||||
return new Response('No authentication', { status: 401 });
|
||||
|
|
@ -11,38 +63,32 @@ export const GET: RequestHandler = async ({ params, locals }) => {
|
|||
if (!grp_srv_dm) {
|
||||
return new Response('Missing group, server, or DM ID.', { status: 400 });
|
||||
}
|
||||
let messages = [];
|
||||
|
||||
let messages: Message[] = [];
|
||||
let type = '';
|
||||
|
||||
if (GroupID.is(grp_srv_dm)) {
|
||||
type = 'group';
|
||||
messages = Array.from({ length: 5 }, (_, i) => ({
|
||||
id: crypto.randomUUID(),
|
||||
authorId: `user_${Math.floor(Math.random() * 10)}`,
|
||||
content: 'group message ' + (i + 1),
|
||||
timestamp: Date.now() - Math.floor(Math.random() * 100000)
|
||||
}));
|
||||
const g = (await db.select().from(table.group).where(eq(table.group.id, grp_srv_dm)))[0];
|
||||
if (!g) return new Response('Group not found.', { status: 404 });
|
||||
|
||||
messages = g.messages ?? [];
|
||||
} else if (ServerID.is(grp_srv_dm)) {
|
||||
type = 'server';
|
||||
if (!channelId) return new Response('Missing channel ID.', { status: 400 });
|
||||
const c = (await db.select().from(table.channel).where(eq(table.channel.id, channelId)))[0];
|
||||
if (!c) return new Response('Channel not found.', { status: 404 });
|
||||
|
||||
if (!channelId) {
|
||||
return new Response('Missing channel ID.', { status: 400 });
|
||||
}
|
||||
|
||||
messages = Array.from({ length: 5 }, (_, i) => ({
|
||||
id: crypto.randomUUID(),
|
||||
authorId: `user_${Math.floor(Math.random() * 10)}`,
|
||||
content: 'server message ' + (i + 1),
|
||||
timestamp: Date.now() - Math.floor(Math.random() * 100000)
|
||||
}));
|
||||
} else if (UserID.is(grp_srv_dm)) {
|
||||
messages = c.messages;
|
||||
} else if (DirectMessageID.is(grp_srv_dm)) {
|
||||
type = 'dms';
|
||||
messages = Array.from({ length: 5 }, (_, i) => ({
|
||||
id: crypto.randomUUID(),
|
||||
authorId: Math.random() > 0.5 ? locals.user.id : grp_srv_dm,
|
||||
content: 'dm message ' + (i + 1),
|
||||
timestamp: Date.now() - Math.floor(Math.random() * 100000)
|
||||
}));
|
||||
const dm = (
|
||||
await db.select().from(table.directMessage).where(eq(table.directMessage.id, grp_srv_dm))
|
||||
)[0];
|
||||
|
||||
if (!dm) return new Response('DM not found.', { status: 404 });
|
||||
|
||||
messages = dm.messages;
|
||||
}
|
||||
|
||||
return json({
|
||||
|
|
@ -51,3 +97,67 @@ export const GET: RequestHandler = async ({ params, locals }) => {
|
|||
messages
|
||||
});
|
||||
};
|
||||
|
||||
export const POST: RequestHandler = async ({ params, request, locals }) => {
|
||||
if (!locals.user) {
|
||||
return new Response('Unauthorized', { status: 401 });
|
||||
}
|
||||
|
||||
let { grp_srv_dm, channelId } = params;
|
||||
if (!grp_srv_dm) return new Response('Missing Group/Server/DM id.', { status: 400 });
|
||||
const data = await request.json();
|
||||
const { content } = data;
|
||||
|
||||
if (!content) return new Response('Missing message content.', { status: 400 });
|
||||
|
||||
let messages: Message[] = [];
|
||||
let type = '';
|
||||
|
||||
const message = {
|
||||
id: crypto.randomUUID(),
|
||||
authorId: locals.user.id,
|
||||
content,
|
||||
timestamp: Date.now()
|
||||
};
|
||||
|
||||
if (GroupID.is(grp_srv_dm)) {
|
||||
type = 'group';
|
||||
const g = (await db.select().from(table.group).where(eq(table.group.id, grp_srv_dm)))[0];
|
||||
if (!g) return new Response('Group not found.', { status: 404 });
|
||||
messages = g.messages ?? [];
|
||||
|
||||
messages.push(message);
|
||||
|
||||
await db.update(table.group).set({ messages }).where(eq(table.group.id, grp_srv_dm));
|
||||
} else if (ServerID.is(grp_srv_dm)) {
|
||||
type = 'server';
|
||||
if (!channelId) return new Response('Missing channel ID.', { status: 400 });
|
||||
const c = (await db.select().from(table.channel).where(eq(table.channel.id, channelId)))[0];
|
||||
if (!c) return new Response('Channel not found.', { status: 404 });
|
||||
messages = c.messages ?? [];
|
||||
|
||||
messages.push(message);
|
||||
|
||||
await db.update(table.channel).set({ messages }).where(eq(table.channel.id, channelId));
|
||||
} else if (DirectMessageID.is(grp_srv_dm)) {
|
||||
type = 'dms';
|
||||
const dm = (
|
||||
await db.select().from(table.directMessage).where(eq(table.directMessage.id, grp_srv_dm))
|
||||
)[0];
|
||||
|
||||
if (!dm) return new Response('DM not found.', { status: 404 });
|
||||
|
||||
messages = dm.messages ?? [];
|
||||
|
||||
messages.push(message);
|
||||
|
||||
await db.update(table.directMessage).set({ messages }).where(eq(table.directMessage.id, dm.id));
|
||||
|
||||
_sendToSubscribers(dm.id, { type: 'message', id: dm.id, message });
|
||||
return json({ type, id: dm.id, messages });
|
||||
}
|
||||
|
||||
_sendToSubscribers(grp_srv_dm, { type: 'message', id: grp_srv_dm, message });
|
||||
|
||||
return json({ type, id: grp_srv_dm, messages });
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,17 +1,18 @@
|
|||
import { Status } from '$lib';
|
||||
import { kvStore } from '$lib/server/db/index.js';
|
||||
import { json } from '@sveltejs/kit';
|
||||
|
||||
interface SubscribedTo {
|
||||
subscribed: string[];
|
||||
subscribed: string[]; // any ID (including channels, dms, et cetera can be added in here, to send SSE data to any group of users)
|
||||
userId: string;
|
||||
controller: ReadableStreamDefaultController;
|
||||
}
|
||||
|
||||
export const _clients = new Map<string, SubscribedTo>();
|
||||
|
||||
export function _sendToSubscribers(userId: string, payload: unknown) {
|
||||
export function _sendToSubscribers(id: string, payload: unknown) {
|
||||
for (const [key, client] of _clients) {
|
||||
if (client.subscribed.includes(userId)) {
|
||||
if (client.subscribed.includes(id)) {
|
||||
try {
|
||||
client.controller.enqueue(`data: ${JSON.stringify(payload)}\n\n`);
|
||||
} catch {
|
||||
|
|
@ -30,7 +31,7 @@ export function _isUserConnected(userId: string): boolean {
|
|||
|
||||
export async function GET({ locals, request }) {
|
||||
if (!locals.user) {
|
||||
return new Response('No authentication', { status: 401 });
|
||||
return json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
const userId = locals.user.id;
|
||||
|
|
@ -38,14 +39,14 @@ export async function GET({ locals, request }) {
|
|||
const subscribed = locals.user.friends.map((f) => f.id);
|
||||
const overwrite = locals.user.statusOverwrite;
|
||||
|
||||
const reqId = crypto.randomUUID();
|
||||
const sessionId = crypto.randomUUID();
|
||||
|
||||
const stream = new ReadableStream({
|
||||
start(controller) {
|
||||
_clients.set(reqId, { subscribed, userId, controller });
|
||||
_clients.set(sessionId, { subscribed, userId, controller });
|
||||
console.log(`SSE Client opened. total: ${_clients.size}`);
|
||||
|
||||
controller.enqueue(`data: ${JSON.stringify({ type: 'connected' })}\n\n`);
|
||||
controller.enqueue(`data: ${JSON.stringify({ type: 'connected', sessionId })}\n\n`);
|
||||
|
||||
if (overwrite === Status.DND) {
|
||||
kvStore.set(`user-${userId}-state`, Status.DND);
|
||||
|
|
@ -56,7 +57,7 @@ export async function GET({ locals, request }) {
|
|||
}
|
||||
|
||||
request.signal.addEventListener('abort', () => {
|
||||
_clients.delete(reqId);
|
||||
_clients.delete(sessionId);
|
||||
console.log(`SSE Client aborted. total: ${_clients.size}`);
|
||||
|
||||
if (_isUserConnected(userId)) return;
|
||||
|
|
|
|||
111
src/routes/api/updates/[sessionId]/+server.ts
Normal file
111
src/routes/api/updates/[sessionId]/+server.ts
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
import { json } from '@sveltejs/kit';
|
||||
import type { RequestHandler } from './$types';
|
||||
import { _clients } from '../+server';
|
||||
import { DirectMessageID } from '$lib';
|
||||
import { db } from '$lib/server/db';
|
||||
import * as table from '$lib/server/db/schema';
|
||||
import { or } from 'drizzle-orm';
|
||||
import { eq } from 'drizzle-orm';
|
||||
|
||||
export const POST: RequestHandler = async ({ params, request, locals }) => {
|
||||
if (!locals.user) {
|
||||
return json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
const { sessionId } = params;
|
||||
if (!sessionId) {
|
||||
return json({ error: 'Missing sessionId' }, { status: 400 });
|
||||
}
|
||||
|
||||
const client = _clients.get(sessionId);
|
||||
if (!client) {
|
||||
return json({ error: 'Client not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
if (client.userId !== locals.user.id) {
|
||||
return json({ error: 'Unauthorized sessionID access' }, { status: 401 });
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { subscribeTo } = body;
|
||||
|
||||
if (typeof subscribeTo !== 'string' || !subscribeTo.trim()) {
|
||||
return json({ error: 'Invalid subscribeTo value' }, { status: 400 });
|
||||
}
|
||||
|
||||
let isValidDmid = false;
|
||||
|
||||
if (DirectMessageID.is(subscribeTo)) {
|
||||
const find = await db
|
||||
.select()
|
||||
.from(table.directMessage)
|
||||
.where(
|
||||
or(
|
||||
eq(table.directMessage.firstMember, locals.user.id),
|
||||
eq(table.directMessage.secondMember, locals.user.id)
|
||||
)
|
||||
);
|
||||
|
||||
if (find?.length != 0) {
|
||||
isValidDmid = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
!(
|
||||
isValidDmid ||
|
||||
locals.user.groups.find((z) => z.id === subscribeTo) ||
|
||||
locals.user.servers.find((z) => z.id === subscribeTo)
|
||||
)
|
||||
) {
|
||||
return json({ error: 'Invalid subscription' }, { status: 401 });
|
||||
}
|
||||
|
||||
if (!client.subscribed.includes(subscribeTo)) {
|
||||
client.subscribed.push(subscribeTo);
|
||||
}
|
||||
|
||||
return json({
|
||||
message: `Added ${subscribeTo} to client subscriptions.`,
|
||||
subscribed: client.subscribed
|
||||
});
|
||||
};
|
||||
|
||||
export const DELETE: RequestHandler = async ({ params, request, locals }) => {
|
||||
if (!locals.user) {
|
||||
return json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
const { sessionId } = params;
|
||||
if (!sessionId) {
|
||||
return json({ error: 'Missing sessionId' }, { status: 400 });
|
||||
}
|
||||
|
||||
const client = _clients.get(sessionId);
|
||||
if (!client) {
|
||||
return json({ error: 'Client not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
if (client.userId !== locals.user.id) {
|
||||
return json({ error: 'Unauthorized sessionID access' }, { status: 401 });
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { subscribeTo } = body;
|
||||
|
||||
if (typeof subscribeTo !== 'string' || !subscribeTo.trim()) {
|
||||
return json({ error: 'Invalid subscribeTo value' }, { status: 400 });
|
||||
}
|
||||
|
||||
const index = client.subscribed.indexOf(subscribeTo);
|
||||
if (index !== -1) {
|
||||
client.subscribed.splice(index, 1);
|
||||
} else {
|
||||
return json({ error: 'Subscription not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
return json({
|
||||
message: `Removed ${subscribeTo} from client subscriptions.`,
|
||||
subscribed: client.subscribed
|
||||
});
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue