Skip to content

Commit

Permalink
fix a bunch of stuff regarding channels, move models
Browse files Browse the repository at this point in the history
  • Loading branch information
targoninc-alex committed May 28, 2024
1 parent 07d57d0 commit 1f25f73
Show file tree
Hide file tree
Showing 6 changed files with 110 additions and 20 deletions.
22 changes: 17 additions & 5 deletions src/features/database/mariaDbDatabase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,17 +161,25 @@ WHERE ur.userId = ?`, [userId]);
throw new Error("Could not create channel");
}

await this.query("INSERT INTO venel.channelMembers (channelId, userId) VALUES (?, ?), (?, ?)", [
channelId, id,
channelId, targetUserId
]);
if (id !== targetUserId) {
await this.query("INSERT INTO venel.channelMembers (channelId, userId) VALUES (?, ?), (?, ?)", [
channelId, id,
channelId, targetUserId
]);
} else {
await this.query("INSERT INTO venel.channelMembers (channelId, userId) VALUES (?, ?)", [channelId, id]);
}
return channelId;
}

async getChannelMembers(channelId: Id): Promise<ChannelMember[] | null> {
return await this.query("SELECT * FROM venel.channelMembers WHERE channelId = ?", [channelId]);
}

async getChannelMembersAsUsers(channelId: Id): Promise<User[] | null> {
return await this.query("SELECT u.id, u.updatedAt, u.createdAt, u.username, u.displayname, u.description FROM venel.users u INNER JOIN venel.channelMembers cm ON u.id = cm.userId WHERE cm.channelId = ?", [channelId]);
}

async getMessageById(messageId: Id): Promise<Message | null> {
const rows = await this.query("SELECT * FROM venel.messages WHERE id = ?", [messageId]);
return rows ? rows[0] : null;
Expand All @@ -189,8 +197,12 @@ WHERE ur.userId = ?`, [userId]);
return await this.query("SELECT c.id, c.type, c.name, c.createdAt, c.updatedAt FROM venel.channels c INNER JOIN venel.channelMembers cm ON c.id = cm.channelId WHERE cm.userId = ?", [id]);
}

async getLastMessageForChannel(channelId: Id) {
async getLastMessageForChannel(channelId: Id): Promise<Message | null> {
const rows = await this.query("SELECT * FROM venel.messages WHERE channelId = ? ORDER BY createdAt DESC LIMIT 1", [channelId]);
return rows ? rows[0] : null;
}

async searchUsers(query: string): Promise<User[] | null> {
return await this.query("SELECT * FROM venel.users WHERE username LIKE ? OR displayname LIKE ?", [`%${query}%`, `%${query}%`]);
}
}
48 changes: 33 additions & 15 deletions src/features/messaging/endpoints.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import {MariaDbDatabase} from "../database/mariaDbDatabase";
import {Request, Response} from "express";
import {Channel, ChannelMember, Message, User} from "../database/models";
import {ChannelMember, User} from "../database/models";
import {CLI} from "../../tooling/CLI";
import {PermissionsList} from "../../enums/permissionsList";
import {SafeUser, safeUser} from "../authentication/actions";
import {safeUser} from "../authentication/actions";
import {ReceivableMessage} from "../../models/receivableMessage";
import {UiChannel} from "../../models/uiChannel";

export class MessagingEndpoints {
static async checkChannelAccess(db: MariaDbDatabase, user: User, channelId: number) {
Expand Down Expand Up @@ -48,7 +50,11 @@ export class MessagingEndpoints {
return;
}
await db.createMessage(channelId, user.id, text);
const message = await db.getLastMessageForChannel(channelId);
const message = await db.getLastMessageForChannel(channelId) as ReceivableMessage | null;
if (!message) {
res.status(500).send("Message not found");
return;
}
message.sender = safeUser(user);
CLI.success(`Message sent to channel ${channelId} by user ${user.id}.`);
res.json(message);
Expand Down Expand Up @@ -202,29 +208,41 @@ export class MessagingEndpoints {
}
for (const channel of channels as UiChannel[]) {
if (channel.type === "dm") {
const members = await db.getChannelMembers(channel.id);
const previousName = channel.name;
const members = await db.getChannelMembersAsUsers(channel.id);
if (members) {
for (const member of members) {
if (member.userId !== user.id) {
const targetUser = await db.getUserById(member.userId);
if (targetUser) {
channel.name = targetUser.displayname ?? targetUser.username;
}
if (member.id !== user.id) {
channel.name = member.displayname ?? member.username;
}
}
if (channel.name === previousName) {
channel.name = "Note to self";
}
channel.members = members;
}
}
}
res.json(channels);
}
}
}

export interface ReceivableMessage extends Message {
sender: SafeUser;
static searchUsers(db: MariaDbDatabase) {
return async (req: Request, res: Response) => {
const query = req.query.query as string;
if (!query) {
res.status(400).send("Query is required");
return;
}

const users = await db.searchUsers(query);
if (!users) {
res.json([]);
return;
}
res.json(users.map(u => safeUser(u)));
}

}
}

export interface UiChannel extends Channel {
members: ChannelMember[];
}
4 changes: 4 additions & 0 deletions src/features/messagingFeature.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ export class MessagingFeature {
app.delete(`${mPrefix}/deleteMessage`, AuthActions.checkAuthenticated, MessagingEndpoints.deleteMessage(db));
app.patch(`${mPrefix}/editMessage`, AuthActions.checkAuthenticated, MessagingEndpoints.editMessage(db));

// Users
const uPrefix = "/api/users";
app.get(`${uPrefix}/search`, AuthActions.checkAuthenticated, MessagingEndpoints.searchUsers(db));

// Channels
const cPrefix = "/api/channels";
app.post(`${cPrefix}/createDirect`, AuthActions.checkAuthenticated, MessagingEndpoints.createChannelDm(db));
Expand Down
6 changes: 6 additions & 0 deletions src/models/receivableMessage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import {Message} from "../features/database/models";
import {SafeUser} from "../features/authentication/actions";

export interface ReceivableMessage extends Message {
sender: SafeUser;
}
6 changes: 6 additions & 0 deletions src/models/uiChannel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import {Channel} from "../features/database/models";
import {SafeUser} from "../features/authentication/actions";

export interface UiChannel extends Channel {
members: SafeUser[];
}
44 changes: 44 additions & 0 deletions src/swagger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1038,6 +1038,50 @@ export const swaggerOptions = {
}
}
},
"/api/users/search": {
get: {
security: [
{
cookieAuth: []
}
],
summary: "Search for users",
tags: [
"User Management"
],
description: "Search for users",
parameters: [
{
name: "query",
in: "query",
description: "The search query",
required: true,
schema: {
type: "string"
}
}
],
responses: {
200: {
description: "Users found",
content: {
'application/json': {
schema: {
type: "array",
items: {
type: "object",
"$ref": "#/components/schemas/User"
}
}
}
}
},
400: {
description: "Bad Request: Query is required"
}
}
}
}
},
components: {
schemas: {
Expand Down

0 comments on commit 1f25f73

Please sign in to comment.