mirror of
https://github.com/SrIzan10/hctv.git
synced 2026-06-06 00:56:56 +00:00
Compare commits
85 Commits
feat/js-sd
...
feat/metri
| Author | SHA1 | Date | |
|---|---|---|---|
| 626a9f0d5b | |||
| 88cb43204a | |||
| 1e5416f4b6 | |||
| f31f74eb1a | |||
| dc02831482 | |||
| a77ed916c5 | |||
| 96a68b46ae | |||
| 21e2e094d6 | |||
| fcdbc4e878 | |||
| cdb0c01ffd | |||
| 3771baae8c | |||
| d719debf6a | |||
| e22a35484a | |||
| 2597aa8d86 | |||
| e0b6075900 | |||
| c7cedbbfe0 | |||
| df4537bbe3 | |||
| 7cd071b3b6 | |||
| a8a64432a4 | |||
| 10b77c673e | |||
| 960e3306e4 | |||
| fbfbe3ff6f | |||
| 07eefcf9c7 | |||
| 527155a0c1 | |||
| ba30d6e097 | |||
| 70ae7ef3b3 | |||
| eddfebc311 | |||
| 460125972f | |||
| 91b08f00b2 | |||
| eccf9e5791 | |||
| 01514931cb | |||
| 6d5f7b4fd5 | |||
| 2c95ddc6dd | |||
| a6fcaff5f3 | |||
| b4f66e01d9 | |||
| ef5eab0d17 | |||
| cf4cc77071 | |||
| 1bbe4fdc0a | |||
| 67b9af57f9 | |||
| 398d4113c8 | |||
| 32c101934d | |||
| 48e00bada4 | |||
| bc69136133 | |||
| a96939684b | |||
| ed1608b8e3 | |||
| f4f653614d | |||
| 5fca354c58 | |||
| b4ad29853a | |||
| cf2f0ac86d | |||
| f57dec65e0 | |||
| 4c7ddeeb72 | |||
| 2a4a1adcd8 | |||
| 107982dbec | |||
| a75d9e3795 | |||
| 5336541010 | |||
| dd71b822ed | |||
| d343335b8e | |||
| 892cb7ab87 | |||
| b274903dc1 | |||
| b1c20a374a | |||
| 0b6b23c42d | |||
| 008db9e2c8 | |||
| 24bfcff68a | |||
| dc2b01ae21 | |||
| ef4563cc7c | |||
| 936b853536 | |||
| 60387773bf | |||
| eac101764b | |||
| 5f43567d89 | |||
|
|
bf86bafbe8 | ||
|
|
8f2516cabe | ||
|
|
d2cd99d3d4 | ||
|
|
c8e3b63cc5 | ||
| 60e01d8207 | |||
| 9e0ca29a2c | |||
| ae4d88a9e0 | |||
| 5735074af9 | |||
| 899e8f1054 | |||
| acd8e0d980 | |||
| cb10ee1855 | |||
| b0eb5d4430 | |||
| d8b9803019 | |||
| 2ceb813a98 | |||
| 6222f9dafe | |||
| c7bb9aef72 |
44
.github/workflows/docker.yml
vendored
44
.github/workflows/docker.yml
vendored
@@ -10,7 +10,7 @@ jobs:
|
||||
name: Push frontend to Docker Hub
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Wait
|
||||
- name: Wait
|
||||
uses: NathanFirmo/wait-for-other-action@v1.0.4
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -40,12 +40,12 @@ jobs:
|
||||
RELEASE_URL=$(curl -s https://api.github.com/repos/srizan10/hctv/releases/latest | \
|
||||
grep "browser_download_url.*slack-import-emojis-linux-x86_64" | \
|
||||
cut -d '"' -f 4)
|
||||
|
||||
|
||||
curl -L -o slack-import-emojis-bin $RELEASE_URL
|
||||
chmod +x slack-import-emojis-bin
|
||||
|
||||
|
||||
mkdir -p apps/web/src/lib/instrumentation/
|
||||
|
||||
|
||||
./slack-import-emojis-bin default
|
||||
|
||||
cp emojis.json apps/web/
|
||||
@@ -98,11 +98,43 @@ jobs:
|
||||
secrets: |
|
||||
TURBO_TOKEN=${{ secrets.TURBO_TOKEN }}
|
||||
TURBO_TEAM=${{ secrets.TURBO_TEAM }}
|
||||
mediamtx:
|
||||
name: Push MediaMTX image to Docker Hub
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check out the repo
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Log in to Docker Hub
|
||||
uses: docker/login-action@f4ef78c080cd8ba55a85445d5b36e214a81df20a
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
||||
- name: Extract metadata (tags, labels) for Docker
|
||||
id: meta
|
||||
uses: docker/metadata-action@9ec57ed1fcdbf14dcef7dfbe97b2010124a938b7
|
||||
with:
|
||||
images: srizan10/hclive-mediamtx
|
||||
tags: latest
|
||||
|
||||
- name: Build and push Docker image
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
file: ./docker/mediamtx/Dockerfile
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
platforms: linux/amd64
|
||||
deploy:
|
||||
name: Deploy to Coolify
|
||||
runs-on: ubuntu-latest
|
||||
needs: [frontend, chat]
|
||||
needs: [frontend, chat, mediamtx]
|
||||
steps:
|
||||
- name: Send coolify redeploy webhook
|
||||
run: |
|
||||
curl -X POST -H "Authorization: Bearer ${{ secrets.COOLIFY_API_KEY }}" https://coolify.srizan.dev/api/v1/deploy?uuid=${{ secrets.COOLIFY_APP_UUID }}&force=true
|
||||
curl -X POST -H "Authorization: Bearer ${{ secrets.COOLIFY_API_KEY }}" https://coolify.srizan.dev/api/v1/deploy?uuid=${{ secrets.COOLIFY_APP_UUID }}&force=true
|
||||
|
||||
@@ -14,7 +14,8 @@
|
||||
"@hono/node-ws": "^1.1.0",
|
||||
"@leeoniya/ufuzzy": "^1.0.18",
|
||||
"@oslojs/encoding": "^1.1.0",
|
||||
"hono": "^4.7.5"
|
||||
"hono": "^4.7.5",
|
||||
"prom-client": "^15.1.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.11.17",
|
||||
|
||||
@@ -1,41 +1,342 @@
|
||||
import { serve } from '@hono/node-server';
|
||||
import { createNodeWebSocket, type ModifiedWebSocket } from '@hctv/hono-ws';
|
||||
import { createNodeWebSocket } from '@hctv/hono-ws';
|
||||
import { Hono } from 'hono';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { lucia } from '@hctv/auth';
|
||||
import { getCookie } from 'hono/cookie';
|
||||
import {
|
||||
chatMetricsRegistry,
|
||||
recordChatConnectionAccepted,
|
||||
recordChatConnectionRejected,
|
||||
recordChatDisconnect,
|
||||
recordChatError,
|
||||
recordChatModerationBlock,
|
||||
recordDeliveredChatMessage,
|
||||
recordDeliveredChatMessageBytes,
|
||||
recordEmojiSearchResults,
|
||||
recordHistoryMessagesLoaded,
|
||||
recordIncomingChatMessage,
|
||||
recordUniqueChatter,
|
||||
setChannelHistorySize,
|
||||
setChatModerationState,
|
||||
startChatMessageTimer,
|
||||
} from './metrics.js';
|
||||
import { getPersonalChannel } from './utils/personalChannel.js';
|
||||
import { getRedisConnection, prisma, type BotAccount, type BotApiKey, type User } from '@hctv/db';
|
||||
import { ChatModerationAction, getRedisConnection, prisma } from '@hctv/db';
|
||||
import uFuzzy from '@leeoniya/ufuzzy';
|
||||
import {
|
||||
handleDeleteMessageCommand,
|
||||
handleUserRestrictionCommand,
|
||||
sendModerationError,
|
||||
} from './utils/moderation.js';
|
||||
import { randomString } from './utils/randomString.js';
|
||||
import type {
|
||||
ChatModerationCommand,
|
||||
ChatModerationSettingsShape,
|
||||
ChatRestrictionState,
|
||||
ChatSocket,
|
||||
ChatUser,
|
||||
} from './types/chat.js';
|
||||
import { basicAuth } from 'hono/basic-auth';
|
||||
|
||||
const redis = getRedisConnection();
|
||||
const MESSAGE_HISTORY_SIZE = 15;
|
||||
const MESSAGE_HISTORY_SIZE = 100;
|
||||
const MESSAGE_TTL = 60 * 60 * 24;
|
||||
const MODERATION_SETTINGS_CACHE_TTL_SECONDS = 30;
|
||||
const threed = await readFile('./src/3d.txt', 'utf-8');
|
||||
const uf = new uFuzzy();
|
||||
|
||||
type IncomingMessage = {
|
||||
type?: string;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
|
||||
const METRICS_MESSAGE_TYPES = [
|
||||
'ping',
|
||||
'message',
|
||||
'emojiMsg',
|
||||
'emojiSearch',
|
||||
'mod:deleteMessage',
|
||||
'mod:timeoutUser',
|
||||
'mod:banUser',
|
||||
'mod:unbanUser',
|
||||
'mod:liftTimeout',
|
||||
] as const;
|
||||
|
||||
type MetricsMessageType = (typeof METRICS_MESSAGE_TYPES)[number] | 'unknown';
|
||||
|
||||
function getMetricsMessageType(type: unknown): MetricsMessageType {
|
||||
if (typeof type !== 'string') {
|
||||
return 'unknown';
|
||||
}
|
||||
|
||||
return (METRICS_MESSAGE_TYPES as readonly string[]).includes(type)
|
||||
? (type as MetricsMessageType)
|
||||
: 'unknown';
|
||||
}
|
||||
|
||||
const DEFAULT_MODERATION_SETTINGS: ChatModerationSettingsShape = {
|
||||
blockedTerms: [],
|
||||
slowModeSeconds: 0,
|
||||
maxMessageLength: 400,
|
||||
rateLimitCount: 8,
|
||||
rateLimitWindowSeconds: 10,
|
||||
};
|
||||
|
||||
function normalizeModerationSettings(
|
||||
settings?: Partial<ChatModerationSettingsShape> | null
|
||||
): ChatModerationSettingsShape {
|
||||
return {
|
||||
blockedTerms:
|
||||
settings?.blockedTerms
|
||||
?.map((term) => term.trim().toLowerCase())
|
||||
.filter((term) => term.length >= 2)
|
||||
.slice(0, 200) ?? [],
|
||||
slowModeSeconds: Math.min(Math.max(settings?.slowModeSeconds ?? 0, 0), 120),
|
||||
maxMessageLength: Math.min(Math.max(settings?.maxMessageLength ?? 50, 50), 2000),
|
||||
rateLimitCount: Math.min(Math.max(settings?.rateLimitCount ?? 8, 3), 30),
|
||||
rateLimitWindowSeconds: Math.min(Math.max(settings?.rateLimitWindowSeconds ?? 10, 5), 60),
|
||||
};
|
||||
}
|
||||
|
||||
function escapeRegExp(value: string): string {
|
||||
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
}
|
||||
|
||||
function containsBlockedTerm(message: string, blockedTerms: string[]): string | null {
|
||||
const normalizedMessage = message.toLowerCase();
|
||||
|
||||
for (const term of blockedTerms) {
|
||||
const regex = new RegExp(`(^|\\W)${escapeRegExp(term)}($|\\W)`, 'i');
|
||||
if (regex.test(normalizedMessage)) {
|
||||
return term;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
async function getCachedModerationSettings(
|
||||
channelId: string
|
||||
): Promise<ChatModerationSettingsShape> {
|
||||
const cacheKey = `chat:moderation:settings:${channelId}`;
|
||||
const cachedSettings = await redis.get(cacheKey);
|
||||
|
||||
if (cachedSettings) {
|
||||
try {
|
||||
return normalizeModerationSettings(JSON.parse(cachedSettings));
|
||||
} catch {
|
||||
await redis.del(cacheKey);
|
||||
}
|
||||
}
|
||||
|
||||
const dbSettings = await prisma.chatModerationSettings.findUnique({
|
||||
where: { channelId },
|
||||
select: {
|
||||
blockedTerms: true,
|
||||
slowModeSeconds: true,
|
||||
maxMessageLength: true,
|
||||
rateLimitCount: true,
|
||||
rateLimitWindowSeconds: true,
|
||||
},
|
||||
});
|
||||
|
||||
const normalized = normalizeModerationSettings(dbSettings ?? DEFAULT_MODERATION_SETTINGS);
|
||||
await redis.setex(cacheKey, MODERATION_SETTINGS_CACHE_TTL_SECONDS, JSON.stringify(normalized));
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function resolveSocketState(socket: ChatSocket): ChatSocket {
|
||||
return (socket.raw as unknown as ChatSocket | undefined) ?? socket;
|
||||
}
|
||||
|
||||
function broadcastToChannel(
|
||||
targetUsername: string,
|
||||
ws: ChatSocket,
|
||||
payload: Record<string, unknown>
|
||||
) {
|
||||
ws.wss.clients.forEach((clientSocket: unknown) => {
|
||||
const client = clientSocket as ChatSocket;
|
||||
const clientState = resolveSocketState(client);
|
||||
if (client.readyState === client.OPEN && clientState.targetUsername === targetUsername) {
|
||||
client.send(JSON.stringify(payload));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function getActiveRestriction(
|
||||
channelId: string,
|
||||
userId: string
|
||||
): Promise<ChatRestrictionState | null> {
|
||||
const activeBan = await prisma.chatUserBan.findUnique({
|
||||
where: {
|
||||
channelId_userId: {
|
||||
channelId,
|
||||
userId,
|
||||
},
|
||||
},
|
||||
select: {
|
||||
reason: true,
|
||||
expiresAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!activeBan) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (activeBan.expiresAt && activeBan.expiresAt < new Date()) {
|
||||
await prisma.chatUserBan.delete({
|
||||
where: {
|
||||
channelId_userId: {
|
||||
channelId,
|
||||
userId,
|
||||
},
|
||||
},
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
type: activeBan.expiresAt ? 'timeout' : 'ban',
|
||||
reason: activeBan.reason,
|
||||
expiresAt: activeBan.expiresAt,
|
||||
};
|
||||
}
|
||||
|
||||
async function sendChatAccessState(socket: ChatSocket, channelId: string, userId: string) {
|
||||
const restriction = await getActiveRestriction(channelId, userId);
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: 'chatAccess',
|
||||
canSend: !restriction,
|
||||
restriction,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
async function broadcastRestrictionStateToUser(
|
||||
targetUsername: string,
|
||||
targetUserId: string,
|
||||
channelId: string,
|
||||
ws: ChatSocket
|
||||
) {
|
||||
const restriction = await getActiveRestriction(channelId, targetUserId);
|
||||
ws.wss.clients.forEach((clientSocket: unknown) => {
|
||||
const client = clientSocket as ChatSocket;
|
||||
const clientState = resolveSocketState(client);
|
||||
if (
|
||||
client.readyState === client.OPEN &&
|
||||
clientState.targetUsername === targetUsername &&
|
||||
clientState.chatUser?.id === targetUserId
|
||||
) {
|
||||
client.send(
|
||||
JSON.stringify({
|
||||
type: 'chatAccess',
|
||||
canSend: !restriction,
|
||||
restriction,
|
||||
})
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const RATE_LIMIT_LUA = `
|
||||
local current = redis.call('INCR', KEYS[1])
|
||||
if current == 1 then
|
||||
redis.call('EXPIRE', KEYS[1], ARGV[1])
|
||||
end
|
||||
return current
|
||||
`;
|
||||
|
||||
async function isRateLimited(
|
||||
channelId: string,
|
||||
userId: string,
|
||||
count: number,
|
||||
windowSeconds: number
|
||||
): Promise<boolean> {
|
||||
const key = `chat:ratelimit:${channelId}:${userId}`;
|
||||
const currentCount = (await redis.eval(RATE_LIMIT_LUA, 1, key, String(windowSeconds))) as number;
|
||||
return currentCount > count;
|
||||
}
|
||||
|
||||
async function logModerationEvent(payload: {
|
||||
action: ChatModerationAction;
|
||||
channelId: string;
|
||||
moderatorId: string;
|
||||
targetUserId?: string;
|
||||
reason?: string;
|
||||
details?: Record<string, unknown>;
|
||||
}) {
|
||||
await prisma.chatModerationEvent.create({
|
||||
data: {
|
||||
action: payload.action,
|
||||
channelId: payload.channelId,
|
||||
moderatorId: payload.moderatorId,
|
||||
targetUserId: payload.targetUserId,
|
||||
reason: payload.reason,
|
||||
details: payload.details as any,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function deleteMessageFromHistory(targetUsername: string, msgId: string): Promise<boolean> {
|
||||
const channelKey = `chat:history:${targetUsername}`;
|
||||
const history = await redis.zrange(channelKey, 0, -1);
|
||||
|
||||
for (const entry of history) {
|
||||
try {
|
||||
const parsed = JSON.parse(entry) as { msgId?: string };
|
||||
if (parsed.msgId === msgId) {
|
||||
await redis.zrem(channelKey, entry);
|
||||
return true;
|
||||
}
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
const app = new Hono();
|
||||
const { injectWebSocket, upgradeWebSocket } = createNodeWebSocket({ app });
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
app.use(
|
||||
'/metrics',
|
||||
basicAuth({ username: process.env.METRICS_USER!, password: process.env.METRICS_PASS! })
|
||||
);
|
||||
}
|
||||
|
||||
app.get('/', async (c) => {
|
||||
return c.text(threed);
|
||||
});
|
||||
|
||||
app.get('/up', async (c) => {
|
||||
return c.text('it works');
|
||||
return c.text('hello world');
|
||||
});
|
||||
|
||||
app.get('/metrics', async () => {
|
||||
return new Response(await chatMetricsRegistry.metrics(), {
|
||||
headers: {
|
||||
'Content-Type': chatMetricsRegistry.contentType,
|
||||
'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate',
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
app.get(
|
||||
'/ws/:username',
|
||||
upgradeWebSocket((c) => ({
|
||||
async onOpen(evt, ws) {
|
||||
let authMethod = 'unknown';
|
||||
const token = getCookie(c, 'auth_session');
|
||||
const grant = c.req.query('grant');
|
||||
const authHeader = c.req.header('Authorization');
|
||||
const botAuth = c.req.query('botAuth');
|
||||
|
||||
if (!token && (!grant || grant === 'null') && !authHeader && !botAuth) {
|
||||
recordChatConnectionRejected(authMethod, 'missing_auth');
|
||||
ws.close();
|
||||
return;
|
||||
}
|
||||
@@ -62,12 +363,16 @@ app.get(
|
||||
});
|
||||
|
||||
if (botAccount) {
|
||||
authMethod = 'bot_api_key';
|
||||
chatUser = {
|
||||
id: botAccount.botAccount.id,
|
||||
username: botAccount.botAccount.slug,
|
||||
pfpUrl: botAccount.botAccount.pfpUrl,
|
||||
displayName: botAccount.botAccount.displayName,
|
||||
isBot: true,
|
||||
moderatorUserId: botAccount.botAccount.ownerId,
|
||||
isPlatformAdmin: false,
|
||||
channelRole: null,
|
||||
};
|
||||
|
||||
personalChannel = {
|
||||
@@ -82,11 +387,15 @@ app.get(
|
||||
if (session.user) {
|
||||
const userChannel = await getPersonalChannel(session.user.id);
|
||||
if (userChannel) {
|
||||
authMethod = 'session';
|
||||
chatUser = {
|
||||
id: session.user.id,
|
||||
username: userChannel.name,
|
||||
pfpUrl: session.user.pfpUrl,
|
||||
isBot: false,
|
||||
moderatorUserId: session.user.id,
|
||||
isPlatformAdmin: Boolean(session.user.isAdmin),
|
||||
channelRole: null,
|
||||
};
|
||||
personalChannel = userChannel;
|
||||
}
|
||||
@@ -101,53 +410,178 @@ app.get(
|
||||
: null;
|
||||
|
||||
if (!chatUser && !dbGrant) {
|
||||
recordChatConnectionRejected(authMethod, 'auth_failed');
|
||||
ws.close();
|
||||
return;
|
||||
}
|
||||
|
||||
const { username } = c.req.param();
|
||||
if (!chatUser && dbGrant) {
|
||||
authMethod = 'obs_grant';
|
||||
}
|
||||
|
||||
if (dbGrant && dbGrant.name !== username) {
|
||||
recordChatConnectionRejected(authMethod, 'grant_mismatch');
|
||||
ws.close();
|
||||
return;
|
||||
}
|
||||
const channel = await prisma.channel.findUnique({
|
||||
where: { name: username },
|
||||
select: {
|
||||
id: true,
|
||||
ownerId: true,
|
||||
managers: {
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
},
|
||||
chatModerators: {
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
},
|
||||
chatModeratorBots: {
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!channel) {
|
||||
recordChatConnectionRejected(authMethod, 'channel_not_found');
|
||||
ws.close();
|
||||
return;
|
||||
}
|
||||
|
||||
if (await prisma.channel.count({ where: { name: username } }) === 0) {
|
||||
// channel doesn't exist
|
||||
ws.close();
|
||||
return;
|
||||
let channelRole: ChatUser['channelRole'] = null;
|
||||
const activeChatUser = chatUser;
|
||||
if (activeChatUser) {
|
||||
if (activeChatUser.isBot) {
|
||||
if (channel.chatModeratorBots.some((bot) => bot.id === activeChatUser.id)) {
|
||||
channelRole = 'botModerator';
|
||||
}
|
||||
} else if (channel.ownerId === activeChatUser.id) {
|
||||
channelRole = 'owner';
|
||||
} else if (channel.managers.some((manager) => manager.id === activeChatUser.id)) {
|
||||
channelRole = 'manager';
|
||||
} else if (channel.chatModerators.some((moderator) => moderator.id === activeChatUser.id)) {
|
||||
channelRole = 'chatModerator';
|
||||
}
|
||||
}
|
||||
|
||||
ws.targetUsername = username;
|
||||
ws.chatUser = chatUser;
|
||||
ws.personalChannel = personalChannel;
|
||||
ws.viewerId = randomString(10);
|
||||
if (chatUser) {
|
||||
const moderatorUser = await prisma.user.findUnique({
|
||||
where: { id: chatUser.moderatorUserId },
|
||||
select: { isAdmin: true },
|
||||
});
|
||||
|
||||
if (ws.raw) {
|
||||
ws.raw.targetUsername = username;
|
||||
ws.raw.chatUser = chatUser;
|
||||
ws.raw.personalChannel = personalChannel;
|
||||
chatUser = {
|
||||
...chatUser,
|
||||
isPlatformAdmin: chatUser.isBot ? false : Boolean(moderatorUser?.isAdmin),
|
||||
channelRole,
|
||||
};
|
||||
}
|
||||
|
||||
const isModerator = Boolean(
|
||||
chatUser &&
|
||||
(chatUser.isPlatformAdmin ||
|
||||
chatUser.channelRole === 'owner' ||
|
||||
chatUser.channelRole === 'manager' ||
|
||||
chatUser.channelRole === 'chatModerator' ||
|
||||
chatUser.channelRole === 'botModerator')
|
||||
);
|
||||
|
||||
const moderationSettings = await getCachedModerationSettings(channel.id);
|
||||
|
||||
const socket = ws as unknown as ChatSocket;
|
||||
const socketState = resolveSocketState(socket);
|
||||
|
||||
socket.targetUsername = username;
|
||||
socket.channelId = channel.id;
|
||||
socket.chatUser = chatUser;
|
||||
socket.personalChannel = personalChannel;
|
||||
socket.viewerId = randomString(10);
|
||||
socket.isModerator = isModerator;
|
||||
socket.excludeFromViewerCount = Boolean(dbGrant);
|
||||
|
||||
socketState.targetUsername = username;
|
||||
socketState.channelId = channel.id;
|
||||
socketState.chatUser = chatUser;
|
||||
socketState.personalChannel = personalChannel;
|
||||
socketState.viewerId = socket.viewerId;
|
||||
socketState.isModerator = isModerator;
|
||||
socket.metricsTracked = true;
|
||||
socketState.metricsTracked = true;
|
||||
socket.metricsAuthMethod = authMethod;
|
||||
socketState.metricsAuthMethod = authMethod;
|
||||
|
||||
recordChatConnectionAccepted(username, authMethod);
|
||||
setChatModerationState(username, {
|
||||
blockedTerms: moderationSettings.blockedTerms.length,
|
||||
maxMessageLength: moderationSettings.maxMessageLength,
|
||||
rateLimitCount: moderationSettings.rateLimitCount,
|
||||
rateLimitWindowSeconds: moderationSettings.rateLimitWindowSeconds,
|
||||
slowModeSeconds: moderationSettings.slowModeSeconds,
|
||||
});
|
||||
|
||||
socketState.excludeFromViewerCount = Boolean(dbGrant);
|
||||
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: 'session',
|
||||
viewer: chatUser
|
||||
? {
|
||||
id: chatUser.id,
|
||||
username: chatUser.username,
|
||||
}
|
||||
: null,
|
||||
permissions: {
|
||||
canModerate: isModerator,
|
||||
},
|
||||
moderation: {
|
||||
hasBlockedTerms: moderationSettings.blockedTerms.length > 0,
|
||||
slowModeSeconds: moderationSettings.slowModeSeconds,
|
||||
maxMessageLength: moderationSettings.maxMessageLength,
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
if (chatUser && !chatUser.isBot) {
|
||||
await sendChatAccessState(socket, channel.id, chatUser.id);
|
||||
}
|
||||
|
||||
const channelKey = `chat:history:${username}`;
|
||||
const messages = await redis.zrange(channelKey, 0, MESSAGE_HISTORY_SIZE - 1);
|
||||
|
||||
if (messages.length > 0) {
|
||||
ws.send(
|
||||
recordHistoryMessagesLoaded(username, messages.length);
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: 'history',
|
||||
messages: messages.map((msg) => JSON.parse(msg)),
|
||||
})
|
||||
);
|
||||
}
|
||||
setChannelHistorySize(username, messages.length);
|
||||
},
|
||||
async onClose(evt, ws) {
|
||||
// if prematurely exiting due to authentication issues
|
||||
console.log('client disconnected');
|
||||
if (!ws.targetUsername) return;
|
||||
const socket = ws as unknown as ChatSocket;
|
||||
const socketState = resolveSocketState(socket);
|
||||
if (process.env.NODE_ENV !== 'production') console.log('client disconnected');
|
||||
if (!socketState.targetUsername) return;
|
||||
|
||||
if (socketState.metricsTracked) {
|
||||
recordChatDisconnect(
|
||||
socketState.targetUsername,
|
||||
socketState.metricsAuthMethod ?? 'unknown'
|
||||
);
|
||||
socketState.metricsTracked = false;
|
||||
}
|
||||
|
||||
const streamInfo = await prisma.streamInfo.findUnique({
|
||||
where: {
|
||||
username: ws.targetUsername,
|
||||
username: socketState.targetUsername,
|
||||
},
|
||||
select: {
|
||||
viewers: true,
|
||||
@@ -156,57 +590,200 @@ app.get(
|
||||
|
||||
if (!streamInfo) return;
|
||||
|
||||
await redis.del(`viewer:${ws.targetUsername}:${ws.viewerId}`);
|
||||
if (!socketState.excludeFromViewerCount) {
|
||||
await redis.del(`viewer:${socketState.targetUsername}:${socketState.viewerId}`);
|
||||
}
|
||||
},
|
||||
async onMessage(evt, ws) {
|
||||
let outcome = 'ignored';
|
||||
let messageType = 'unknown';
|
||||
let stopTimer: ReturnType<typeof startChatMessageTimer> | null = null;
|
||||
|
||||
try {
|
||||
const msg = JSON.parse(evt.data.toString());
|
||||
const socket = ws as unknown as ChatSocket;
|
||||
const socketState = resolveSocketState(socket);
|
||||
const rawPayload = evt.data.toString();
|
||||
const msg = JSON.parse(rawPayload) as IncomingMessage;
|
||||
messageType = getMetricsMessageType(msg.type);
|
||||
recordIncomingChatMessage(messageType, Buffer.byteLength(rawPayload));
|
||||
stopTimer = startChatMessageTimer(messageType);
|
||||
|
||||
if (msg.type === 'ping') {
|
||||
await redis.setex(`viewer:${ws.targetUsername}:${ws.viewerId}`, 30, '1');
|
||||
ws.send(JSON.stringify({ type: 'pong' }));
|
||||
if (!socketState.excludeFromViewerCount) {
|
||||
await redis.setex(
|
||||
`viewer:${socketState.targetUsername}:${socketState.viewerId}`,
|
||||
30,
|
||||
'1'
|
||||
);
|
||||
}
|
||||
socket.send(JSON.stringify({ type: 'pong' }));
|
||||
outcome = 'pong';
|
||||
return;
|
||||
}
|
||||
|
||||
if (msg.type === 'mod:deleteMessage') {
|
||||
await handleDeleteMessageCommand(socket, socketState, msg as ChatModerationCommand, {
|
||||
deleteMessageFromHistory,
|
||||
logModerationEvent,
|
||||
broadcastToChannel,
|
||||
});
|
||||
outcome = 'moderation';
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
msg.type === 'mod:timeoutUser' ||
|
||||
msg.type === 'mod:banUser' ||
|
||||
msg.type === 'mod:unbanUser' ||
|
||||
msg.type === 'mod:liftTimeout'
|
||||
) {
|
||||
await handleUserRestrictionCommand(socket, socketState, msg as ChatModerationCommand, {
|
||||
logModerationEvent,
|
||||
broadcastRestrictionStateToUser,
|
||||
broadcastToChannel,
|
||||
});
|
||||
outcome = 'moderation';
|
||||
return;
|
||||
}
|
||||
|
||||
if (msg.type === 'message') {
|
||||
if (!ws.chatUser || !ws.personalChannel) return;
|
||||
if (
|
||||
!socketState.chatUser ||
|
||||
!socketState.personalChannel ||
|
||||
!socketState.channelId ||
|
||||
!socketState.targetUsername
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const chatUser = socketState.chatUser;
|
||||
const channelId = socketState.channelId;
|
||||
const targetUsername = socketState.targetUsername;
|
||||
const isModerator = Boolean(socketState.isModerator);
|
||||
|
||||
if (!chatUser || !channelId || !targetUsername) {
|
||||
return;
|
||||
}
|
||||
|
||||
const moderationSettings = await getCachedModerationSettings(channelId);
|
||||
|
||||
const restriction = await getActiveRestriction(channelId, chatUser.id);
|
||||
if (restriction) {
|
||||
sendModerationError(
|
||||
socket,
|
||||
restriction.type === 'timeout' ? 'TIMED_OUT' : 'BANNED',
|
||||
restriction.type === 'timeout'
|
||||
? 'You are currently timed out in this chat.'
|
||||
: 'You are currently banned from this chat.',
|
||||
restriction
|
||||
);
|
||||
|
||||
await sendChatAccessState(socket, channelId, chatUser.id);
|
||||
outcome = 'blocked';
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
!isModerator &&
|
||||
(await isRateLimited(
|
||||
channelId,
|
||||
chatUser.id,
|
||||
moderationSettings.rateLimitCount,
|
||||
moderationSettings.rateLimitWindowSeconds
|
||||
))
|
||||
) {
|
||||
sendModerationError(socket, 'RATE_LIMIT', 'You are sending messages too fast.');
|
||||
recordChatModerationBlock('rate_limit');
|
||||
outcome = 'rate_limited';
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isModerator && moderationSettings.slowModeSeconds > 0) {
|
||||
const slowModeKey = `chat:slowmode:${channelId}:${chatUser.id}`;
|
||||
const timeRemaining = await redis.ttl(slowModeKey);
|
||||
if (timeRemaining > 0) {
|
||||
sendModerationError(socket, 'SLOW_MODE', `Slow mode is on. Wait ${timeRemaining}s.`);
|
||||
recordChatModerationBlock('slow_mode');
|
||||
outcome = 'slow_mode';
|
||||
return;
|
||||
}
|
||||
await redis.setex(slowModeKey, moderationSettings.slowModeSeconds, '1');
|
||||
}
|
||||
|
||||
const message = (msg.message as string).trim();
|
||||
if (!message) {
|
||||
return;
|
||||
}
|
||||
if (message.length > moderationSettings.maxMessageLength) {
|
||||
sendModerationError(
|
||||
socket,
|
||||
'MESSAGE_TOO_LONG',
|
||||
`Message exceeds ${moderationSettings.maxMessageLength} characters.`
|
||||
);
|
||||
recordChatModerationBlock('message_too_long');
|
||||
outcome = 'message_too_long';
|
||||
return;
|
||||
}
|
||||
|
||||
const blockedTerm = containsBlockedTerm(message, moderationSettings.blockedTerms);
|
||||
if (blockedTerm) {
|
||||
if (!chatUser.isBot) {
|
||||
await logModerationEvent({
|
||||
action: ChatModerationAction.MESSAGE_BLOCKED,
|
||||
channelId,
|
||||
moderatorId: chatUser.id,
|
||||
targetUserId: chatUser.id,
|
||||
reason: 'Blocked term matched',
|
||||
details: { blockedTerm },
|
||||
});
|
||||
}
|
||||
recordChatModerationBlock('blocked_term');
|
||||
sendModerationError(socket, 'BLOCKED_TERM', 'Message blocked by channel moderation.');
|
||||
outcome = 'blocked_term';
|
||||
return;
|
||||
}
|
||||
|
||||
const msgId = crypto.randomUUID();
|
||||
const msgObj = {
|
||||
user: {
|
||||
id: ws.chatUser.id,
|
||||
username: ws.chatUser.username,
|
||||
pfpUrl: ws.chatUser.pfpUrl,
|
||||
displayName: ws.chatUser.displayName,
|
||||
isBot: ws.chatUser.isBot || false,
|
||||
id: chatUser.id,
|
||||
username: chatUser.username,
|
||||
pfpUrl: chatUser.pfpUrl,
|
||||
displayName: chatUser.displayName,
|
||||
isBot: chatUser.isBot || false,
|
||||
isPlatformAdmin: chatUser.isPlatformAdmin,
|
||||
channelRole: chatUser.channelRole,
|
||||
},
|
||||
message,
|
||||
msgId: `${crypto.randomUUID()}`
|
||||
};
|
||||
|
||||
const redisObj = {
|
||||
user: msgObj.user,
|
||||
message: msgObj.message,
|
||||
msgId,
|
||||
type: 'message',
|
||||
msgId: `${crypto.randomUUID()}`,
|
||||
};
|
||||
|
||||
const redisStr = JSON.stringify(redisObj);
|
||||
const msgStr = JSON.stringify(msgObj);
|
||||
const redisStr = JSON.stringify(msgObj);
|
||||
|
||||
const channelKey = `chat:history:${ws.targetUsername}`;
|
||||
const channelKey = `chat:history:${targetUsername}`;
|
||||
await redis.zadd(channelKey, Date.now(), redisStr);
|
||||
await redis.zremrangebyrank(channelKey, 0, -MESSAGE_HISTORY_SIZE - 1);
|
||||
await redis.expire(channelKey, MESSAGE_TTL);
|
||||
const historySize = await redis.zcard(channelKey);
|
||||
setChannelHistorySize(targetUsername, historySize);
|
||||
|
||||
ws.wss.clients.forEach((c) => {
|
||||
const client = c as ModifiedWebSocket;
|
||||
if (client.readyState === client.OPEN && client.targetUsername === ws.targetUsername) {
|
||||
c.send(msgStr);
|
||||
}
|
||||
});
|
||||
broadcastToChannel(targetUsername, socket, msgObj as unknown as Record<string, unknown>);
|
||||
recordDeliveredChatMessage(chatUser.isBot ? 'bot' : 'user');
|
||||
recordDeliveredChatMessageBytes(
|
||||
chatUser.isBot ? 'bot' : 'user',
|
||||
Buffer.byteLength(message)
|
||||
);
|
||||
const isFirstMessageFromUser =
|
||||
(await redis.sadd(`chat:unique-chatters:${targetUsername}`, chatUser.id)) === 1;
|
||||
|
||||
if (isFirstMessageFromUser) {
|
||||
recordUniqueChatter(chatUser.isBot ? 'bot' : 'user');
|
||||
}
|
||||
outcome = 'broadcast';
|
||||
}
|
||||
if (msg.type === 'emojiMsg') {
|
||||
if (!socketState.chatUser) return;
|
||||
const emojis = msg.emojis as string[];
|
||||
const emojiMap: Record<string, string> = {};
|
||||
|
||||
@@ -231,15 +808,22 @@ app.get(
|
||||
emojis: emojiMap,
|
||||
})
|
||||
);
|
||||
outcome = 'emoji_lookup';
|
||||
}
|
||||
if (msg.type === 'emojiSearch') {
|
||||
console.log('emoji search request:', msg);
|
||||
const searchTerm = msg.searchTerm as string;
|
||||
if (!socketState.chatUser) return;
|
||||
const rawSearchTerm = (msg.searchTerm as string)?.trim() ?? '';
|
||||
if (!rawSearchTerm || rawSearchTerm.length > 50) {
|
||||
ws.send(JSON.stringify({ type: 'emojiSearchResponse', results: [] }));
|
||||
recordEmojiSearchResults('empty', 0);
|
||||
outcome = 'emoji_search_empty';
|
||||
return;
|
||||
}
|
||||
const searchTerm = rawSearchTerm;
|
||||
|
||||
const emojis = await redis.hgetall('emojis');
|
||||
const emojiKeys = Object.keys(emojis);
|
||||
const idxs = uf.filter(emojiKeys, searchTerm);
|
||||
console.log(`Emoji search for "${searchTerm}" found ${idxs?.length || 0} results.`);
|
||||
|
||||
if (idxs && idxs.length > 0) {
|
||||
const results: string[] = [];
|
||||
@@ -262,7 +846,8 @@ app.get(
|
||||
results: results,
|
||||
})
|
||||
);
|
||||
console.log(`Sending emoji search results: ${results.join(', ')}`);
|
||||
recordEmojiSearchResults('matched', results.length);
|
||||
outcome = 'emoji_search';
|
||||
} else {
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
@@ -270,10 +855,16 @@ app.get(
|
||||
results: [],
|
||||
})
|
||||
);
|
||||
recordEmojiSearchResults('no_match', 0);
|
||||
outcome = 'emoji_search_empty';
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
outcome = 'error';
|
||||
recordChatError('on_message');
|
||||
console.error('Error processing message:', e);
|
||||
} finally {
|
||||
stopTimer?.({ type: messageType, outcome });
|
||||
}
|
||||
},
|
||||
}))
|
||||
@@ -289,11 +880,3 @@ const server = serve(
|
||||
}
|
||||
);
|
||||
injectWebSocket(server);
|
||||
|
||||
interface ChatUser {
|
||||
id: string;
|
||||
username: string;
|
||||
pfpUrl: string;
|
||||
displayName?: string;
|
||||
isBot: boolean;
|
||||
}
|
||||
|
||||
251
apps/chat/src/metrics.ts
Normal file
251
apps/chat/src/metrics.ts
Normal file
@@ -0,0 +1,251 @@
|
||||
import { collectDefaultMetrics, Counter, Gauge, Histogram, Registry } from 'prom-client';
|
||||
|
||||
function createMetricsStore() {
|
||||
const register = new Registry();
|
||||
register.setDefaultLabels({ app: 'chat' });
|
||||
|
||||
collectDefaultMetrics({
|
||||
prefix: 'hctv_chat_',
|
||||
register,
|
||||
});
|
||||
|
||||
const websocketConnections = new Gauge({
|
||||
name: 'hctv_chat_websocket_connections',
|
||||
help: 'Current number of active chat websocket connections.',
|
||||
registers: [register],
|
||||
});
|
||||
|
||||
const websocketConnectionsByChannel = new Gauge({
|
||||
name: 'hctv_chat_websocket_connections_by_channel',
|
||||
help: 'Current number of active chat websocket connections by target channel.',
|
||||
labelNames: ['channel'],
|
||||
registers: [register],
|
||||
});
|
||||
|
||||
const websocketConnectionsByAuthMethod = new Gauge({
|
||||
name: 'hctv_chat_websocket_connections_by_auth_method',
|
||||
help: 'Current number of active chat websocket connections by auth method.',
|
||||
labelNames: ['auth_method'],
|
||||
registers: [register],
|
||||
});
|
||||
|
||||
const websocketConnectionAttempts = new Counter({
|
||||
name: 'hctv_chat_websocket_connection_attempts_total',
|
||||
help: 'Total websocket connection attempts grouped by outcome, auth method, and rejection reason.',
|
||||
labelNames: ['outcome', 'auth_method', 'reason'],
|
||||
registers: [register],
|
||||
});
|
||||
|
||||
const incomingMessages = new Counter({
|
||||
name: 'hctv_chat_incoming_messages_total',
|
||||
help: 'Total inbound websocket frames grouped by message type.',
|
||||
labelNames: ['type'],
|
||||
registers: [register],
|
||||
});
|
||||
|
||||
const inboundPayloadBytes = new Counter({
|
||||
name: 'hctv_chat_inbound_payload_bytes_total',
|
||||
help: 'Total inbound websocket payload bytes grouped by message type.',
|
||||
labelNames: ['type'],
|
||||
registers: [register],
|
||||
});
|
||||
|
||||
const messageDuration = new Histogram({
|
||||
name: 'hctv_chat_message_duration_seconds',
|
||||
help: 'Chat websocket message processing time in seconds.',
|
||||
labelNames: ['type', 'outcome'],
|
||||
buckets: [0.0005, 0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1],
|
||||
registers: [register],
|
||||
});
|
||||
|
||||
const deliveredMessages = new Counter({
|
||||
name: 'hctv_chat_messages_delivered_total',
|
||||
help: 'Total chat messages successfully broadcast, grouped by sender type.',
|
||||
labelNames: ['sender_type'],
|
||||
registers: [register],
|
||||
});
|
||||
|
||||
const deliveredMessageBytes = new Counter({
|
||||
name: 'hctv_chat_message_bytes_delivered_total',
|
||||
help: 'Total message body bytes successfully broadcast, grouped by sender type.',
|
||||
labelNames: ['sender_type'],
|
||||
registers: [register],
|
||||
});
|
||||
|
||||
const channelHistorySize = new Gauge({
|
||||
name: 'hctv_chat_channel_history_size',
|
||||
help: 'Current number of messages retained in Redis history for a channel.',
|
||||
labelNames: ['channel'],
|
||||
registers: [register],
|
||||
});
|
||||
|
||||
const channelHistoryLoadedMessages = new Counter({
|
||||
name: 'hctv_chat_history_messages_loaded_total',
|
||||
help: 'Total history messages loaded from Redis during websocket joins.',
|
||||
labelNames: ['channel'],
|
||||
registers: [register],
|
||||
});
|
||||
|
||||
const moderationState = new Gauge({
|
||||
name: 'hctv_chat_moderation_state',
|
||||
help: 'Current moderation settings by channel.',
|
||||
labelNames: ['channel', 'setting'],
|
||||
registers: [register],
|
||||
});
|
||||
|
||||
const channelUniqueChatters = new Counter({
|
||||
name: 'hctv_chat_unique_chatters_total',
|
||||
help: 'Users who successfully sent at least one chat message, grouped by sender type.',
|
||||
labelNames: ['sender_type'],
|
||||
registers: [register],
|
||||
});
|
||||
|
||||
const moderationActions = new Counter({
|
||||
name: 'hctv_chat_moderation_actions_total',
|
||||
help: 'Successful moderation actions performed in chat.',
|
||||
labelNames: ['action'],
|
||||
registers: [register],
|
||||
});
|
||||
|
||||
const moderationBlocks = new Counter({
|
||||
name: 'hctv_chat_moderation_blocks_total',
|
||||
help: 'Message blocks and throttling decisions grouped by reason.',
|
||||
labelNames: ['reason'],
|
||||
registers: [register],
|
||||
});
|
||||
|
||||
const emojiSearchResults = new Histogram({
|
||||
name: 'hctv_chat_emoji_search_results',
|
||||
help: 'Number of emoji search results returned per query.',
|
||||
labelNames: ['outcome'],
|
||||
buckets: [0, 1, 2, 5, 10, 25, 50, 100, 150],
|
||||
registers: [register],
|
||||
});
|
||||
|
||||
const errors = new Counter({
|
||||
name: 'hctv_chat_errors_total',
|
||||
help: 'Errors observed in the chat service grouped by phase.',
|
||||
labelNames: ['phase'],
|
||||
registers: [register],
|
||||
});
|
||||
|
||||
return {
|
||||
deliveredMessages,
|
||||
deliveredMessageBytes,
|
||||
channelHistoryLoadedMessages,
|
||||
channelHistorySize,
|
||||
emojiSearchResults,
|
||||
errors,
|
||||
inboundPayloadBytes,
|
||||
incomingMessages,
|
||||
messageDuration,
|
||||
moderationActions,
|
||||
moderationBlocks,
|
||||
moderationState,
|
||||
register,
|
||||
channelUniqueChatters,
|
||||
websocketConnectionAttempts,
|
||||
websocketConnections,
|
||||
websocketConnectionsByAuthMethod,
|
||||
websocketConnectionsByChannel,
|
||||
};
|
||||
}
|
||||
|
||||
const globalForMetrics = globalThis as typeof globalThis & {
|
||||
__hctvChatMetrics?: ReturnType<typeof createMetricsStore>;
|
||||
};
|
||||
|
||||
const metrics = (globalForMetrics.__hctvChatMetrics ??= createMetricsStore());
|
||||
|
||||
export const chatMetricsRegistry = metrics.register;
|
||||
|
||||
export function recordChatConnectionAccepted(channel: string, authMethod: string): void {
|
||||
metrics.websocketConnectionAttempts.inc({
|
||||
auth_method: authMethod,
|
||||
outcome: 'accepted',
|
||||
reason: 'none',
|
||||
});
|
||||
metrics.websocketConnections.inc();
|
||||
metrics.websocketConnectionsByChannel.inc({ channel });
|
||||
metrics.websocketConnectionsByAuthMethod.inc({ auth_method: authMethod });
|
||||
}
|
||||
|
||||
export function recordChatConnectionRejected(authMethod: string, reason: string): void {
|
||||
metrics.websocketConnectionAttempts.inc({ auth_method: authMethod, outcome: 'rejected', reason });
|
||||
}
|
||||
|
||||
export function recordChatDisconnect(channel: string, authMethod: string): void {
|
||||
metrics.websocketConnections.dec();
|
||||
metrics.websocketConnectionsByChannel.dec({ channel });
|
||||
metrics.websocketConnectionsByAuthMethod.dec({ auth_method: authMethod });
|
||||
}
|
||||
|
||||
export function recordIncomingChatMessage(type: string, payloadBytes: number): void {
|
||||
metrics.incomingMessages.inc({ type });
|
||||
metrics.inboundPayloadBytes.inc({ type }, payloadBytes);
|
||||
}
|
||||
|
||||
export function startChatMessageTimer(type: string) {
|
||||
return metrics.messageDuration.startTimer({ type });
|
||||
}
|
||||
|
||||
export function recordDeliveredChatMessage(senderType: string): void {
|
||||
metrics.deliveredMessages.inc({ sender_type: senderType });
|
||||
}
|
||||
|
||||
export function recordDeliveredChatMessageBytes(senderType: string, bytes: number): void {
|
||||
metrics.deliveredMessageBytes.inc({ sender_type: senderType }, bytes);
|
||||
}
|
||||
|
||||
export function setChannelHistorySize(channel: string, size: number): void {
|
||||
metrics.channelHistorySize.set({ channel }, size);
|
||||
}
|
||||
|
||||
export function recordHistoryMessagesLoaded(channel: string, count: number): void {
|
||||
if (count > 0) {
|
||||
metrics.channelHistoryLoadedMessages.inc({ channel }, count);
|
||||
}
|
||||
}
|
||||
|
||||
export function setChatModerationState(
|
||||
channel: string,
|
||||
settings: {
|
||||
blockedTerms: number;
|
||||
maxMessageLength: number;
|
||||
rateLimitCount: number;
|
||||
rateLimitWindowSeconds: number;
|
||||
slowModeSeconds: number;
|
||||
}
|
||||
): void {
|
||||
metrics.moderationState.set({ channel, setting: 'blocked_terms' }, settings.blockedTerms);
|
||||
metrics.moderationState.set({ channel, setting: 'slow_mode_seconds' }, settings.slowModeSeconds);
|
||||
metrics.moderationState.set(
|
||||
{ channel, setting: 'max_message_length' },
|
||||
settings.maxMessageLength
|
||||
);
|
||||
metrics.moderationState.set({ channel, setting: 'rate_limit_count' }, settings.rateLimitCount);
|
||||
metrics.moderationState.set(
|
||||
{ channel, setting: 'rate_limit_window_seconds' },
|
||||
settings.rateLimitWindowSeconds
|
||||
);
|
||||
}
|
||||
|
||||
export function recordUniqueChatter(senderType: string): void {
|
||||
metrics.channelUniqueChatters.inc({ sender_type: senderType });
|
||||
}
|
||||
|
||||
export function recordChatModerationAction(action: string): void {
|
||||
metrics.moderationActions.inc({ action });
|
||||
}
|
||||
|
||||
export function recordChatModerationBlock(reason: string): void {
|
||||
metrics.moderationBlocks.inc({ reason });
|
||||
}
|
||||
|
||||
export function recordChatError(phase: string): void {
|
||||
metrics.errors.inc({ phase });
|
||||
}
|
||||
|
||||
export function recordEmojiSearchResults(outcome: string, count: number): void {
|
||||
metrics.emojiSearchResults.observe({ outcome }, count);
|
||||
}
|
||||
70
apps/chat/src/types/chat.ts
Normal file
70
apps/chat/src/types/chat.ts
Normal file
@@ -0,0 +1,70 @@
|
||||
import type { ModifiedWebSocket } from '@hctv/hono-ws';
|
||||
|
||||
export interface ChatUser {
|
||||
id: string;
|
||||
username: string;
|
||||
pfpUrl: string;
|
||||
displayName?: string;
|
||||
isBot: boolean;
|
||||
moderatorUserId: string;
|
||||
isPlatformAdmin: boolean;
|
||||
channelRole: 'owner' | 'manager' | 'chatModerator' | 'botModerator' | null;
|
||||
}
|
||||
|
||||
export interface ChatModerationSettingsShape {
|
||||
blockedTerms: string[];
|
||||
slowModeSeconds: number;
|
||||
maxMessageLength: number;
|
||||
rateLimitCount: number;
|
||||
rateLimitWindowSeconds: number;
|
||||
}
|
||||
|
||||
export interface ChatRestrictionState {
|
||||
type: 'timeout' | 'ban';
|
||||
reason: string;
|
||||
expiresAt: Date | null;
|
||||
}
|
||||
|
||||
export interface ChatSocket {
|
||||
readyState: number;
|
||||
OPEN: number;
|
||||
send: (data: string) => void;
|
||||
close: () => void;
|
||||
wss: {
|
||||
clients: Set<unknown>;
|
||||
};
|
||||
targetUsername?: string;
|
||||
channelId?: string;
|
||||
chatUser?: ChatUser | null;
|
||||
personalChannel?: any;
|
||||
viewerId?: string;
|
||||
isModerator?: boolean;
|
||||
metricsTracked?: boolean;
|
||||
metricsAuthMethod?: string;
|
||||
excludeFromViewerCount?: boolean;
|
||||
raw?:
|
||||
| (ModifiedWebSocket & {
|
||||
targetUsername?: string;
|
||||
channelId?: string;
|
||||
chatUser?: ChatUser | null;
|
||||
personalChannel?: any;
|
||||
isModerator?: boolean;
|
||||
metricsTracked?: boolean;
|
||||
metricsAuthMethod?: string;
|
||||
excludeFromViewerCount?: boolean;
|
||||
})
|
||||
| null;
|
||||
}
|
||||
|
||||
export type ChatModerationCommand = {
|
||||
type:
|
||||
| 'mod:deleteMessage'
|
||||
| 'mod:timeoutUser'
|
||||
| 'mod:banUser'
|
||||
| 'mod:unbanUser'
|
||||
| 'mod:liftTimeout';
|
||||
msgId?: string;
|
||||
targetUserId?: string;
|
||||
durationSeconds?: number;
|
||||
reason?: string;
|
||||
};
|
||||
411
apps/chat/src/utils/moderation.ts
Normal file
411
apps/chat/src/utils/moderation.ts
Normal file
@@ -0,0 +1,411 @@
|
||||
import { ChatModerationAction, prisma } from '@hctv/db';
|
||||
import { recordChatModerationAction } from '../metrics.js';
|
||||
import type {
|
||||
ChatModerationCommand,
|
||||
ChatRestrictionState,
|
||||
ChatSocket,
|
||||
ChatUser,
|
||||
} from '../types/chat.js';
|
||||
|
||||
const ROLE_RANK: Record<NonNullable<ChatUser['channelRole']> | '__none__', number> = {
|
||||
owner: 100,
|
||||
manager: 50,
|
||||
chatModerator: 10,
|
||||
botModerator: 10,
|
||||
__none__: 0,
|
||||
};
|
||||
|
||||
function roleRank(role: ChatUser['channelRole']): number {
|
||||
return role ? (ROLE_RANK[role] ?? 0) : ROLE_RANK.__none__;
|
||||
}
|
||||
|
||||
type ModerationContext = {
|
||||
chatUser: ChatUser;
|
||||
targetUsername: string;
|
||||
channelId: string;
|
||||
};
|
||||
|
||||
type DeleteMessageDeps = {
|
||||
deleteMessageFromHistory: (targetUsername: string, msgId: string) => Promise<boolean>;
|
||||
logModerationEvent: (payload: {
|
||||
action: ChatModerationAction;
|
||||
channelId: string;
|
||||
moderatorId: string;
|
||||
targetUserId?: string;
|
||||
reason?: string;
|
||||
details?: Record<string, unknown>;
|
||||
}) => Promise<void>;
|
||||
broadcastToChannel: (
|
||||
targetUsername: string,
|
||||
ws: ChatSocket,
|
||||
payload: Record<string, unknown>
|
||||
) => void;
|
||||
};
|
||||
|
||||
type UserRestrictionDeps = {
|
||||
logModerationEvent: (payload: {
|
||||
action: ChatModerationAction;
|
||||
channelId: string;
|
||||
moderatorId: string;
|
||||
targetUserId?: string;
|
||||
reason?: string;
|
||||
details?: Record<string, unknown>;
|
||||
}) => Promise<void>;
|
||||
broadcastRestrictionStateToUser: (
|
||||
targetUsername: string,
|
||||
targetUserId: string,
|
||||
channelId: string,
|
||||
ws: ChatSocket
|
||||
) => Promise<void>;
|
||||
broadcastToChannel: (
|
||||
targetUsername: string,
|
||||
ws: ChatSocket,
|
||||
payload: Record<string, unknown>
|
||||
) => void;
|
||||
};
|
||||
|
||||
export function sendModerationError(
|
||||
socket: ChatSocket,
|
||||
code: string,
|
||||
message: string,
|
||||
restriction?: ChatRestrictionState
|
||||
) {
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: 'moderationError',
|
||||
code,
|
||||
message,
|
||||
restriction,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
async function requireModerationContext(
|
||||
socket: ChatSocket,
|
||||
socketState: ChatSocket
|
||||
): Promise<ModerationContext | null> {
|
||||
if (!socketState.chatUser || !socketState.targetUsername || !socketState.channelId) {
|
||||
sendModerationError(socket, 'FORBIDDEN', 'You do not have permission to moderate this chat.');
|
||||
return null;
|
||||
}
|
||||
|
||||
const chatUser = socketState.chatUser;
|
||||
const channelId = socketState.channelId;
|
||||
|
||||
const [channel, moderatorRecord] = await Promise.all([
|
||||
prisma.channel.findUnique({
|
||||
where: { id: channelId },
|
||||
select: {
|
||||
ownerId: true,
|
||||
managers: { select: { id: true } },
|
||||
chatModerators: { select: { id: true } },
|
||||
chatModeratorBots: { select: { id: true } },
|
||||
},
|
||||
}),
|
||||
prisma.user.findUnique({
|
||||
where: { id: chatUser.moderatorUserId },
|
||||
select: { isAdmin: true },
|
||||
}),
|
||||
]);
|
||||
|
||||
if (!channel) {
|
||||
sendModerationError(socket, 'FORBIDDEN', 'You do not have permission to moderate this chat.');
|
||||
return null;
|
||||
}
|
||||
|
||||
const isPlatformAdmin = chatUser.isBot ? false : Boolean(moderatorRecord?.isAdmin);
|
||||
|
||||
let channelRole: ChatUser['channelRole'] = null;
|
||||
if (chatUser.isBot) {
|
||||
if (channel.chatModeratorBots.some((b) => b.id === chatUser.id)) {
|
||||
channelRole = 'botModerator';
|
||||
}
|
||||
} else if (channel.ownerId === chatUser.id) {
|
||||
channelRole = 'owner';
|
||||
} else if (channel.managers.some((m) => m.id === chatUser.id)) {
|
||||
channelRole = 'manager';
|
||||
} else if (channel.chatModerators.some((m) => m.id === chatUser.id)) {
|
||||
channelRole = 'chatModerator';
|
||||
}
|
||||
|
||||
const isModerator =
|
||||
isPlatformAdmin ||
|
||||
channelRole === 'owner' ||
|
||||
channelRole === 'manager' ||
|
||||
channelRole === 'chatModerator' ||
|
||||
channelRole === 'botModerator';
|
||||
|
||||
if (!isModerator) {
|
||||
sendModerationError(socket, 'FORBIDDEN', 'You do not have permission to moderate this chat.');
|
||||
return null;
|
||||
}
|
||||
|
||||
const resolvedChatUser: ChatUser = { ...chatUser, isPlatformAdmin, channelRole };
|
||||
|
||||
return {
|
||||
chatUser: resolvedChatUser,
|
||||
targetUsername: socketState.targetUsername,
|
||||
channelId,
|
||||
};
|
||||
}
|
||||
|
||||
async function resolveModerationTarget(
|
||||
socket: ChatSocket,
|
||||
actingModeratorUserId: string,
|
||||
rawTargetUserId: unknown,
|
||||
channelId: string
|
||||
) {
|
||||
const targetUserId = typeof rawTargetUserId === 'string' ? rawTargetUserId : '';
|
||||
|
||||
if (!targetUserId || targetUserId === actingModeratorUserId) {
|
||||
sendModerationError(socket, 'INVALID_TARGET', 'Invalid moderation target.');
|
||||
return null;
|
||||
}
|
||||
|
||||
const targetUserRecord = await prisma.user.findUnique({
|
||||
where: { id: targetUserId },
|
||||
select: {
|
||||
isAdmin: true,
|
||||
personalChannel: { select: { name: true } },
|
||||
ownedChannels: { where: { id: channelId }, select: { id: true } },
|
||||
managedChannels: { where: { id: channelId }, select: { id: true } },
|
||||
chatModeratedChannels: { where: { id: channelId }, select: { id: true } },
|
||||
},
|
||||
});
|
||||
|
||||
if (!targetUserRecord) {
|
||||
sendModerationError(socket, 'INVALID_TARGET', 'Target user no longer exists.');
|
||||
return null;
|
||||
}
|
||||
|
||||
let targetChannelRole: ChatUser['channelRole'] = null;
|
||||
if (targetUserRecord.ownedChannels.length > 0) {
|
||||
targetChannelRole = 'owner';
|
||||
} else if (targetUserRecord.managedChannels.length > 0) {
|
||||
targetChannelRole = 'manager';
|
||||
} else if (targetUserRecord.chatModeratedChannels.length > 0) {
|
||||
targetChannelRole = 'chatModerator';
|
||||
}
|
||||
|
||||
return {
|
||||
targetUserId,
|
||||
targetUserRecord,
|
||||
targetChannelRole,
|
||||
resolvedTargetUsername: targetUserRecord.personalChannel?.name ?? 'that user',
|
||||
};
|
||||
}
|
||||
|
||||
async function ensureAdminTargetModerationAllowed(
|
||||
socket: ChatSocket,
|
||||
actingModeratorUserId: string,
|
||||
targetIsAdmin: boolean
|
||||
) {
|
||||
if (!targetIsAdmin) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const actingUserRecord = await prisma.user.findUnique({
|
||||
where: { id: actingModeratorUserId },
|
||||
select: { isAdmin: true },
|
||||
});
|
||||
|
||||
if (!actingUserRecord?.isAdmin) {
|
||||
sendModerationError(
|
||||
socket,
|
||||
'FORBIDDEN',
|
||||
'Platform admins cannot be moderated via chat commands.'
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function ensureRoleHierarchyAllowed(
|
||||
socket: ChatSocket,
|
||||
actorRole: ChatUser['channelRole'],
|
||||
actorIsPlatformAdmin: boolean,
|
||||
targetRole: ChatUser['channelRole']
|
||||
): boolean {
|
||||
if (actorIsPlatformAdmin) return true;
|
||||
|
||||
if (roleRank(actorRole) <= roleRank(targetRole)) {
|
||||
sendModerationError(
|
||||
socket,
|
||||
'FORBIDDEN',
|
||||
'You cannot moderate a user with an equal or higher role than yours.'
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function handleDeleteMessageCommand(
|
||||
socket: ChatSocket,
|
||||
socketState: ChatSocket,
|
||||
msg: ChatModerationCommand,
|
||||
deps: DeleteMessageDeps
|
||||
) {
|
||||
const context = await requireModerationContext(socket, socketState);
|
||||
if (!context) {
|
||||
return;
|
||||
}
|
||||
|
||||
const msgId = typeof msg.msgId === 'string' ? msg.msgId : '';
|
||||
if (!msgId) {
|
||||
sendModerationError(socket, 'INVALID_REQUEST', 'Invalid message id.');
|
||||
return;
|
||||
}
|
||||
|
||||
const deleted = await deps.deleteMessageFromHistory(context.targetUsername, msgId);
|
||||
if (!deleted) {
|
||||
sendModerationError(socket, 'NOT_FOUND', 'Message not found.');
|
||||
return;
|
||||
}
|
||||
|
||||
await deps.logModerationEvent({
|
||||
action: ChatModerationAction.MESSAGE_DELETED,
|
||||
channelId: context.channelId,
|
||||
moderatorId: context.chatUser.moderatorUserId,
|
||||
reason: 'Message deleted by moderator',
|
||||
details: { msgId },
|
||||
});
|
||||
recordChatModerationAction('message_deleted');
|
||||
|
||||
deps.broadcastToChannel(context.targetUsername, socket, { type: 'messageDeleted', msgId });
|
||||
}
|
||||
|
||||
export async function handleUserRestrictionCommand(
|
||||
socket: ChatSocket,
|
||||
socketState: ChatSocket,
|
||||
msg: ChatModerationCommand,
|
||||
deps: UserRestrictionDeps
|
||||
) {
|
||||
const context = await requireModerationContext(socket, socketState);
|
||||
if (!context) {
|
||||
return;
|
||||
}
|
||||
|
||||
const actingModeratorUserId = context.chatUser.moderatorUserId;
|
||||
const target = await resolveModerationTarget(
|
||||
socket,
|
||||
actingModeratorUserId,
|
||||
msg.targetUserId,
|
||||
context.channelId
|
||||
);
|
||||
if (!target) {
|
||||
return;
|
||||
}
|
||||
|
||||
const canModerateTarget = await ensureAdminTargetModerationAllowed(
|
||||
socket,
|
||||
actingModeratorUserId,
|
||||
target.targetUserRecord.isAdmin
|
||||
);
|
||||
if (!canModerateTarget) {
|
||||
return;
|
||||
}
|
||||
|
||||
const hierarchyAllowed = ensureRoleHierarchyAllowed(
|
||||
socket,
|
||||
context.chatUser.channelRole,
|
||||
context.chatUser.isPlatformAdmin,
|
||||
target.targetChannelRole
|
||||
);
|
||||
if (!hierarchyAllowed) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (msg.type === 'mod:unbanUser' || msg.type === 'mod:liftTimeout') {
|
||||
await prisma.chatUserBan.deleteMany({
|
||||
where: {
|
||||
channelId: context.channelId,
|
||||
userId: target.targetUserId,
|
||||
},
|
||||
});
|
||||
|
||||
await deps.logModerationEvent({
|
||||
action: ChatModerationAction.USER_UNBANNED,
|
||||
channelId: context.channelId,
|
||||
moderatorId: actingModeratorUserId,
|
||||
targetUserId: target.targetUserId,
|
||||
reason: 'User unbanned in chat',
|
||||
});
|
||||
recordChatModerationAction('user_unbanned');
|
||||
|
||||
await deps.broadcastRestrictionStateToUser(
|
||||
context.targetUsername,
|
||||
target.targetUserId,
|
||||
context.channelId,
|
||||
socket
|
||||
);
|
||||
|
||||
deps.broadcastToChannel(context.targetUsername, socket, {
|
||||
type: 'systemMsg',
|
||||
message: `${target.resolvedTargetUsername} can chat again.`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const reason =
|
||||
typeof msg.reason === 'string' && msg.reason.trim().length > 0
|
||||
? msg.reason.trim().slice(0, 250)
|
||||
: msg.type === 'mod:timeoutUser'
|
||||
? 'Timed out by moderator'
|
||||
: 'Banned by moderator';
|
||||
const durationSeconds =
|
||||
msg.type === 'mod:timeoutUser'
|
||||
? Math.min(Math.max(Number(msg.durationSeconds) || 300, 10), 60 * 60 * 24)
|
||||
: null;
|
||||
const expiresAt = durationSeconds ? new Date(Date.now() + durationSeconds * 1000) : null;
|
||||
|
||||
await prisma.chatUserBan.upsert({
|
||||
where: {
|
||||
channelId_userId: {
|
||||
channelId: context.channelId,
|
||||
userId: target.targetUserId,
|
||||
},
|
||||
},
|
||||
create: {
|
||||
channelId: context.channelId,
|
||||
userId: target.targetUserId,
|
||||
bannedById: actingModeratorUserId,
|
||||
reason,
|
||||
expiresAt,
|
||||
},
|
||||
update: {
|
||||
bannedById: actingModeratorUserId,
|
||||
reason,
|
||||
expiresAt,
|
||||
},
|
||||
});
|
||||
|
||||
await deps.logModerationEvent({
|
||||
action:
|
||||
msg.type === 'mod:timeoutUser'
|
||||
? ChatModerationAction.USER_TIMEOUT
|
||||
: ChatModerationAction.USER_BANNED,
|
||||
channelId: context.channelId,
|
||||
moderatorId: actingModeratorUserId,
|
||||
targetUserId: target.targetUserId,
|
||||
reason,
|
||||
details: durationSeconds ? { durationSeconds } : undefined,
|
||||
});
|
||||
recordChatModerationAction(msg.type === 'mod:timeoutUser' ? 'user_timeout' : 'user_banned');
|
||||
|
||||
await deps.broadcastRestrictionStateToUser(
|
||||
context.targetUsername,
|
||||
target.targetUserId,
|
||||
context.channelId,
|
||||
socket
|
||||
);
|
||||
|
||||
deps.broadcastToChannel(context.targetUsername, socket, {
|
||||
type: 'systemMsg',
|
||||
message:
|
||||
msg.type === 'mod:timeoutUser'
|
||||
? `${target.resolvedTargetUsername} was timed out for ${durationSeconds}s.`
|
||||
: `${target.resolvedTargetUsername} was banned.`,
|
||||
});
|
||||
}
|
||||
@@ -21,64 +21,235 @@ Bot accounts are now supported. You can choose to connect as a bot by providing
|
||||
**Security Note:** When using the `?botAuth=` query parameter, be aware that query parameters may be logged in server logs, and/or proxy logs. Use the `Authorization` header method whenever possible. The query parameter method should only be used when connecting from an environment where headers cannot be set.
|
||||
|
||||
It is highly advised to use a bot account for any automated task, and to implement anything pointed out in this page.
|
||||
|
||||
</Aside>
|
||||
|
||||
Once connected, you must implement a subroutine in your code to send ping messages every about 5 seconds. This is because of Cloudflare limitations.
|
||||
|
||||
Messages are sent and received in JSON format. The following message types are supported:
|
||||
|
||||
- `session`: sent by the server immediately upon connection.
|
||||
- received by client:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "session",
|
||||
"viewer": {
|
||||
"id": "user_id",
|
||||
"username": "your_username"
|
||||
},
|
||||
"permissions": {
|
||||
"canModerate": false
|
||||
},
|
||||
"moderation": {
|
||||
"hasBlockedTerms": false,
|
||||
"slowModeSeconds": 0,
|
||||
"maxMessageLength": 400
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`viewer` is `null` for unauthenticated (grant-only) connections. `canModerate` is `true` for channel owners, managers, moderators, and platform admins.
|
||||
|
||||
- `chatAccess`: sent by the server on connect (for authenticated non-bot users) and whenever a user's restriction state changes.
|
||||
- received by client:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "chatAccess",
|
||||
"canSend": true,
|
||||
"restriction": null
|
||||
}
|
||||
```
|
||||
|
||||
When the user is restricted, `canSend` is `false` and `restriction` contains:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "timeout",
|
||||
"reason": "Timed out by moderator",
|
||||
"expiresAt": "2026-01-01T00:00:00.000Z"
|
||||
}
|
||||
```
|
||||
|
||||
`type` is either `"timeout"` or `"ban"`. `expiresAt` is an ISO 8601 string for timeouts, or `null` for permanent bans.
|
||||
|
||||
- `ping`: a ping message to keep the connection alive.
|
||||
- sent by client:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "ping"
|
||||
}
|
||||
```
|
||||
|
||||
- received by client:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "pong"
|
||||
}
|
||||
```
|
||||
|
||||
- `message`: a chat message.
|
||||
- sent by client:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "message",
|
||||
"message": "Hello, world!"
|
||||
}
|
||||
```
|
||||
- received by client:
|
||||
|
||||
- received by client (broadcast to all viewers of the channel):
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "message",
|
||||
"msgId": "uuid-v4",
|
||||
"user": {
|
||||
"id": "user_id",
|
||||
"username": "user_who_sent_message",
|
||||
"avatar": "https://emoji.slack-edge.com/avatar.png"
|
||||
"pfpUrl": "https://example.com/avatar.png",
|
||||
"displayName": "Display Name",
|
||||
"isBot": false,
|
||||
"isPlatformAdmin": false,
|
||||
"channelRole": null
|
||||
},
|
||||
"message": "Hello, world!"
|
||||
}
|
||||
```
|
||||
- `ping`: a ping message to keep the connection alive.
|
||||
- sent by client:
|
||||
```json
|
||||
{
|
||||
"type": "ping"
|
||||
}
|
||||
```
|
||||
- received by client:
|
||||
```json
|
||||
{
|
||||
"type": "pong"
|
||||
}
|
||||
```
|
||||
- `history`: a message containing the chat history. This is sent upon connection.
|
||||
|
||||
`channelRole` is one of `"owner"`, `"manager"`, `"chatModerator"`, `"botModerator"`, or `null`. `displayName` may be `undefined` for regular users.
|
||||
|
||||
- `history`: the recent chat history, sent upon connection.
|
||||
- received by client:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "history",
|
||||
"messages": [
|
||||
{
|
||||
"type": "message",
|
||||
"msgId": "uuid-v4",
|
||||
"user": {
|
||||
"id": "user_id",
|
||||
"username": "user_who_sent_message",
|
||||
"avatar": "https://emoji.slack-edge.com/avatar.png"
|
||||
"pfpUrl": "https://example.com/avatar.png",
|
||||
"displayName": "Display Name",
|
||||
"isBot": false,
|
||||
"isPlatformAdmin": false,
|
||||
"channelRole": null
|
||||
},
|
||||
"message": "Hello, world!",
|
||||
"type": "message",
|
||||
},
|
||||
...
|
||||
"message": "Hello, world!"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Up to 100 messages are returned. Each message has the same shape as a received `message` event.
|
||||
|
||||
- `systemMsg`: a system notification broadcast to all viewers, e.g. when a user is banned or unbanned.
|
||||
- received by client:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "systemMsg",
|
||||
"message": "username was banned."
|
||||
}
|
||||
```
|
||||
|
||||
- `moderationError`: sent to the acting client when a message or moderation action is rejected.
|
||||
- received by client:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "moderationError",
|
||||
"code": "RATE_LIMIT",
|
||||
"message": "You are sending messages too fast.",
|
||||
"restriction": null
|
||||
}
|
||||
```
|
||||
|
||||
`restriction` is only present (non-null) for `TIMED_OUT` and `BANNED` codes, and has the same shape as the `restriction` field in `chatAccess`. Possible codes:
|
||||
|
||||
| Code | Trigger |
|
||||
| ------------------ | ---------------------------------------------- |
|
||||
| `FORBIDDEN` | Not permitted to perform the action |
|
||||
| `RATE_LIMIT` | Too many messages in the rate limit window |
|
||||
| `SLOW_MODE` | Sent before the slow mode cooldown expired |
|
||||
| `TIMED_OUT` | User is currently timed out |
|
||||
| `BANNED` | User is permanently banned |
|
||||
| `MESSAGE_TOO_LONG` | Message exceeds `maxMessageLength` |
|
||||
| `BLOCKED_TERM` | Message contains a blocked term |
|
||||
| `INVALID_TARGET` | Moderation target is invalid or does not exist |
|
||||
| `INVALID_REQUEST` | Malformed moderation command |
|
||||
| `NOT_FOUND` | Target message not found (delete) |
|
||||
|
||||
## Moderation commands
|
||||
|
||||
moderation commands are only available to authenticated users with the `canModerate` permission (`owner`, `manager`, `chatModerator`, `botModerator`, or platform admin). sending any of these without permission returns a `moderationError` with code `FORBIDDEN`.
|
||||
|
||||
obviously, role hierarchy is enforced: a `chatModerator` cannot moderate a `manager` or `owner`. Platform admins bypass hierarchy checks entirely.
|
||||
|
||||
- `mod:deleteMessage`: delete a message from the chat history and broadcast its removal.
|
||||
- sent by client:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "mod:deleteMessage",
|
||||
"msgId": "uuid-of-message-to-delete"
|
||||
}
|
||||
```
|
||||
|
||||
- received by all clients on success:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "messageDeleted",
|
||||
"msgId": "uuid-of-message-to-delete"
|
||||
}
|
||||
```
|
||||
|
||||
- `mod:timeoutUser`: temporarily restrict a user from sending messages.
|
||||
- sent by client:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "mod:timeoutUser",
|
||||
"targetUserId": "user_id",
|
||||
"durationSeconds": 300,
|
||||
"reason": "Optional reason"
|
||||
}
|
||||
```
|
||||
|
||||
`durationSeconds` is clamped between 10 and 86400 (24 hours). Defaults to 300 if omitted. On success, a `systemMsg` is broadcast and the target receives a `chatAccess` update.
|
||||
|
||||
- `mod:banUser`: permanently ban a user from sending messages.
|
||||
- sent by client:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "mod:banUser",
|
||||
"targetUserId": "user_id",
|
||||
"reason": "Optional reason"
|
||||
}
|
||||
```
|
||||
|
||||
On success, a `systemMsg` is broadcast and the target receives a `chatAccess` update.
|
||||
|
||||
- `mod:liftTimeout` / `mod:unbanUser`: remove an active timeout or ban.
|
||||
- sent by client:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "mod:liftTimeout",
|
||||
"targetUserId": "user_id"
|
||||
}
|
||||
```
|
||||
|
||||
Both types behave identically and remove any active restriction for the target user. On success, a `systemMsg` is broadcast and the target receives a `chatAccess` update with `canSend: true`.
|
||||
|
||||
## Emoji handling
|
||||
|
||||
_diagram source: devin deepwiki_
|
||||
@@ -119,22 +290,29 @@ The server then checks Redis for the emoji URL and returns it.
|
||||
|
||||
When a user wants to look up an emoji (by typing `:(partial name)`), the server uses uFuzzy to find matching emojis in the Redis `emojis` hash key and returns the results.
|
||||
|
||||
<Aside type="caution">
|
||||
`emojiMsg` and `emojiSearch` require an authenticated connection. They are not available to
|
||||
grant-only (OBS) viewers.
|
||||
</Aside>
|
||||
|
||||
Here's what gets sent on the websocket:
|
||||
|
||||
- `emojiMsg`: Looks up emojis
|
||||
- sent by client:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "emojiMsg",
|
||||
"emojis": ["aga", "yapa", "heavysob", "yay", "yay-bounce"]
|
||||
}
|
||||
```
|
||||
|
||||
- received by client:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "emojiMsgResponse",
|
||||
"emojis": {
|
||||
// rough example of urls
|
||||
"aga": "https://emoji.slack-edge.com/aga.png",
|
||||
"yapa": "https://emoji.slack-edge.com/yapa.png",
|
||||
"heavysob": "https://emoji.slack-edge.com/heavysob.png",
|
||||
@@ -143,20 +321,23 @@ Here's what gets sent on the websocket:
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- `emojiSearch`: Searches for emojis
|
||||
- sent by client:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "emojiSearch",
|
||||
"searchTerm": "aga"
|
||||
}
|
||||
```
|
||||
|
||||
- received by client:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "emojiSearchResponse",
|
||||
"results": [
|
||||
// real results btw
|
||||
"aga",
|
||||
"aga-brick-throw",
|
||||
"aga-dance",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
FROM node:lts-slim AS base
|
||||
FROM node:22-slim AS base
|
||||
ENV PNPM_HOME="/pnpm"
|
||||
ENV PATH="$PNPM_HOME:$PATH"
|
||||
RUN corepack enable
|
||||
@@ -24,6 +24,7 @@ RUN turbo prune @hctv/web --docker
|
||||
FROM base AS installer
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
git \
|
||||
curl \
|
||||
libvips-dev \
|
||||
python3 \
|
||||
make \
|
||||
@@ -38,12 +39,32 @@ WORKDIR /app
|
||||
COPY --from=builder /app/out/json/ .
|
||||
RUN pnpm install --frozen-lockfile
|
||||
|
||||
# Install a standalone Prisma CLI for runtime migrations (no pnpm symlinks).
|
||||
RUN mkdir -p /opt/prisma-cli && cd /opt/prisma-cli && npm init -y && npm install prisma@6.5.0
|
||||
|
||||
COPY --from=builder /app/out/full/ .
|
||||
|
||||
# Generate latest emojis.json during image build.
|
||||
RUN ARCH=$(dpkg --print-architecture) && \
|
||||
if [ "$ARCH" = "amd64" ]; then EMOJI_ARCH="x86_64"; \
|
||||
elif [ "$ARCH" = "arm64" ]; then EMOJI_ARCH="aarch64"; \
|
||||
else EMOJI_ARCH=""; fi && \
|
||||
RELEASE_JSON=$(curl -fsSL https://api.github.com/repos/srizan10/hctv/releases/latest || true) && \
|
||||
RELEASE_URL=$(printf '%s' "$RELEASE_JSON" | grep "browser_download_url.*slack-import-emojis-linux-${EMOJI_ARCH}" | cut -d '"' -f 4 || true) && \
|
||||
if [ -n "$RELEASE_URL" ] && \
|
||||
curl -fsSL -o /tmp/slack-import-emojis-bin "$RELEASE_URL" && \
|
||||
chmod +x /tmp/slack-import-emojis-bin && \
|
||||
/tmp/slack-import-emojis-bin default; then \
|
||||
cp /app/emojis.json /app/apps/web/emojis.json; \
|
||||
else \
|
||||
cp /app/apps/web/src/lib/instrumentation/emojis.json /app/apps/web/emojis.json; \
|
||||
fi
|
||||
|
||||
RUN --mount=type=secret,id=TURBO_TOKEN --mount=type=secret,id=TURBO_TEAM --mount=type=secret,id=SENTRY_AUTH_TOKEN \
|
||||
COMMIT=$(cat /tmp/commit_hash 2>/dev/null || echo "unknown") && \
|
||||
TURBO_TOKEN=$(cat /run/secrets/TURBO_TOKEN) TURBO_TEAM=$(cat /run/secrets/TURBO_TEAM) \
|
||||
SENTRY_AUTH_TOKEN=$(cat /run/secrets/SENTRY_AUTH_TOKEN) \
|
||||
commit=$COMMIT yarn turbo run build --env-mode=loose
|
||||
commit=$COMMIT pnpm turbo run build --env-mode=loose
|
||||
|
||||
FROM base AS runner
|
||||
WORKDIR /app
|
||||
@@ -54,20 +75,20 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
RUN groupadd --system --gid 1001 nodejs
|
||||
RUN useradd --system --uid 1001 nextjs
|
||||
RUN useradd --system --uid 1001 nextjs --create-home
|
||||
|
||||
# Copy Prisma files for migrations
|
||||
COPY --from=installer --chown=nextjs:nodejs /app/packages/db/prisma ./packages/db/prisma
|
||||
COPY --from=installer --chown=nextjs:nodejs /app/packages/db/generated ./packages/db/generated
|
||||
COPY --from=installer --chown=nextjs:nodejs /app/packages/db/package.json ./packages/db/package.json
|
||||
COPY --from=installer --chown=nextjs:nodejs /app/node_modules ./node_modules
|
||||
# Ensure home directory and cache directories have proper permissions
|
||||
RUN mkdir -p /home/nextjs/.cache && \
|
||||
chown -R nextjs:nodejs /home/nextjs
|
||||
|
||||
COPY --from=installer /tmp/commit_hash /tmp/commit_hash
|
||||
RUN COMMIT_VALUE=$(cat /tmp/commit_hash 2>/dev/null || echo "unknown") && \
|
||||
echo "#!/bin/sh" > /usr/local/bin/start.sh && \
|
||||
echo "set -e" >> /usr/local/bin/start.sh && \
|
||||
echo "export COREPACK_ENABLE_DOWNLOAD_PROMPT=0" >> /usr/local/bin/start.sh && \
|
||||
echo "export HOME=/home/nextjs" >> /usr/local/bin/start.sh && \
|
||||
echo "echo 'Running database migrations...'" >> /usr/local/bin/start.sh && \
|
||||
echo "pnpm prisma migrate deploy --schema=/app/packages/db/prisma/schema.prisma" >> /usr/local/bin/start.sh && \
|
||||
echo "node /opt/prisma-cli/node_modules/prisma/build/index.js migrate deploy --schema /app/packages/db/prisma/schema.prisma" >> /usr/local/bin/start.sh && \
|
||||
echo "cd /app" >> /usr/local/bin/start.sh && \
|
||||
echo "export commit=$COMMIT_VALUE" >> /usr/local/bin/start.sh && \
|
||||
echo "echo 'Starting Next.js application...'" >> /usr/local/bin/start.sh && \
|
||||
@@ -81,6 +102,10 @@ USER nextjs
|
||||
COPY --from=installer --chown=nextjs:nodejs /app/apps/web/.next/standalone ./
|
||||
COPY --from=installer --chown=nextjs:nodejs /app/apps/web/.next/static ./apps/web/.next/static
|
||||
COPY --from=installer --chown=nextjs:nodejs /app/apps/web/public ./apps/web/public
|
||||
COPY --chown=nextjs:nodejs apps/web/emojis.json .
|
||||
|
||||
CMD ["/usr/local/bin/start.sh"]
|
||||
COPY --from=installer --chown=nextjs:nodejs /app/apps/web/emojis.json ./emojis.json
|
||||
|
||||
# Copy Prisma schema and migrations for prisma migrate deploy
|
||||
COPY --from=installer --chown=nextjs:nodejs /app/packages/db/prisma ./packages/db/prisma
|
||||
COPY --from=installer --chown=nextjs:nodejs /opt/prisma-cli /opt/prisma-cli
|
||||
|
||||
CMD ["/usr/local/bin/start.sh"]
|
||||
|
||||
@@ -48,6 +48,7 @@
|
||||
"clsx": "^2.1.0",
|
||||
"cmdk": "1.0.0",
|
||||
"date-fns": "^4.1.0",
|
||||
"embla-carousel-react": "^8.6.0",
|
||||
"hls-video-element": "^1.5.0",
|
||||
"hls.js": "^1.6.15",
|
||||
"lucia": "^3.2.2",
|
||||
@@ -59,6 +60,7 @@
|
||||
"nuqs": "^2.4.3",
|
||||
"pg": "^8.14.1",
|
||||
"pg-boss": "^10.1.6",
|
||||
"prom-client": "^15.1.3",
|
||||
"react": "^19.2.3",
|
||||
"react-day-picker": "^9.13.0",
|
||||
"react-dom": "^19.2.3",
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,559 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { format, formatDistanceToNow } from 'date-fns';
|
||||
import { toast } from 'sonner';
|
||||
import {
|
||||
ArrowLeft,
|
||||
Gavel,
|
||||
Flag,
|
||||
User,
|
||||
MessageSquare,
|
||||
Clock,
|
||||
ShieldAlert,
|
||||
ShieldOff,
|
||||
ShieldCheck,
|
||||
Trash2,
|
||||
CheckCircle2,
|
||||
XCircle,
|
||||
AlertTriangle,
|
||||
Timer,
|
||||
Ban,
|
||||
Unlock,
|
||||
Info,
|
||||
} from 'lucide-react';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
type ReportModerationAction =
|
||||
| 'review'
|
||||
| 'dismiss'
|
||||
| 'delete_reported_message'
|
||||
| 'timeout_10m'
|
||||
| 'timeout_1h'
|
||||
| 'ban_chat'
|
||||
| 'lift_chat_ban'
|
||||
| 'ban_platform'
|
||||
| 'unban_platform';
|
||||
|
||||
type ActionSeverity = 'info' | 'moderate' | 'severe';
|
||||
|
||||
interface ActionOption {
|
||||
value: ReportModerationAction;
|
||||
label: string;
|
||||
description: string;
|
||||
severity: ActionSeverity;
|
||||
requiresNote?: boolean;
|
||||
icon: React.ReactNode;
|
||||
}
|
||||
|
||||
const ACTION_OPTIONS: ActionOption[] = [
|
||||
{
|
||||
value: 'review',
|
||||
label: 'Mark as reviewed',
|
||||
description: 'Acknowledge the report without further action.',
|
||||
severity: 'info',
|
||||
icon: <CheckCircle2 className="h-4 w-4" />,
|
||||
},
|
||||
{
|
||||
value: 'dismiss',
|
||||
label: 'Dismiss',
|
||||
description: 'Close this report as unfounded or resolved.',
|
||||
severity: 'info',
|
||||
icon: <XCircle className="h-4 w-4" />,
|
||||
},
|
||||
{
|
||||
value: 'delete_reported_message',
|
||||
label: 'Delete message',
|
||||
description: 'Remove the reported message from the chat.',
|
||||
severity: 'moderate',
|
||||
requiresNote: true,
|
||||
icon: <Trash2 className="h-4 w-4" />,
|
||||
},
|
||||
{
|
||||
value: 'timeout_10m',
|
||||
label: 'Timeout 10 minutes',
|
||||
description: 'Prevent user from chatting for 10 minutes.',
|
||||
severity: 'moderate',
|
||||
requiresNote: true,
|
||||
icon: <Timer className="h-4 w-4" />,
|
||||
},
|
||||
{
|
||||
value: 'timeout_1h',
|
||||
label: 'Timeout 1 hour',
|
||||
description: 'Prevent user from chatting for 1 hour.',
|
||||
severity: 'moderate',
|
||||
requiresNote: true,
|
||||
icon: <Timer className="h-4 w-4" />,
|
||||
},
|
||||
{
|
||||
value: 'ban_chat',
|
||||
label: 'Ban from chat',
|
||||
description: 'Permanently ban user from chat.',
|
||||
severity: 'severe',
|
||||
requiresNote: true,
|
||||
icon: <Ban className="h-4 w-4" />,
|
||||
},
|
||||
{
|
||||
value: 'lift_chat_ban',
|
||||
label: 'Lift chat ban',
|
||||
description: 'Restore chat access for this user.',
|
||||
severity: 'info',
|
||||
requiresNote: true,
|
||||
icon: <Unlock className="h-4 w-4" />,
|
||||
},
|
||||
{
|
||||
value: 'ban_platform',
|
||||
label: 'Ban from platform',
|
||||
description: 'Permanently ban user from the entire platform.',
|
||||
severity: 'severe',
|
||||
requiresNote: true,
|
||||
icon: <ShieldOff className="h-4 w-4" />,
|
||||
},
|
||||
{
|
||||
value: 'unban_platform',
|
||||
label: 'Unban from platform',
|
||||
description: 'Restore platform access for this user.',
|
||||
severity: 'info',
|
||||
requiresNote: true,
|
||||
icon: <ShieldCheck className="h-4 w-4" />,
|
||||
},
|
||||
];
|
||||
|
||||
const SEVERITY_STYLES: Record<
|
||||
ActionSeverity,
|
||||
{ card: string; selected: string; icon: string; ring: string }
|
||||
> = {
|
||||
info: {
|
||||
card: 'border-border hover:border-muted-foreground/40 hover:bg-muted/30',
|
||||
selected: 'border-primary bg-primary/5',
|
||||
icon: 'text-muted-foreground',
|
||||
ring: 'ring-primary/30',
|
||||
},
|
||||
moderate: {
|
||||
card: 'border-border hover:border-amber-500/40 hover:bg-amber-500/5',
|
||||
selected: 'border-amber-500 bg-amber-500/5',
|
||||
icon: 'text-amber-500',
|
||||
ring: 'ring-amber-500/30',
|
||||
},
|
||||
severe: {
|
||||
card: 'border-border hover:border-destructive/40 hover:bg-destructive/5',
|
||||
selected: 'border-destructive bg-destructive/5',
|
||||
icon: 'text-destructive',
|
||||
ring: 'ring-destructive/30',
|
||||
},
|
||||
};
|
||||
|
||||
const STATUS_CONFIG = {
|
||||
OPEN: { label: 'Open', variant: 'destructive' as const, icon: <Flag className="h-3 w-3" /> },
|
||||
REVIEWED: {
|
||||
label: 'Reviewed',
|
||||
variant: 'secondary' as const,
|
||||
icon: <CheckCircle2 className="h-3 w-3" />,
|
||||
},
|
||||
DISMISSED: {
|
||||
label: 'Dismissed',
|
||||
variant: 'outline' as const,
|
||||
icon: <XCircle className="h-3 w-3" />,
|
||||
},
|
||||
};
|
||||
|
||||
const ACTION_LABELS: Record<NonNullable<ChatReportCase['lastAction']>, string> = {
|
||||
REVIEW: 'Marked as reviewed',
|
||||
DISMISS: 'Dismissed',
|
||||
DELETE_REPORTED_MESSAGE: 'Message deleted',
|
||||
TIMEOUT_10M: 'User timed out (10m)',
|
||||
TIMEOUT_1H: 'User timed out (1h)',
|
||||
BAN_CHAT: 'Chat banned',
|
||||
LIFT_CHAT_BAN: 'Chat ban lifted',
|
||||
BAN_PLATFORM: 'Platform banned',
|
||||
UNBAN_PLATFORM: 'Platform ban lifted',
|
||||
};
|
||||
|
||||
function InfoRow({ label, children }: { label: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<span className="text-[11px] font-medium uppercase tracking-wider text-muted-foreground">
|
||||
{label}
|
||||
</span>
|
||||
<span className="text-sm">{children}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SectionLabel({ icon, children }: { icon: React.ReactNode; children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="flex items-center gap-2 mb-3">
|
||||
<span className="text-muted-foreground">{icon}</span>
|
||||
<span className="text-xs font-semibold uppercase tracking-widest text-muted-foreground">
|
||||
{children}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function ReportCasePageClient({ report }: ReportCasePageClientProps) {
|
||||
const router = useRouter();
|
||||
const [selectedAction, setSelectedAction] = useState<ReportModerationAction>('review');
|
||||
const [note, setNote] = useState('');
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
|
||||
const selectedMeta = ACTION_OPTIONS.find((o) => o.value === selectedAction)!;
|
||||
const requiresNote = Boolean(selectedMeta?.requiresNote);
|
||||
const isSevere = selectedMeta?.severity === 'severe';
|
||||
|
||||
const statusConfig = STATUS_CONFIG[report.status];
|
||||
|
||||
const submitAction = async () => {
|
||||
if (requiresNote && note.trim().length < 10) {
|
||||
toast.error('Please include at least 10 characters for enforcement context.');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSubmitting(true);
|
||||
try {
|
||||
const res = await fetch('/api/admin/reports', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
reportId: report.id,
|
||||
action: selectedAction,
|
||||
note: note.trim() || undefined,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const errorText = await res.text();
|
||||
toast.error(errorText || 'Failed to apply action');
|
||||
return;
|
||||
}
|
||||
|
||||
toast.success('Report action applied');
|
||||
setNote('');
|
||||
router.refresh();
|
||||
} catch {
|
||||
toast.error('Failed to apply action');
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const actionGroups: Array<{ label: string; actions: ActionOption[] }> = [
|
||||
{
|
||||
label: 'Informational',
|
||||
actions: ACTION_OPTIONS.filter((a) => a.severity === 'info'),
|
||||
},
|
||||
{
|
||||
label: 'Moderation',
|
||||
actions: ACTION_OPTIONS.filter((a) => a.severity === 'moderate'),
|
||||
},
|
||||
{
|
||||
label: 'Severe',
|
||||
actions: ACTION_OPTIONS.filter((a) => a.severity === 'severe'),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="container max-w-5xl mx-auto py-8 px-4">
|
||||
<div className="flex items-start justify-between gap-4 mb-8">
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-center gap-3">
|
||||
<h1 className="text-2xl font-bold tracking-tight">Report Case</h1>
|
||||
<Badge
|
||||
variant={statusConfig.variant}
|
||||
className="flex items-center gap-1.5 text-xs px-2 py-0.5"
|
||||
>
|
||||
{statusConfig.icon}
|
||||
{statusConfig.label}
|
||||
</Badge>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground font-mono">{report.id}</p>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => router.push(`/admin?tab=reports&reportId=${report.id}`)}
|
||||
className="shrink-0 gap-1.5"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
Back to reports
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-5 gap-6">
|
||||
<div className="md:col-span-3 space-y-5">
|
||||
{report.reportedMessage ? (
|
||||
<div className="rounded-lg border border-border bg-muted/20 overflow-hidden">
|
||||
<div className="px-4 py-3 border-b border-border bg-muted/30 flex items-center gap-2">
|
||||
<MessageSquare className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
<span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
|
||||
Reported message
|
||||
</span>
|
||||
</div>
|
||||
<div className="px-4 py-4">
|
||||
<p className="text-sm leading-relaxed break-words">{report.reportedMessage}</p>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="rounded-lg border border-dashed border-border px-4 py-5 flex items-center gap-3 text-muted-foreground">
|
||||
<Info className="h-4 w-4 shrink-0" />
|
||||
<span className="text-sm">No message content was captured with this report.</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="rounded-lg border border-border overflow-hidden">
|
||||
<div className="px-4 py-3 border-b border-border bg-muted/20">
|
||||
<SectionLabel icon={<User className="h-3.5 w-3.5" />}>Parties</SectionLabel>
|
||||
</div>
|
||||
<div className="px-4 py-4 grid grid-cols-2 gap-x-6 gap-y-4">
|
||||
<InfoRow label="Reporter">
|
||||
<span className="font-medium">{report.reporter}</span>
|
||||
</InfoRow>
|
||||
<InfoRow label="Target">
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
<span className="font-medium">{report.target}</span>
|
||||
{report.targetIsAdmin && (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="text-[10px] py-0 px-1.5 text-amber-500 border-amber-500/40"
|
||||
>
|
||||
Admin
|
||||
</Badge>
|
||||
)}
|
||||
{report.targetIsPlatformBanned && (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="text-[10px] py-0 px-1.5 text-destructive border-destructive/40"
|
||||
>
|
||||
Platform banned
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</InfoRow>
|
||||
<InfoRow label="Channel">
|
||||
<span className="font-mono text-xs bg-muted px-1.5 py-0.5 rounded">
|
||||
{report.channelName}
|
||||
</span>
|
||||
</InfoRow>
|
||||
<InfoRow label="Reason">
|
||||
<span>{report.reason}</span>
|
||||
</InfoRow>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="rounded-lg border border-border overflow-hidden">
|
||||
<div className="px-4 py-3 border-b border-border bg-muted/20">
|
||||
<SectionLabel icon={<Clock className="h-3.5 w-3.5" />}>Timeline</SectionLabel>
|
||||
</div>
|
||||
<div className="px-4 py-4 space-y-4">
|
||||
<InfoRow label="Filed">
|
||||
<span>
|
||||
{format(new Date(report.createdAt), 'PPP p')}{' '}
|
||||
<span className="text-muted-foreground text-xs">
|
||||
({formatDistanceToNow(new Date(report.createdAt), { addSuffix: true })})
|
||||
</span>
|
||||
</span>
|
||||
</InfoRow>
|
||||
{report.handledAt ? (
|
||||
<InfoRow label="Last handled">
|
||||
<span>
|
||||
{format(new Date(report.handledAt), 'PPP p')}{' '}
|
||||
<span className="text-muted-foreground text-xs">
|
||||
({formatDistanceToNow(new Date(report.handledAt), { addSuffix: true })})
|
||||
</span>
|
||||
</span>
|
||||
</InfoRow>
|
||||
) : null}
|
||||
<InfoRow label="Last action">
|
||||
{report.lastAction ? (
|
||||
<span className="font-medium">{ACTION_LABELS[report.lastAction]}</span>
|
||||
) : (
|
||||
<span className="text-muted-foreground">None</span>
|
||||
)}
|
||||
</InfoRow>
|
||||
<InfoRow label="Handled by">
|
||||
{report.handledBy ? (
|
||||
<span className="font-medium">{report.handledBy}</span>
|
||||
) : (
|
||||
<span className="text-muted-foreground">—</span>
|
||||
)}
|
||||
</InfoRow>
|
||||
{report.handlingNote ? (
|
||||
<div className="pt-1">
|
||||
<span className="text-[11px] font-medium uppercase tracking-wider text-muted-foreground block mb-1.5">
|
||||
Last note
|
||||
</span>
|
||||
<p className="text-sm bg-muted/40 rounded-md px-3 py-2.5 leading-relaxed border border-border">
|
||||
{report.handlingNote}
|
||||
</p>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{report.targetIsAdmin && (
|
||||
<div className="flex items-start gap-3 rounded-lg border border-amber-500/30 bg-amber-500/5 px-4 py-3">
|
||||
<AlertTriangle className="h-4 w-4 text-amber-500 shrink-0 mt-0.5" />
|
||||
<div className="text-sm text-amber-700 dark:text-amber-400 leading-snug">
|
||||
<span className="font-semibold">Caution:</span> The reported user is a platform
|
||||
admin. Enforcement actions will still apply.
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="md:col-span-2">
|
||||
<div className="rounded-lg border border-border overflow-hidden sticky top-6">
|
||||
<div className="px-4 py-3 border-b border-border bg-muted/20 flex items-center gap-2">
|
||||
<Gavel className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
<span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
|
||||
Enforcement
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="px-4 py-4 space-y-5">
|
||||
{/* Action selector */}
|
||||
<div className="space-y-3">
|
||||
{actionGroups.map((group) => (
|
||||
<div key={group.label}>
|
||||
<p className="text-[10px] font-semibold uppercase tracking-widest text-muted-foreground mb-2">
|
||||
{group.label}
|
||||
</p>
|
||||
<div className="space-y-1.5">
|
||||
{group.actions.map((action) => {
|
||||
const isSelected = selectedAction === action.value;
|
||||
const styles = SEVERITY_STYLES[action.severity];
|
||||
return (
|
||||
<button
|
||||
key={action.value}
|
||||
type="button"
|
||||
onClick={() => setSelectedAction(action.value)}
|
||||
className={cn(
|
||||
'w-full flex items-start gap-3 rounded-md border px-3 py-2.5 text-left transition-all cursor-pointer',
|
||||
isSelected ? `${styles.selected} ring-1 ${styles.ring}` : styles.card
|
||||
)}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
'mt-0.5 shrink-0',
|
||||
isSelected ? styles.icon : 'text-muted-foreground'
|
||||
)}
|
||||
>
|
||||
{action.icon}
|
||||
</span>
|
||||
<div className="min-w-0">
|
||||
<p
|
||||
className={cn(
|
||||
'text-sm font-medium leading-tight',
|
||||
isSelected && action.severity === 'severe' && 'text-destructive',
|
||||
isSelected &&
|
||||
action.severity === 'moderate' &&
|
||||
'text-amber-600 dark:text-amber-400'
|
||||
)}
|
||||
>
|
||||
{action.label}
|
||||
</p>
|
||||
<p className="text-[11px] text-muted-foreground mt-0.5 leading-snug">
|
||||
{action.description}
|
||||
</p>
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="note" className="text-xs">
|
||||
Moderator note
|
||||
{requiresNote ? (
|
||||
<span className="text-destructive ml-1">*</span>
|
||||
) : (
|
||||
<span className="text-muted-foreground ml-1">(optional)</span>
|
||||
)}
|
||||
</Label>
|
||||
<Textarea
|
||||
id="note"
|
||||
value={note}
|
||||
onChange={(e) => setNote(e.target.value)}
|
||||
placeholder="Explain why this action is being taken."
|
||||
rows={3}
|
||||
className="text-sm resize-none"
|
||||
/>
|
||||
{requiresNote && (
|
||||
<p className="text-[11px] text-muted-foreground">Min. 10 characters required.</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{isSevere && (
|
||||
<div className="flex items-start gap-2.5 rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2.5">
|
||||
<ShieldAlert className="h-4 w-4 text-destructive shrink-0 mt-0.5" />
|
||||
<p className="text-[12px] text-destructive leading-snug">
|
||||
This is a severe action may often not be easily undone. Double-check before
|
||||
applying.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Button
|
||||
onClick={submitAction}
|
||||
disabled={isSubmitting}
|
||||
variant={isSevere ? 'destructive' : 'default'}
|
||||
className="w-full gap-2"
|
||||
size="sm"
|
||||
>
|
||||
<Gavel className="h-3.5 w-3.5" />
|
||||
{isSubmitting ? 'Applying…' : 'Apply action'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Types ───────────────────────────────────────────────────────────────────
|
||||
|
||||
interface ReportCasePageClientProps {
|
||||
report: ChatReportCase;
|
||||
}
|
||||
|
||||
interface ChatReportCase {
|
||||
id: string;
|
||||
status: 'OPEN' | 'REVIEWED' | 'DISMISSED';
|
||||
reason: string;
|
||||
reportedMessage: string | null;
|
||||
reportedMessageId: string | null;
|
||||
targetUsername: string | null;
|
||||
channelName: string;
|
||||
createdAt: string;
|
||||
handledAt: string | null;
|
||||
handlingNote: string | null;
|
||||
lastAction:
|
||||
| 'REVIEW'
|
||||
| 'DISMISS'
|
||||
| 'DELETE_REPORTED_MESSAGE'
|
||||
| 'TIMEOUT_10M'
|
||||
| 'TIMEOUT_1H'
|
||||
| 'BAN_CHAT'
|
||||
| 'LIFT_CHAT_BAN'
|
||||
| 'BAN_PLATFORM'
|
||||
| 'UNBAN_PLATFORM'
|
||||
| null;
|
||||
reporter: string;
|
||||
target: string;
|
||||
targetUserId: string | null;
|
||||
targetIsAdmin: boolean;
|
||||
targetIsPlatformBanned: boolean;
|
||||
handledBy: string | null;
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import { validateRequest } from '@/lib/auth/validate';
|
||||
import { prisma } from '@hctv/db';
|
||||
import { notFound, redirect } from 'next/navigation';
|
||||
import ReportCasePageClient from './page.client';
|
||||
|
||||
export default async function ReportCasePage({ params }: ReportCasePageProps) {
|
||||
const { reportId } = await params;
|
||||
const { user } = await validateRequest();
|
||||
|
||||
if (!user) {
|
||||
redirect('/auth/hackclub');
|
||||
}
|
||||
|
||||
if (!user.isAdmin) {
|
||||
redirect('/');
|
||||
}
|
||||
|
||||
const report = await prisma.chatUserReport.findUnique({
|
||||
where: {
|
||||
id: reportId,
|
||||
},
|
||||
include: {
|
||||
channel: {
|
||||
select: {
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
reporter: {
|
||||
include: {
|
||||
personalChannel: {
|
||||
select: {
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
targetUser: {
|
||||
include: {
|
||||
personalChannel: {
|
||||
select: {
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
ban: true,
|
||||
},
|
||||
},
|
||||
handledBy: {
|
||||
include: {
|
||||
personalChannel: {
|
||||
select: {
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!report) {
|
||||
notFound();
|
||||
}
|
||||
|
||||
return (
|
||||
<ReportCasePageClient
|
||||
report={{
|
||||
id: report.id,
|
||||
status: report.status,
|
||||
reason: report.reason,
|
||||
reportedMessage: report.reportedMessage,
|
||||
reportedMessageId: report.reportedMessageId,
|
||||
targetUsername: report.targetUsername,
|
||||
channelName: report.channel.name,
|
||||
createdAt: report.createdAt.toISOString(),
|
||||
handledAt: report.handledAt?.toISOString() ?? null,
|
||||
handlingNote: report.handlingNote,
|
||||
lastAction: report.lastAction,
|
||||
reporter: report.reporter.personalChannel?.name ?? report.reporter.slack_id,
|
||||
target:
|
||||
report.targetUser?.personalChannel?.name ??
|
||||
report.targetUsername ??
|
||||
report.targetUserId ??
|
||||
'unknown',
|
||||
targetUserId: report.targetUserId,
|
||||
targetIsAdmin: Boolean(report.targetUser?.isAdmin),
|
||||
targetIsPlatformBanned: Boolean(report.targetUser?.ban),
|
||||
handledBy: report.handledBy?.personalChannel?.name ?? report.handledBy?.slack_id ?? null,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
interface ReportCasePageProps {
|
||||
params: Promise<{
|
||||
reportId: string;
|
||||
}>;
|
||||
}
|
||||
178
apps/web/src/app/(ui)/(protected)/api/admin/audit/route.ts
Normal file
178
apps/web/src/app/(ui)/(protected)/api/admin/audit/route.ts
Normal file
@@ -0,0 +1,178 @@
|
||||
import { validateRequest } from '@/lib/auth/validate';
|
||||
import { prisma } from '@hctv/db';
|
||||
import { NextRequest } from 'next/server';
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const { user } = await validateRequest();
|
||||
if (!user?.isAdmin) {
|
||||
return new Response('Forbidden', { status: 403 });
|
||||
}
|
||||
|
||||
const searchParams = request.nextUrl.searchParams;
|
||||
const take = Math.min(Math.max(Number(searchParams.get('take') ?? 100), 10), 250);
|
||||
|
||||
const [adminLogs, chatLogs] = await Promise.all([
|
||||
prisma.adminAuditLog.findMany({
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take,
|
||||
include: {
|
||||
actor: {
|
||||
select: {
|
||||
id: true,
|
||||
isAdmin: true,
|
||||
slack_id: true,
|
||||
personalChannel: {
|
||||
select: {
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
prisma.chatModerationEvent.findMany({
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take,
|
||||
include: {
|
||||
channel: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
moderator: {
|
||||
select: {
|
||||
id: true,
|
||||
isAdmin: true,
|
||||
slack_id: true,
|
||||
personalChannel: {
|
||||
select: {
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
targetUser: {
|
||||
select: {
|
||||
id: true,
|
||||
isAdmin: true,
|
||||
slack_id: true,
|
||||
personalChannel: {
|
||||
select: {
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
const targetUserIds = [
|
||||
...new Set(adminLogs.map((log) => log.targetUserId).filter(Boolean)),
|
||||
] as string[];
|
||||
const targetUsers =
|
||||
targetUserIds.length > 0
|
||||
? await prisma.user.findMany({
|
||||
where: {
|
||||
id: {
|
||||
in: targetUserIds,
|
||||
},
|
||||
},
|
||||
include: {
|
||||
personalChannel: {
|
||||
select: {
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
: [];
|
||||
const targetUserMap = new Map(
|
||||
targetUsers.map((targetUser) => [
|
||||
targetUser.id,
|
||||
targetUser.personalChannel?.name ?? targetUser.slack_id,
|
||||
])
|
||||
);
|
||||
const targetUserAdminMap = new Map(
|
||||
targetUsers.map((targetUser) => [targetUser.id, targetUser.isAdmin])
|
||||
);
|
||||
|
||||
const actorIds = [
|
||||
...new Set([
|
||||
...adminLogs.map((log) => log.actorId),
|
||||
...chatLogs.map((log) => log.moderatorId),
|
||||
...chatLogs.map((log) => log.targetUserId).filter(Boolean),
|
||||
...targetUserIds,
|
||||
]),
|
||||
] as string[];
|
||||
|
||||
const modRoleUsers =
|
||||
actorIds.length > 0
|
||||
? await prisma.user.findMany({
|
||||
where: {
|
||||
id: { in: actorIds },
|
||||
OR: [
|
||||
{ ownedChannels: { some: {} } },
|
||||
{ managedChannels: { some: {} } },
|
||||
{ chatModeratedChannels: { some: {} } },
|
||||
],
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
})
|
||||
: [];
|
||||
const channelModSet = new Set(modRoleUsers.map((user) => user.id));
|
||||
|
||||
const normalizedAdminLogs = adminLogs.map((log) => ({
|
||||
id: log.id,
|
||||
source: 'platform' as const,
|
||||
action: log.action,
|
||||
createdAt: log.createdAt,
|
||||
actor: log.actor.personalChannel?.name ?? log.actor.slack_id,
|
||||
target:
|
||||
log.targetChannel ??
|
||||
(log.targetUserId ? (targetUserMap.get(log.targetUserId) ?? log.targetUserId) : null),
|
||||
reason: log.reason,
|
||||
details: log.details,
|
||||
actorMeta: {
|
||||
isPlatformAdmin: log.actor.isAdmin,
|
||||
isChannelModerator: channelModSet.has(log.actorId),
|
||||
},
|
||||
targetMeta: log.targetUserId
|
||||
? {
|
||||
isPlatformAdmin: Boolean(targetUserAdminMap.get(log.targetUserId)),
|
||||
isChannelModerator: channelModSet.has(log.targetUserId),
|
||||
}
|
||||
: null,
|
||||
}));
|
||||
|
||||
const normalizedChatLogs = chatLogs.map((log) => ({
|
||||
id: log.id,
|
||||
source: 'chat' as const,
|
||||
action: log.action,
|
||||
createdAt: log.createdAt,
|
||||
actor: log.moderator.personalChannel?.name ?? log.moderator.slack_id,
|
||||
target: log.targetUser?.personalChannel?.name ?? log.channel.name,
|
||||
reason: log.reason,
|
||||
details: log.details,
|
||||
channelName: log.channel.name,
|
||||
actorMeta: {
|
||||
isPlatformAdmin: log.moderator.isAdmin,
|
||||
isChannelModerator: true,
|
||||
},
|
||||
targetMeta: log.targetUser
|
||||
? {
|
||||
isPlatformAdmin: log.targetUser.isAdmin,
|
||||
isChannelModerator: channelModSet.has(log.targetUser.id),
|
||||
}
|
||||
: null,
|
||||
}));
|
||||
|
||||
const logs = [...normalizedAdminLogs, ...normalizedChatLogs]
|
||||
.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
|
||||
.slice(0, take);
|
||||
|
||||
return Response.json(logs);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { validateRequest } from '@/lib/auth/validate';
|
||||
import { prisma } from '@hctv/db';
|
||||
import { AdminAuditAction, prisma } from '@hctv/db';
|
||||
import { NextRequest } from 'next/server';
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
@@ -14,16 +14,21 @@ export async function GET(request: NextRequest) {
|
||||
const channels = await prisma.channel.findMany({
|
||||
where: search
|
||||
? {
|
||||
OR: [
|
||||
{ name: { contains: search, mode: 'insensitive' } },
|
||||
{ description: { contains: search, mode: 'insensitive' } },
|
||||
],
|
||||
}
|
||||
OR: [
|
||||
{ name: { contains: search, mode: 'insensitive' } },
|
||||
{ description: { contains: search, mode: 'insensitive' } },
|
||||
],
|
||||
}
|
||||
: undefined,
|
||||
include: {
|
||||
restriction: true,
|
||||
owner: {
|
||||
select: { id: true, slack_id: true, pfpUrl: true, personalChannel: { select: { name: true } } },
|
||||
select: {
|
||||
id: true,
|
||||
slack_id: true,
|
||||
pfpUrl: true,
|
||||
personalChannel: { select: { name: true } },
|
||||
},
|
||||
},
|
||||
personalFor: {
|
||||
select: {
|
||||
@@ -42,18 +47,36 @@ export async function POST(request: NextRequest) {
|
||||
return new Response('Forbidden', { status: 403 });
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { channelId, action, reason, expiresAt } = body as {
|
||||
let body: {
|
||||
channelId: string;
|
||||
action: 'restrict' | 'unrestrict';
|
||||
reason?: string;
|
||||
expiresAt?: string;
|
||||
};
|
||||
|
||||
try {
|
||||
body = await request.json();
|
||||
} catch {
|
||||
return new Response('Invalid JSON body', { status: 400 });
|
||||
}
|
||||
|
||||
const { channelId, action, reason, expiresAt } = body;
|
||||
|
||||
if (!channelId || !action) {
|
||||
return new Response('Missing required fields', { status: 400 });
|
||||
}
|
||||
|
||||
let expiresAtDate: Date | null = null;
|
||||
if (expiresAt !== undefined && expiresAt !== null && expiresAt !== '') {
|
||||
expiresAtDate = new Date(expiresAt);
|
||||
if (isNaN(expiresAtDate.getTime())) {
|
||||
return new Response('Invalid expiresAt date', { status: 400 });
|
||||
}
|
||||
if (expiresAtDate <= new Date()) {
|
||||
return new Response('expiresAt must be a future date', { status: 400 });
|
||||
}
|
||||
}
|
||||
|
||||
const channel = await prisma.channel.findUnique({ where: { id: channelId } });
|
||||
if (!channel) {
|
||||
return new Response('Channel not found', { status: 404 });
|
||||
@@ -69,13 +92,26 @@ export async function POST(request: NextRequest) {
|
||||
update: {
|
||||
reason,
|
||||
restrictedBy: user.id,
|
||||
expiresAt: expiresAt ? new Date(expiresAt) : null,
|
||||
expiresAt: expiresAtDate,
|
||||
},
|
||||
create: {
|
||||
channelId,
|
||||
reason,
|
||||
restrictedBy: user.id,
|
||||
expiresAt: expiresAt ? new Date(expiresAt) : null,
|
||||
expiresAt: expiresAtDate,
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.adminAuditLog.create({
|
||||
data: {
|
||||
action: AdminAuditAction.CHANNEL_RESTRICTED,
|
||||
actorId: user.id,
|
||||
targetChannel: channel.name,
|
||||
reason,
|
||||
details: {
|
||||
channelId,
|
||||
expiresAt: expiresAtDate?.toISOString() ?? null,
|
||||
} as any,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -83,7 +119,22 @@ export async function POST(request: NextRequest) {
|
||||
}
|
||||
|
||||
if (action === 'unrestrict') {
|
||||
await prisma.channelRestriction.delete({ where: { channelId } }).catch(() => { });
|
||||
const deleted = await prisma.channelRestriction.deleteMany({ where: { channelId } });
|
||||
if (deleted.count === 0) {
|
||||
return new Response('Channel does not have an active restriction', { status: 400 });
|
||||
}
|
||||
|
||||
await prisma.adminAuditLog.create({
|
||||
data: {
|
||||
action: AdminAuditAction.CHANNEL_UNRESTRICTED,
|
||||
actorId: user.id,
|
||||
targetChannel: channel.name,
|
||||
details: {
|
||||
channelId,
|
||||
} as any,
|
||||
},
|
||||
});
|
||||
|
||||
return Response.json({ success: true, message: 'Channel unrestricted' });
|
||||
}
|
||||
|
||||
|
||||
529
apps/web/src/app/(ui)/(protected)/api/admin/reports/route.ts
Normal file
529
apps/web/src/app/(ui)/(protected)/api/admin/reports/route.ts
Normal file
@@ -0,0 +1,529 @@
|
||||
import { validateRequest } from '@/lib/auth/validate';
|
||||
import {
|
||||
AdminAuditAction,
|
||||
ChatModerationAction,
|
||||
ChatReportAction,
|
||||
ChatReportStatus,
|
||||
getRedisConnection,
|
||||
prisma,
|
||||
} from '@hctv/db';
|
||||
import { NextRequest } from 'next/server';
|
||||
|
||||
const redis = getRedisConnection();
|
||||
const REPORT_ALREADY_HANDLED_ERROR = 'REPORT_ALREADY_HANDLED';
|
||||
const NO_ACTIVE_CHAT_BAN_ERROR = 'NO_ACTIVE_CHAT_BAN';
|
||||
const NO_ACTIVE_PLATFORM_BAN_ERROR = 'NO_ACTIVE_PLATFORM_BAN';
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const { user } = await validateRequest();
|
||||
if (!user?.isAdmin) {
|
||||
return new Response('Forbidden', { status: 403 });
|
||||
}
|
||||
|
||||
const searchParams = request.nextUrl.searchParams;
|
||||
const take = Math.min(Math.max(Number(searchParams.get('take') ?? 100), 10), 250);
|
||||
const reportId = searchParams.get('reportId')?.trim();
|
||||
|
||||
const reports = await prisma.chatUserReport.findMany({
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take,
|
||||
include: {
|
||||
channel: {
|
||||
select: {
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
reporter: {
|
||||
include: {
|
||||
personalChannel: {
|
||||
select: {
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
targetUser: {
|
||||
include: {
|
||||
personalChannel: {
|
||||
select: {
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
handledBy: {
|
||||
include: {
|
||||
personalChannel: {
|
||||
select: {
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const normalizedReports = reports.map((report) => ({
|
||||
id: report.id,
|
||||
status: report.status,
|
||||
reason: report.reason,
|
||||
reportedMessage: report.reportedMessage,
|
||||
reportedMessageId: report.reportedMessageId,
|
||||
targetUsername: report.targetUsername,
|
||||
channelName: report.channel.name,
|
||||
createdAt: report.createdAt,
|
||||
handledAt: report.handledAt,
|
||||
handlingNote: report.handlingNote,
|
||||
lastAction: report.lastAction,
|
||||
reporter: report.reporter.personalChannel?.name ?? report.reporter.slack_id,
|
||||
handledBy: report.handledBy?.personalChannel?.name ?? report.handledBy?.slack_id ?? null,
|
||||
target:
|
||||
report.targetUser?.personalChannel?.name ??
|
||||
report.targetUsername ??
|
||||
report.targetUserId ??
|
||||
'unknown',
|
||||
}));
|
||||
|
||||
return Response.json({
|
||||
reports: normalizedReports,
|
||||
reportId,
|
||||
});
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const { user } = await validateRequest();
|
||||
if (!user?.isAdmin) {
|
||||
return new Response('Forbidden', { status: 403 });
|
||||
}
|
||||
|
||||
let body: {
|
||||
reportId?: string;
|
||||
action?:
|
||||
| 'review'
|
||||
| 'dismiss'
|
||||
| 'delete_reported_message'
|
||||
| 'timeout_10m'
|
||||
| 'timeout_1h'
|
||||
| 'ban_chat'
|
||||
| 'lift_chat_ban'
|
||||
| 'ban_platform'
|
||||
| 'unban_platform';
|
||||
note?: string;
|
||||
};
|
||||
|
||||
try {
|
||||
body = await request.json();
|
||||
} catch {
|
||||
return new Response('Invalid JSON body', { status: 400 });
|
||||
}
|
||||
|
||||
const reportId = body.reportId?.trim();
|
||||
const action = body.action;
|
||||
const note = body.note?.trim() || null;
|
||||
|
||||
if (!reportId || !action) {
|
||||
return new Response('Missing required fields', { status: 400 });
|
||||
}
|
||||
|
||||
const report = await prisma.chatUserReport.findUnique({
|
||||
where: { id: reportId },
|
||||
include: {
|
||||
channel: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
targetUser: {
|
||||
select: {
|
||||
id: true,
|
||||
isAdmin: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!report) {
|
||||
return new Response('Report not found', { status: 404 });
|
||||
}
|
||||
|
||||
const targetUserId = report.targetUserId ?? report.targetUser?.id ?? null;
|
||||
const isTargetAdmin = Boolean(report.targetUser?.isAdmin);
|
||||
|
||||
if (
|
||||
(action === 'ban_platform' ||
|
||||
action === 'ban_chat' ||
|
||||
action === 'timeout_10m' ||
|
||||
action === 'timeout_1h') &&
|
||||
isTargetAdmin
|
||||
) {
|
||||
return new Response('Cannot enforce this action on an admin user', { status: 400 });
|
||||
}
|
||||
|
||||
const reportPatchBase = {
|
||||
handledById: user.id,
|
||||
handledAt: new Date(),
|
||||
handlingNote: note,
|
||||
};
|
||||
|
||||
if (action === 'review') {
|
||||
try {
|
||||
await prisma.$transaction(async (tx) => {
|
||||
const claimed = await tx.chatUserReport.updateMany({
|
||||
where: { id: reportId, status: ChatReportStatus.OPEN },
|
||||
data: {
|
||||
...reportPatchBase,
|
||||
status: ChatReportStatus.REVIEWED,
|
||||
lastAction: ChatReportAction.REVIEW,
|
||||
},
|
||||
});
|
||||
if (claimed.count === 0) {
|
||||
throw new Error(REPORT_ALREADY_HANDLED_ERROR);
|
||||
}
|
||||
|
||||
await tx.adminAuditLog.create({
|
||||
data: {
|
||||
action: AdminAuditAction.REPORT_REVIEWED,
|
||||
actorId: user.id,
|
||||
targetUserId,
|
||||
targetChannel: report.channel.name,
|
||||
reason: note,
|
||||
details: {
|
||||
reportId,
|
||||
} as any,
|
||||
},
|
||||
});
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message === REPORT_ALREADY_HANDLED_ERROR) {
|
||||
return new Response('Report has already been handled', { status: 409 });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
return Response.json({ success: true });
|
||||
}
|
||||
|
||||
if (action === 'dismiss') {
|
||||
try {
|
||||
await prisma.$transaction(async (tx) => {
|
||||
const claimed = await tx.chatUserReport.updateMany({
|
||||
where: { id: reportId, status: ChatReportStatus.OPEN },
|
||||
data: {
|
||||
...reportPatchBase,
|
||||
status: ChatReportStatus.DISMISSED,
|
||||
lastAction: ChatReportAction.DISMISS,
|
||||
},
|
||||
});
|
||||
if (claimed.count === 0) {
|
||||
throw new Error(REPORT_ALREADY_HANDLED_ERROR);
|
||||
}
|
||||
|
||||
await tx.adminAuditLog.create({
|
||||
data: {
|
||||
action: AdminAuditAction.REPORT_DISMISSED,
|
||||
actorId: user.id,
|
||||
targetUserId,
|
||||
targetChannel: report.channel.name,
|
||||
reason: note,
|
||||
details: {
|
||||
reportId,
|
||||
} as any,
|
||||
},
|
||||
});
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message === REPORT_ALREADY_HANDLED_ERROR) {
|
||||
return new Response('Report has already been handled', { status: 409 });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
return Response.json({ success: true });
|
||||
}
|
||||
|
||||
if (action === 'delete_reported_message') {
|
||||
if (!report.reportedMessageId) {
|
||||
return new Response('No reported message id available for this report', { status: 400 });
|
||||
}
|
||||
|
||||
const channelKey = `chat:history:${report.channel.name}`;
|
||||
const history = await redis.zrange(channelKey, 0, -1);
|
||||
let deleted = false;
|
||||
|
||||
for (const entry of history) {
|
||||
try {
|
||||
const parsed = JSON.parse(entry) as { msgId?: string };
|
||||
if (parsed.msgId === report.reportedMessageId) {
|
||||
await redis.zrem(channelKey, entry);
|
||||
deleted = true;
|
||||
break;
|
||||
}
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (!deleted) {
|
||||
return new Response('Reported message was not found in chat history', { status: 404 });
|
||||
}
|
||||
|
||||
try {
|
||||
await prisma.$transaction(async (tx) => {
|
||||
const claimed = await tx.chatUserReport.updateMany({
|
||||
where: { id: reportId, status: ChatReportStatus.OPEN },
|
||||
data: {
|
||||
...reportPatchBase,
|
||||
status: ChatReportStatus.REVIEWED,
|
||||
lastAction: ChatReportAction.DELETE_REPORTED_MESSAGE,
|
||||
},
|
||||
});
|
||||
if (claimed.count === 0) {
|
||||
throw new Error(REPORT_ALREADY_HANDLED_ERROR);
|
||||
}
|
||||
|
||||
await tx.chatModerationEvent.create({
|
||||
data: {
|
||||
action: ChatModerationAction.MESSAGE_DELETED,
|
||||
channelId: report.channel.id,
|
||||
moderatorId: user.id,
|
||||
targetUserId,
|
||||
reason: note ?? 'Message deleted from report review',
|
||||
details: {
|
||||
reportId,
|
||||
msgId: report.reportedMessageId,
|
||||
} as any,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.adminAuditLog.create({
|
||||
data: {
|
||||
action: AdminAuditAction.REPORT_ENFORCEMENT,
|
||||
actorId: user.id,
|
||||
targetUserId,
|
||||
targetChannel: report.channel.name,
|
||||
reason: note,
|
||||
details: {
|
||||
reportId,
|
||||
enforcement: 'DELETE_REPORTED_MESSAGE',
|
||||
msgId: report.reportedMessageId,
|
||||
} as any,
|
||||
},
|
||||
});
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message === REPORT_ALREADY_HANDLED_ERROR) {
|
||||
return new Response('Report has already been handled', { status: 409 });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
return Response.json({ success: true });
|
||||
}
|
||||
|
||||
if (!targetUserId) {
|
||||
return new Response('Report target is unavailable', { status: 400 });
|
||||
}
|
||||
|
||||
if (
|
||||
action === 'timeout_10m' ||
|
||||
action === 'timeout_1h' ||
|
||||
action === 'ban_chat' ||
|
||||
action === 'lift_chat_ban'
|
||||
) {
|
||||
const timeoutSeconds = action === 'timeout_10m' ? 600 : action === 'timeout_1h' ? 3600 : null;
|
||||
try {
|
||||
await prisma.$transaction(async (tx) => {
|
||||
const claimed = await tx.chatUserReport.updateMany({
|
||||
where: { id: reportId, status: ChatReportStatus.OPEN },
|
||||
data: {
|
||||
...reportPatchBase,
|
||||
status: ChatReportStatus.REVIEWED,
|
||||
lastAction:
|
||||
action === 'timeout_10m'
|
||||
? ChatReportAction.TIMEOUT_10M
|
||||
: action === 'timeout_1h'
|
||||
? ChatReportAction.TIMEOUT_1H
|
||||
: action === 'ban_chat'
|
||||
? ChatReportAction.BAN_CHAT
|
||||
: ChatReportAction.LIFT_CHAT_BAN,
|
||||
},
|
||||
});
|
||||
if (claimed.count === 0) {
|
||||
throw new Error(REPORT_ALREADY_HANDLED_ERROR);
|
||||
}
|
||||
|
||||
if (action === 'lift_chat_ban') {
|
||||
const deleted = await tx.chatUserBan.deleteMany({
|
||||
where: {
|
||||
channelId: report.channel.id,
|
||||
userId: targetUserId,
|
||||
},
|
||||
});
|
||||
if (deleted.count === 0) {
|
||||
throw new Error(NO_ACTIVE_CHAT_BAN_ERROR);
|
||||
}
|
||||
} else {
|
||||
await tx.chatUserBan.upsert({
|
||||
where: {
|
||||
channelId_userId: {
|
||||
channelId: report.channel.id,
|
||||
userId: targetUserId,
|
||||
},
|
||||
},
|
||||
create: {
|
||||
channelId: report.channel.id,
|
||||
userId: targetUserId,
|
||||
bannedById: user.id,
|
||||
reason: note ?? report.reason,
|
||||
expiresAt: timeoutSeconds ? new Date(Date.now() + timeoutSeconds * 1000) : null,
|
||||
},
|
||||
update: {
|
||||
bannedById: user.id,
|
||||
reason: note ?? report.reason,
|
||||
expiresAt: timeoutSeconds ? new Date(Date.now() + timeoutSeconds * 1000) : null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
await tx.chatModerationEvent.create({
|
||||
data: {
|
||||
action:
|
||||
action === 'lift_chat_ban'
|
||||
? ChatModerationAction.USER_UNBANNED
|
||||
: action === 'ban_chat'
|
||||
? ChatModerationAction.USER_BANNED
|
||||
: ChatModerationAction.USER_TIMEOUT,
|
||||
channelId: report.channel.id,
|
||||
moderatorId: user.id,
|
||||
targetUserId,
|
||||
reason: note ?? report.reason,
|
||||
details:
|
||||
timeoutSeconds === null
|
||||
? ({ reportId } as any)
|
||||
: ({ reportId, durationSeconds: timeoutSeconds } as any),
|
||||
},
|
||||
});
|
||||
|
||||
await tx.adminAuditLog.create({
|
||||
data: {
|
||||
action: AdminAuditAction.REPORT_ENFORCEMENT,
|
||||
actorId: user.id,
|
||||
targetUserId,
|
||||
targetChannel: report.channel.name,
|
||||
reason: note,
|
||||
details: {
|
||||
reportId,
|
||||
enforcement:
|
||||
action === 'timeout_10m'
|
||||
? 'TIMEOUT_10M'
|
||||
: action === 'timeout_1h'
|
||||
? 'TIMEOUT_1H'
|
||||
: action === 'ban_chat'
|
||||
? 'BAN_CHAT'
|
||||
: 'LIFT_CHAT_BAN',
|
||||
} as any,
|
||||
},
|
||||
});
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message === REPORT_ALREADY_HANDLED_ERROR) {
|
||||
return new Response('Report has already been handled', { status: 409 });
|
||||
}
|
||||
if (error instanceof Error && error.message === NO_ACTIVE_CHAT_BAN_ERROR) {
|
||||
return new Response('User does not have an active chat ban for this channel', {
|
||||
status: 400,
|
||||
});
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
return Response.json({ success: true });
|
||||
}
|
||||
|
||||
if (action === 'ban_platform' || action === 'unban_platform') {
|
||||
try {
|
||||
await prisma.$transaction(async (tx) => {
|
||||
const claimed = await tx.chatUserReport.updateMany({
|
||||
where: { id: reportId, status: ChatReportStatus.OPEN },
|
||||
data: {
|
||||
...reportPatchBase,
|
||||
status: ChatReportStatus.REVIEWED,
|
||||
lastAction:
|
||||
action === 'ban_platform'
|
||||
? ChatReportAction.BAN_PLATFORM
|
||||
: ChatReportAction.UNBAN_PLATFORM,
|
||||
},
|
||||
});
|
||||
if (claimed.count === 0) {
|
||||
throw new Error(REPORT_ALREADY_HANDLED_ERROR);
|
||||
}
|
||||
|
||||
if (action === 'ban_platform') {
|
||||
await tx.userBan.upsert({
|
||||
where: { userId: targetUserId },
|
||||
update: {
|
||||
reason: note ?? report.reason,
|
||||
bannedBy: user.id,
|
||||
expiresAt: null,
|
||||
},
|
||||
create: {
|
||||
userId: targetUserId,
|
||||
reason: note ?? report.reason,
|
||||
bannedBy: user.id,
|
||||
expiresAt: null,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
const deleted = await tx.userBan.deleteMany({ where: { userId: targetUserId } });
|
||||
if (deleted.count === 0) {
|
||||
throw new Error(NO_ACTIVE_PLATFORM_BAN_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
await tx.adminAuditLog.create({
|
||||
data: {
|
||||
action:
|
||||
action === 'ban_platform'
|
||||
? AdminAuditAction.USER_BANNED
|
||||
: AdminAuditAction.USER_UNBANNED,
|
||||
actorId: user.id,
|
||||
targetUserId,
|
||||
targetChannel: report.channel.name,
|
||||
reason: note,
|
||||
details: {
|
||||
reportId,
|
||||
source: 'CHAT_REPORT',
|
||||
} as any,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.adminAuditLog.create({
|
||||
data: {
|
||||
action: AdminAuditAction.REPORT_ENFORCEMENT,
|
||||
actorId: user.id,
|
||||
targetUserId,
|
||||
targetChannel: report.channel.name,
|
||||
reason: note,
|
||||
details: {
|
||||
reportId,
|
||||
enforcement: action === 'ban_platform' ? 'BAN_PLATFORM' : 'UNBAN_PLATFORM',
|
||||
} as any,
|
||||
},
|
||||
});
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message === REPORT_ALREADY_HANDLED_ERROR) {
|
||||
return new Response('Report has already been handled', { status: 409 });
|
||||
}
|
||||
if (error instanceof Error && error.message === NO_ACTIVE_PLATFORM_BAN_ERROR) {
|
||||
return new Response('User does not have an active platform ban', { status: 400 });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
return Response.json({ success: true });
|
||||
}
|
||||
|
||||
return new Response('Invalid action', { status: 400 });
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { validateRequest } from '@/lib/auth/validate';
|
||||
import { prisma } from '@hctv/db';
|
||||
import { AdminAuditAction, prisma } from '@hctv/db';
|
||||
import { NextRequest } from 'next/server';
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
@@ -14,12 +14,13 @@ export async function GET(request: NextRequest) {
|
||||
const users = await prisma.user.findMany({
|
||||
where: search
|
||||
? {
|
||||
OR: [
|
||||
{ slack_id: { contains: search, mode: 'insensitive' } },
|
||||
{ email: { contains: search, mode: 'insensitive' } },
|
||||
{ personalChannel: { name: { contains: search, mode: 'insensitive' } } },
|
||||
],
|
||||
}
|
||||
OR: [
|
||||
{ slack_id: { contains: search, mode: 'insensitive' } },
|
||||
{ email: { contains: search, mode: 'insensitive' } },
|
||||
{ personalChannel: { name: { contains: search, mode: 'insensitive' } } },
|
||||
],
|
||||
hasOnboarded: true,
|
||||
}
|
||||
: undefined,
|
||||
include: {
|
||||
ban: true,
|
||||
@@ -36,18 +37,36 @@ export async function POST(request: NextRequest) {
|
||||
return new Response('Forbidden', { status: 403 });
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { userId, action, reason, expiresAt } = body as {
|
||||
let body: {
|
||||
userId: string;
|
||||
action: 'ban' | 'unban' | 'promote' | 'demote';
|
||||
reason?: string;
|
||||
expiresAt?: string;
|
||||
};
|
||||
|
||||
try {
|
||||
body = await request.json();
|
||||
} catch {
|
||||
return new Response('Invalid JSON body', { status: 400 });
|
||||
}
|
||||
|
||||
const { userId, action, reason, expiresAt } = body;
|
||||
|
||||
if (!userId || !action) {
|
||||
return new Response('Missing required fields', { status: 400 });
|
||||
}
|
||||
|
||||
let expiresAtDate: Date | null = null;
|
||||
if (expiresAt !== undefined && expiresAt !== null && expiresAt !== '') {
|
||||
expiresAtDate = new Date(expiresAt);
|
||||
if (isNaN(expiresAtDate.getTime())) {
|
||||
return new Response('Invalid expiresAt date', { status: 400 });
|
||||
}
|
||||
if (expiresAtDate <= new Date()) {
|
||||
return new Response('expiresAt must be a future date', { status: 400 });
|
||||
}
|
||||
}
|
||||
|
||||
const targetUser = await prisma.user.findUnique({ where: { id: userId } });
|
||||
if (!targetUser) {
|
||||
return new Response('User not found', { status: 404 });
|
||||
@@ -67,13 +86,25 @@ export async function POST(request: NextRequest) {
|
||||
update: {
|
||||
reason,
|
||||
bannedBy: user.id,
|
||||
expiresAt: expiresAt ? new Date(expiresAt) : null,
|
||||
expiresAt: expiresAtDate,
|
||||
},
|
||||
create: {
|
||||
userId,
|
||||
reason,
|
||||
bannedBy: user.id,
|
||||
expiresAt: expiresAt ? new Date(expiresAt) : null,
|
||||
expiresAt: expiresAtDate,
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.adminAuditLog.create({
|
||||
data: {
|
||||
action: AdminAuditAction.USER_BANNED,
|
||||
actorId: user.id,
|
||||
targetUserId: userId,
|
||||
reason,
|
||||
details: {
|
||||
expiresAt: expiresAtDate?.toISOString() ?? null,
|
||||
} as any,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -81,7 +112,19 @@ export async function POST(request: NextRequest) {
|
||||
}
|
||||
|
||||
if (action === 'unban') {
|
||||
await prisma.userBan.delete({ where: { userId } }).catch(() => { });
|
||||
const deleted = await prisma.userBan.deleteMany({ where: { userId } });
|
||||
if (deleted.count === 0) {
|
||||
return new Response('User does not have an active platform ban', { status: 400 });
|
||||
}
|
||||
|
||||
await prisma.adminAuditLog.create({
|
||||
data: {
|
||||
action: AdminAuditAction.USER_UNBANNED,
|
||||
actorId: user.id,
|
||||
targetUserId: userId,
|
||||
},
|
||||
});
|
||||
|
||||
return Response.json({ success: true, message: 'User unbanned' });
|
||||
}
|
||||
|
||||
@@ -95,6 +138,14 @@ export async function POST(request: NextRequest) {
|
||||
data: { isAdmin: true },
|
||||
});
|
||||
|
||||
await prisma.adminAuditLog.create({
|
||||
data: {
|
||||
action: AdminAuditAction.USER_PROMOTED,
|
||||
actorId: user.id,
|
||||
targetUserId: userId,
|
||||
},
|
||||
});
|
||||
|
||||
return Response.json({ success: true, message: 'User promoted to admin' });
|
||||
}
|
||||
|
||||
@@ -112,6 +163,14 @@ export async function POST(request: NextRequest) {
|
||||
data: { isAdmin: false },
|
||||
});
|
||||
|
||||
await prisma.adminAuditLog.create({
|
||||
data: {
|
||||
action: AdminAuditAction.USER_DEMOTED,
|
||||
actorId: user.id,
|
||||
targetUserId: userId,
|
||||
},
|
||||
});
|
||||
|
||||
return Response.json({ success: true, message: 'User demoted from admin' });
|
||||
}
|
||||
|
||||
|
||||
@@ -1,29 +1,39 @@
|
||||
import { prisma, getRedisConnection } from '@hctv/db';
|
||||
import { recordMediamtxAuth } from '@/lib/metrics';
|
||||
import { NextRequest } from 'next/server';
|
||||
import { z } from 'zod';
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const startedAt = performance.now();
|
||||
let action = 'invalid';
|
||||
let protocol = 'invalid';
|
||||
|
||||
const finish = (body: string, status: number, outcome: string) => {
|
||||
recordMediamtxAuth(action, protocol, outcome, (performance.now() - startedAt) / 1000);
|
||||
return new Response(body, { status });
|
||||
};
|
||||
|
||||
const redis = getRedisConnection();
|
||||
const body = await request.json();
|
||||
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
console.log(
|
||||
'Mediamtx publish auth request:',
|
||||
JSON.stringify(body, null, 2)
|
||||
);
|
||||
};
|
||||
console.log('Mediamtx publish auth request:', JSON.stringify(body, null, 2));
|
||||
}
|
||||
const parsed = schema.safeParse(body);
|
||||
|
||||
if (!parsed.success) {
|
||||
return new Response('invalid request', { status: 400 });
|
||||
return finish('invalid request', 400, 'invalid_request');
|
||||
}
|
||||
const { action, protocol, path, password } = parsed.data;
|
||||
if (action === 'publish' && protocol === 'srt') {
|
||||
const { action: parsedAction, protocol: parsedProtocol, path, password } = parsed.data;
|
||||
action = parsedAction;
|
||||
protocol = parsedProtocol;
|
||||
|
||||
if (parsedAction === 'publish' && parsedProtocol === 'srt') {
|
||||
const channelKey = await redis.get(`streamKey:${path}`);
|
||||
|
||||
if (channelKey) {
|
||||
if (channelKey !== password) {
|
||||
return new Response('invalid stream key', { status: 403 });
|
||||
return finish('invalid stream key', 403, 'invalid_stream_key');
|
||||
}
|
||||
|
||||
const channel = await prisma.channel.findUnique({
|
||||
@@ -38,39 +48,39 @@ export async function POST(request: NextRequest) {
|
||||
});
|
||||
|
||||
if (channel?.restriction) {
|
||||
const isExpired = channel.restriction.expiresAt &&
|
||||
new Date(channel.restriction.expiresAt) < new Date();
|
||||
const isExpired =
|
||||
channel.restriction.expiresAt && new Date(channel.restriction.expiresAt) < new Date();
|
||||
if (!isExpired) {
|
||||
return new Response('channel restricted', { status: 403 });
|
||||
return finish('channel restricted', 403, 'channel_restricted');
|
||||
}
|
||||
}
|
||||
|
||||
if (channel?.owner?.ban) {
|
||||
const isExpired = channel.owner.ban.expiresAt &&
|
||||
new Date(channel.owner.ban.expiresAt) < new Date();
|
||||
const isExpired =
|
||||
channel.owner.ban.expiresAt && new Date(channel.owner.ban.expiresAt) < new Date();
|
||||
if (!isExpired) {
|
||||
return new Response('user banned', { status: 403 });
|
||||
return finish('user banned', 403, 'user_banned');
|
||||
}
|
||||
}
|
||||
|
||||
if (channel?.streamInfo[0].isLive) {
|
||||
return new Response('stream already live', { status: 403 });
|
||||
return finish('stream already live', 403, 'stream_already_live');
|
||||
}
|
||||
|
||||
return new Response('youre in yay', { status: 200 });
|
||||
return finish('youre in yay', 200, 'authorized_publish');
|
||||
}
|
||||
} else if (action === 'read' && protocol === 'hls') {
|
||||
} else if (parsedAction === 'read' && parsedProtocol === 'hls') {
|
||||
if (password === process.env.MEDIAMTX_PUBLISH_KEY) {
|
||||
return new Response('authorized (hls read key for thumbs)', { status: 200 });
|
||||
return finish('authorized (hls read key for thumbs)', 200, 'authorized_thumbnail');
|
||||
}
|
||||
const sessionExists = await redis.exists(`sessions:${password}`);
|
||||
if (!sessionExists) {
|
||||
return new Response('unauthorized', { status: 401 });
|
||||
return finish('unauthorized', 401, 'unauthorized_session');
|
||||
}
|
||||
return new Response('authorized', { status: 200 });
|
||||
return finish('authorized', 200, 'authorized_read');
|
||||
}
|
||||
|
||||
return new Response('uhh', { status: 401 });
|
||||
return finish('uhh', 401, 'unauthorized');
|
||||
}
|
||||
|
||||
const schema = z.object({
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
import { validateRequest } from '@/lib/auth/validate';
|
||||
import { prisma, getRedisConnection } from '@hctv/db';
|
||||
import { NextRequest } from 'next/server';
|
||||
|
||||
const RATE_LIMIT_WINDOW_SECONDS = 10 * 60;
|
||||
const RATE_LIMIT_MAX_REPORTS = 5;
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const { user } = await validateRequest();
|
||||
if (!user) {
|
||||
return new Response('Unauthorized', { status: 401 });
|
||||
}
|
||||
|
||||
let body: {
|
||||
channelName?: string;
|
||||
targetUserId?: string;
|
||||
targetUsername?: string;
|
||||
msgId?: string;
|
||||
message?: string;
|
||||
reason?: string;
|
||||
};
|
||||
|
||||
try {
|
||||
body = await request.json();
|
||||
} catch {
|
||||
return new Response('Invalid JSON body', { status: 400 });
|
||||
}
|
||||
|
||||
const channelName = body.channelName?.trim();
|
||||
const targetUserId = body.targetUserId?.trim();
|
||||
const reason = body.reason?.trim();
|
||||
|
||||
if (!channelName || !targetUserId || !reason) {
|
||||
return new Response('Missing required fields', { status: 400 });
|
||||
}
|
||||
|
||||
if (targetUserId === user.id) {
|
||||
return new Response('You cannot report yourself', { status: 400 });
|
||||
}
|
||||
|
||||
if (reason.length < 10 || reason.length > 1000) {
|
||||
return new Response('Reason must be between 10 and 1000 characters', { status: 400 });
|
||||
}
|
||||
|
||||
const redis = getRedisConnection();
|
||||
const rateLimitKey = `report_rl:${user.id}`;
|
||||
const currentCount = await redis.incr(rateLimitKey);
|
||||
if (currentCount === 1) {
|
||||
await redis.expire(rateLimitKey, RATE_LIMIT_WINDOW_SECONDS);
|
||||
}
|
||||
if (currentCount > RATE_LIMIT_MAX_REPORTS) {
|
||||
return new Response('Too many reports submitted. Please wait before submitting more.', {
|
||||
status: 429,
|
||||
});
|
||||
}
|
||||
|
||||
const [channel, targetUser] = await Promise.all([
|
||||
prisma.channel.findUnique({
|
||||
where: { name: channelName },
|
||||
select: { id: true },
|
||||
}),
|
||||
prisma.user.findUnique({
|
||||
where: { id: targetUserId },
|
||||
select: { id: true, personalChannel: { select: { name: true } } },
|
||||
}),
|
||||
]);
|
||||
|
||||
if (!channel) {
|
||||
return new Response('Channel not found', { status: 404 });
|
||||
}
|
||||
|
||||
if (!targetUser) {
|
||||
return new Response('Target user not found', { status: 404 });
|
||||
}
|
||||
|
||||
const msgId = body.msgId?.trim() || null;
|
||||
const duplicateCheck = await prisma.chatUserReport.findFirst({
|
||||
where: {
|
||||
channelId: channel.id,
|
||||
reporterId: user.id,
|
||||
targetUserId: targetUser.id,
|
||||
reportedMessageId: msgId,
|
||||
status: 'OPEN',
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
if (duplicateCheck) {
|
||||
return new Response('You have already submitted an open report for this message.', {
|
||||
status: 409,
|
||||
});
|
||||
}
|
||||
|
||||
await prisma.chatUserReport.create({
|
||||
data: {
|
||||
channelId: channel.id,
|
||||
reporterId: user.id,
|
||||
targetUserId: targetUser.id,
|
||||
targetUsername: body.targetUsername?.trim() || targetUser.personalChannel?.name || null,
|
||||
reportedMessageId: msgId,
|
||||
reportedMessage: body.message?.trim().slice(0, 1000) || null,
|
||||
reason,
|
||||
},
|
||||
});
|
||||
|
||||
return Response.json({ success: true });
|
||||
}
|
||||
@@ -25,13 +25,14 @@ export async function GET(request: NextRequest) {
|
||||
|
||||
if (shouldGetOwned && user) {
|
||||
channelConditions.push({ ownerId: user.id });
|
||||
channelConditions.push({ managers: { some: { id: user.id } } });
|
||||
}
|
||||
|
||||
if (allPersonalChannels) {
|
||||
channelConditions.push({
|
||||
personalFor: {
|
||||
isNot: null
|
||||
}
|
||||
channelConditions.push({
|
||||
personalFor: {
|
||||
isNot: null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -40,9 +41,8 @@ export async function GET(request: NextRequest) {
|
||||
}
|
||||
|
||||
if (channelConditions.length > 0) {
|
||||
where.channel = channelConditions.length === 1
|
||||
? channelConditions[0]
|
||||
: { OR: channelConditions };
|
||||
where.channel =
|
||||
channelConditions.length === 1 ? channelConditions[0] : { OR: channelConditions };
|
||||
}
|
||||
|
||||
const db = await prisma.streamInfo.findMany({
|
||||
@@ -57,7 +57,7 @@ export async function GET(request: NextRequest) {
|
||||
expiresAt: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -71,7 +71,8 @@ export async function GET(request: NextRequest) {
|
||||
delete obj.channel.obsChatGrantToken;
|
||||
|
||||
if (obj.channel.restriction) {
|
||||
const isExpired = obj.channel.restriction.expiresAt &&
|
||||
const isExpired =
|
||||
obj.channel.restriction.expiresAt &&
|
||||
new Date(obj.channel.restriction.expiresAt) < new Date();
|
||||
if (isExpired) {
|
||||
// @ts-ignore
|
||||
@@ -88,4 +89,4 @@ export async function GET(request: NextRequest) {
|
||||
});
|
||||
|
||||
return Response.json(db);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,20 +21,36 @@ import {
|
||||
Wrench,
|
||||
Eye,
|
||||
EyeOff,
|
||||
MessageSquareWarning,
|
||||
Bot,
|
||||
} from 'lucide-react';
|
||||
import type { LucideIcon } from 'lucide-react';
|
||||
import { UniversalForm } from '@/components/app/UniversalForm/UniversalForm';
|
||||
import {
|
||||
updateChannelSettings,
|
||||
addChannelManager,
|
||||
removeChannelManager,
|
||||
addChatModerator,
|
||||
removeChatModerator,
|
||||
addChatBotModerator,
|
||||
removeChatBotModerator,
|
||||
deleteChannel,
|
||||
toggleGlobalChannelNotifs,
|
||||
editStreamInfo,
|
||||
changeUsername,
|
||||
updateChatModeration,
|
||||
} from '@/lib/form/actions';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { toast } from 'sonner';
|
||||
import type { Channel, User, StreamInfo, StreamKey, Follow } from '@hctv/db';
|
||||
import type {
|
||||
Channel,
|
||||
User,
|
||||
StreamInfo,
|
||||
StreamKey,
|
||||
Follow,
|
||||
ChatModerationSettings,
|
||||
BotAccount,
|
||||
} from '@hctv/db';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
@@ -45,6 +61,7 @@ import {
|
||||
DialogTrigger,
|
||||
} from '@/components/ui/dialog';
|
||||
import { UserCombobox } from '@/components/app/UserCombobox/UserCombobox';
|
||||
import { BotCombobox } from '@/components/app/BotCombobox/BotCombobox';
|
||||
import { parseAsString, useQueryState } from 'nuqs';
|
||||
import { Write } from '@/components/ui/channel-desc-fancy-area/write';
|
||||
import { Preview } from '@/components/ui/channel-desc-fancy-area/preview';
|
||||
@@ -70,8 +87,13 @@ interface ChannelSettingsClientProps {
|
||||
ownerPersonalChannel: Channel | null;
|
||||
managers: User[];
|
||||
managerPersonalChannels: (Channel | null)[];
|
||||
chatModerators: User[];
|
||||
chatModeratorPersonalChannels: (Channel | null)[];
|
||||
chatModeratorBots: BotAccount[];
|
||||
allBotAccounts: Pick<BotAccount, 'id' | 'displayName' | 'slug' | 'pfpUrl'>[];
|
||||
streamInfo: StreamInfo[];
|
||||
streamKey: StreamKey | null;
|
||||
chatSettings: ChatModerationSettings | null;
|
||||
followers: (Follow & { user: { id: string; slack_id: string } })[];
|
||||
followerPersonalChannels: (Channel | null)[];
|
||||
is247: boolean;
|
||||
@@ -114,6 +136,12 @@ export default function ChannelSettingsClient({
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleModerationActionComplete = useCallback((result: any) => {
|
||||
if (result?.success) {
|
||||
toast.success('Moderation settings updated');
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleUsernameChangeComplete = useCallback(
|
||||
(result: any) => {
|
||||
if (result?.success && result?.newUsername) {
|
||||
@@ -224,7 +252,7 @@ export default function ChannelSettingsClient({
|
||||
</div>
|
||||
|
||||
<Tabs className="w-full" value={selTab} onValueChange={setSelTab}>
|
||||
<TabsList className={`grid w-full ${isPersonal ? 'grid-cols-4' : 'grid-cols-5'}`}>
|
||||
<TabsList className={`grid w-full ${isPersonal ? 'grid-cols-5' : 'grid-cols-6'}`}>
|
||||
<TabsTrigger value="general" className="flex items-center gap-2">
|
||||
<Settings className="h-4 w-4" />
|
||||
General
|
||||
@@ -243,6 +271,10 @@ export default function ChannelSettingsClient({
|
||||
<Bell className="h-4 w-4" />
|
||||
Notifications
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="moderation" className="flex items-center gap-2">
|
||||
<MessageSquareWarning className="h-4 w-4" />
|
||||
Moderation
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="utilities" className="flex items-center gap-2">
|
||||
<Wrench className="size-4" />
|
||||
Utilities
|
||||
@@ -651,7 +683,6 @@ export default function ChannelSettingsClient({
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
{/* Owner */}
|
||||
<div className="flex items-center justify-between p-3 border rounded-lg">
|
||||
<div className="flex items-center gap-3">
|
||||
<Avatar className="h-10 w-10">
|
||||
@@ -665,13 +696,9 @@ export default function ChannelSettingsClient({
|
||||
<p className="text-sm text-mantle-foreground">Channel Owner</p>
|
||||
</div>
|
||||
</div>
|
||||
<Badge variant="default">
|
||||
<Shield className="h-3 w-3 mr-1" />
|
||||
Owner
|
||||
</Badge>
|
||||
<ChannelRoleBadges roles={['owner', 'chatModerator']} />
|
||||
</div>
|
||||
|
||||
{/* Managers */}
|
||||
{channel.managers.map((manager) => {
|
||||
const personalChannel = channel.managerPersonalChannels.find(
|
||||
(c) => c?.ownerId === manager.id
|
||||
@@ -691,26 +718,34 @@ export default function ChannelSettingsClient({
|
||||
<p className="text-sm text-mantle-foreground">Manager</p>
|
||||
</div>
|
||||
</div>
|
||||
{isOwner && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={async () => {
|
||||
if (
|
||||
await confirm({
|
||||
title: 'Remove Manager',
|
||||
description: `Are you sure you want to remove ${personalChannel?.name} as a manager? They will no longer be able to stream or moderate this channel.`,
|
||||
confirmText: 'Remove',
|
||||
cancelText: 'Cancel',
|
||||
})
|
||||
) {
|
||||
removeChannelManager(channel.id, manager.id);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<UserMinus className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
<div className="flex items-center gap-2">
|
||||
<ChannelRoleBadges
|
||||
roles={withPlatformAdmin(
|
||||
['manager', 'chatModerator'] as const,
|
||||
manager.isAdmin
|
||||
)}
|
||||
/>
|
||||
{isOwner && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={async () => {
|
||||
if (
|
||||
await confirm({
|
||||
title: 'Remove Manager',
|
||||
description: `Are you sure you want to remove ${personalChannel?.name} as a manager? They will no longer be able to stream or moderate this channel.`,
|
||||
confirmText: 'Remove',
|
||||
cancelText: 'Cancel',
|
||||
})
|
||||
) {
|
||||
removeChannelManager(channel.id, manager.id);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<UserMinus className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
@@ -798,6 +833,221 @@ export default function ChannelSettingsClient({
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="moderation">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Chat Moderation</CardTitle>
|
||||
<CardDescription>
|
||||
Configure rate limits, slow mode, and blocked words for this channel's live
|
||||
chat.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-lg font-semibold">Moderators</h3>
|
||||
<div className="flex gap-2">
|
||||
<AddChatModeratorDialog
|
||||
channelId={channel.id}
|
||||
existingModerators={[
|
||||
channel.owner.id,
|
||||
...channel.managers.map((manager) => manager.id),
|
||||
...channel.chatModerators.map((moderator) => moderator.id),
|
||||
]}
|
||||
/>
|
||||
<AddChatBotModeratorDialog
|
||||
channelId={channel.id}
|
||||
botAccounts={channel.allBotAccounts}
|
||||
existingBotModerators={channel.chatModeratorBots.map((bot) => bot.id)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between p-3 border rounded-lg">
|
||||
<div className="flex items-center gap-3">
|
||||
<Avatar className="h-10 w-10">
|
||||
<AvatarImage src={channel.owner.pfpUrl} />
|
||||
<AvatarFallback>{channel.owner.slack_id[0]?.toUpperCase()}</AvatarFallback>
|
||||
</Avatar>
|
||||
<div>
|
||||
<p className="font-medium">{channel.ownerPersonalChannel?.name}</p>
|
||||
<p className="text-sm text-mantle-foreground">Owner</p>
|
||||
</div>
|
||||
</div>
|
||||
<ChannelRoleBadges
|
||||
roles={withPlatformAdmin(
|
||||
['owner', 'chatModerator'] as const,
|
||||
channel.owner.isAdmin
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{channel.managers.map((manager) => {
|
||||
const personalChannel = channel.managerPersonalChannels.find(
|
||||
(candidate) => candidate?.ownerId === manager.id
|
||||
);
|
||||
return (
|
||||
<div
|
||||
key={manager.id}
|
||||
className="flex items-center justify-between p-3 border rounded-lg"
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<Avatar className="h-10 w-10">
|
||||
<AvatarImage src={manager.pfpUrl} />
|
||||
<AvatarFallback>{personalChannel?.name}</AvatarFallback>
|
||||
</Avatar>
|
||||
<div>
|
||||
<p className="font-medium">{personalChannel?.name}</p>
|
||||
<p className="text-sm text-mantle-foreground">Manager</p>
|
||||
</div>
|
||||
</div>
|
||||
<ChannelRoleBadges
|
||||
roles={withPlatformAdmin(
|
||||
['manager', 'chatModerator'] as const,
|
||||
manager.isAdmin
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
{channel.chatModerators.map((moderator) => {
|
||||
const personalChannel = channel.chatModeratorPersonalChannels.find(
|
||||
(candidate) => candidate?.ownerId === moderator.id
|
||||
);
|
||||
return (
|
||||
<div
|
||||
key={moderator.id}
|
||||
className="flex items-center justify-between p-3 border rounded-lg"
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<Avatar className="h-10 w-10">
|
||||
<AvatarImage src={moderator.pfpUrl} />
|
||||
<AvatarFallback>{personalChannel?.name}</AvatarFallback>
|
||||
</Avatar>
|
||||
<div>
|
||||
<p className="font-medium">{personalChannel?.name}</p>
|
||||
<p className="text-sm text-mantle-foreground">Chat moderator</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<ChannelRoleBadges
|
||||
roles={withPlatformAdmin(['chatModerator'] as const, moderator.isAdmin)}
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
toast.promise(removeChatModerator(channel.id, moderator.id), {
|
||||
loading: 'Removing moderator...',
|
||||
success: 'Moderator removed',
|
||||
error: 'Failed to remove moderator',
|
||||
});
|
||||
}}
|
||||
>
|
||||
<UserMinus className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
{channel.chatModeratorBots.map((botAccount) => (
|
||||
<div
|
||||
key={botAccount.id}
|
||||
className="flex items-center justify-between p-3 border rounded-lg"
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<Avatar className="h-10 w-10">
|
||||
<AvatarImage src={botAccount.pfpUrl} />
|
||||
<AvatarFallback>{botAccount.slug[0]?.toUpperCase()}</AvatarFallback>
|
||||
</Avatar>
|
||||
<div>
|
||||
<p className="font-medium">{botAccount.displayName}</p>
|
||||
<p className="text-sm text-mantle-foreground">@{botAccount.slug}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<ChannelRoleBadges roles={['botModerator']} />
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
toast.promise(removeChatBotModerator(channel.id, botAccount.id), {
|
||||
loading: 'Removing bot moderator...',
|
||||
success: 'Bot moderator removed',
|
||||
error: 'Failed to remove bot moderator',
|
||||
});
|
||||
}}
|
||||
>
|
||||
<UserMinus className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{channel.chatModerators.length === 0 &&
|
||||
channel.chatModeratorBots.length === 0 && (
|
||||
<p className="text-mantle-foreground text-center py-4">
|
||||
No extra chat moderators yet.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
<UniversalForm
|
||||
fields={[
|
||||
{ name: 'channelId', type: 'hidden', value: channel.id, label: 'Channel ID' },
|
||||
{
|
||||
name: 'slowModeSeconds',
|
||||
label: 'Slow mode (seconds)',
|
||||
type: 'number',
|
||||
value: channel.chatSettings?.slowModeSeconds ?? 0,
|
||||
description: 'Users can send one message per interval. Set 0 to disable.',
|
||||
},
|
||||
{
|
||||
name: 'maxMessageLength',
|
||||
label: 'Max message length',
|
||||
type: 'number',
|
||||
value: channel.chatSettings?.maxMessageLength ?? 400,
|
||||
description: 'Maximum allowed message length in characters.',
|
||||
},
|
||||
{
|
||||
name: 'rateLimitCount',
|
||||
label: 'Messages per window',
|
||||
type: 'number',
|
||||
value: channel.chatSettings?.rateLimitCount ?? 8,
|
||||
description: 'How many messages a user can send in the rate limit window.',
|
||||
},
|
||||
{
|
||||
name: 'rateLimitWindowSeconds',
|
||||
label: 'Rate window (seconds)',
|
||||
type: 'number',
|
||||
value: channel.chatSettings?.rateLimitWindowSeconds ?? 10,
|
||||
description: 'Window size used for spam protection.',
|
||||
},
|
||||
{
|
||||
name: 'blockedTerms',
|
||||
label: 'Blocked terms',
|
||||
value: (channel.chatSettings?.blockedTerms ?? []).join('\n'),
|
||||
textArea: true,
|
||||
textAreaRows: 8,
|
||||
description:
|
||||
'One term per line (or comma-separated). Messages containing these terms are blocked.',
|
||||
},
|
||||
]}
|
||||
schemaName="updateChatModeration"
|
||||
action={updateChatModeration}
|
||||
submitText="Save moderation settings"
|
||||
onActionComplete={handleModerationActionComplete}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
<TabsContent value="utilities">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
@@ -834,6 +1084,74 @@ export default function ChannelSettingsClient({
|
||||
);
|
||||
}
|
||||
|
||||
function RoleBadge({
|
||||
icon: Icon,
|
||||
label,
|
||||
className,
|
||||
}: {
|
||||
icon: LucideIcon;
|
||||
label: string;
|
||||
className: string;
|
||||
}) {
|
||||
return (
|
||||
<Badge variant="outline" className={className}>
|
||||
<Icon className="h-3 w-3 mr-1" />
|
||||
{label}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
|
||||
type ChannelRoleBadgeKey = 'owner' | 'manager' | 'chatModerator' | 'botModerator' | 'platformAdmin';
|
||||
|
||||
const ROLE_BADGE_META: Record<
|
||||
ChannelRoleBadgeKey,
|
||||
{ icon: LucideIcon; label: string; className: string }
|
||||
> = {
|
||||
owner: {
|
||||
icon: Shield,
|
||||
label: 'Owner',
|
||||
className: 'border-primary/30 bg-primary/10 text-primary',
|
||||
},
|
||||
manager: {
|
||||
icon: Wrench,
|
||||
label: 'Manager',
|
||||
className: 'border-sky-500/30 bg-sky-500/10 text-sky-700 dark:text-sky-300',
|
||||
},
|
||||
chatModerator: {
|
||||
icon: MessageSquareWarning,
|
||||
label: 'Chat Mod',
|
||||
className: 'border-emerald-500/30 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300',
|
||||
},
|
||||
botModerator: {
|
||||
icon: Bot,
|
||||
label: 'Bot Mod',
|
||||
className: 'border-cyan-500/30 bg-cyan-500/10 text-cyan-700 dark:text-cyan-300',
|
||||
},
|
||||
platformAdmin: {
|
||||
icon: Shield,
|
||||
label: 'Platform Admin',
|
||||
className: 'border-amber-500/30 bg-amber-500/10 text-amber-700 dark:text-amber-300',
|
||||
},
|
||||
};
|
||||
|
||||
const withPlatformAdmin = (
|
||||
roles: readonly ChannelRoleBadgeKey[],
|
||||
isPlatformAdmin?: boolean
|
||||
): ChannelRoleBadgeKey[] => (isPlatformAdmin ? [...roles, 'platformAdmin'] : [...roles]);
|
||||
|
||||
function ChannelRoleBadges({ roles }: { roles: ChannelRoleBadgeKey[] }) {
|
||||
return (
|
||||
<div className="flex items-center gap-1.5 flex-wrap justify-end">
|
||||
{[...new Set(roles)].map((role) => {
|
||||
const meta = ROLE_BADGE_META[role];
|
||||
return (
|
||||
<RoleBadge key={role} icon={meta.icon} label={meta.label} className={meta.className} />
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AddManagerDialog({
|
||||
channelId,
|
||||
existingManagers,
|
||||
@@ -886,3 +1204,112 @@ function AddManagerDialog({
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function AddChatModeratorDialog({
|
||||
channelId,
|
||||
existingModerators,
|
||||
}: {
|
||||
channelId: string;
|
||||
existingModerators: string[];
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [selectedChannel, setSelectedChannel] = useState('');
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button size="sm" variant="outline">
|
||||
<UserPlus className="h-4 w-4 mr-2" />
|
||||
Add User Moderator
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Add chat moderator</DialogTitle>
|
||||
<DialogDescription>
|
||||
Choose a user who should be able to moderate this channel's chat.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<UserCombobox
|
||||
onValueChange={(value) => {
|
||||
setSelectedChannel(value);
|
||||
}}
|
||||
filter={existingModerators}
|
||||
value={selectedChannel}
|
||||
modal
|
||||
/>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
disabled={!selectedChannel}
|
||||
onClick={() => {
|
||||
toast.promise(addChatModerator(channelId, selectedChannel), {
|
||||
loading: 'Adding moderator...',
|
||||
success: 'Moderator added',
|
||||
error: 'Failed to add moderator',
|
||||
});
|
||||
setOpen(false);
|
||||
setSelectedChannel('');
|
||||
}}
|
||||
>
|
||||
Add Moderator
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function AddChatBotModeratorDialog({
|
||||
channelId,
|
||||
botAccounts,
|
||||
existingBotModerators,
|
||||
}: {
|
||||
channelId: string;
|
||||
botAccounts: Pick<BotAccount, 'id' | 'displayName' | 'slug' | 'pfpUrl'>[];
|
||||
existingBotModerators: string[];
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [selectedBotId, setSelectedBotId] = useState('');
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button size="sm" variant="outline">
|
||||
<Bot className="h-4 w-4 mr-2" />
|
||||
Add Bot Moderator
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Add bot moderator</DialogTitle>
|
||||
<DialogDescription>
|
||||
Look up any bot account by name or slug to grant moderation powers.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<BotCombobox
|
||||
bots={botAccounts}
|
||||
filter={existingBotModerators}
|
||||
value={selectedBotId}
|
||||
onValueChange={setSelectedBotId}
|
||||
modal
|
||||
/>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
disabled={!selectedBotId}
|
||||
onClick={() => {
|
||||
toast.promise(addChatBotModerator(channelId, selectedBotId), {
|
||||
loading: 'Adding bot moderator...',
|
||||
success: 'Bot moderator added',
|
||||
error: 'Failed to add bot moderator',
|
||||
});
|
||||
setOpen(false);
|
||||
setSelectedBotId('');
|
||||
}}
|
||||
>
|
||||
Add Bot
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -22,8 +22,11 @@ export default async function ChannelSettingsPage({
|
||||
include: {
|
||||
owner: true,
|
||||
managers: true,
|
||||
chatModerators: true,
|
||||
chatModeratorBots: true,
|
||||
streamInfo: true,
|
||||
streamKey: true,
|
||||
chatSettings: true,
|
||||
followers: {
|
||||
include: {
|
||||
user: {
|
||||
@@ -52,17 +55,38 @@ export default async function ChannelSettingsPage({
|
||||
const managerPersonalChannels = await Promise.all(
|
||||
channel.managers.map((manager) => resolvePersonalChannel(manager.id))
|
||||
);
|
||||
const managerIds = new Set(channel.managers.map((manager) => manager.id));
|
||||
const extraChatModerators = channel.chatModerators.filter(
|
||||
(moderator) => moderator.id !== channel.ownerId && !managerIds.has(moderator.id)
|
||||
);
|
||||
const chatModeratorPersonalChannels = await Promise.all(
|
||||
extraChatModerators.map((moderator) => resolvePersonalChannel(moderator.id))
|
||||
);
|
||||
const followerPersonalChannels = await Promise.all(
|
||||
channel.followers.map((follower) => resolvePersonalChannel(follower.user.id))
|
||||
);
|
||||
const allBotAccounts = await prisma.botAccount.findMany({
|
||||
select: {
|
||||
id: true,
|
||||
displayName: true,
|
||||
slug: true,
|
||||
pfpUrl: true,
|
||||
},
|
||||
orderBy: {
|
||||
slug: 'asc',
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<ChannelSettingsClient
|
||||
channel={{
|
||||
...channel,
|
||||
chatModerators: extraChatModerators,
|
||||
ownerPersonalChannel,
|
||||
managerPersonalChannels,
|
||||
chatModeratorPersonalChannels,
|
||||
followerPersonalChannels,
|
||||
allBotAccounts,
|
||||
}}
|
||||
isOwner={isOwner}
|
||||
currentUser={user}
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
import LandingPage from '@/components/app/LandingPage/LandingPage';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import StreamGrid from '@/components/app/StreamGrid/StreamGrid';
|
||||
import ConfusedDino from '@/components/ui/confuseddino';
|
||||
import { validateRequest } from '@/lib/auth/validate';
|
||||
import { prisma } from '@hctv/db';
|
||||
import { Avatar, AvatarImage, AvatarFallback } from '@radix-ui/react-avatar';
|
||||
import Image from 'next/image';
|
||||
import Link from 'next/link';
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
@@ -13,67 +11,45 @@ export default async function Home() {
|
||||
if (user && !user?.hasOnboarded) {
|
||||
redirect('/onboarding');
|
||||
}
|
||||
const streams = await prisma.streamInfo.findMany({
|
||||
where: {
|
||||
isLive: true,
|
||||
},
|
||||
include: {
|
||||
channel: true,
|
||||
},
|
||||
});
|
||||
|
||||
const [liveStreams, offlineStreams] = await Promise.all([
|
||||
prisma.streamInfo.findMany({
|
||||
where: { isLive: true },
|
||||
include: { channel: true },
|
||||
}),
|
||||
prisma.streamInfo.findMany({
|
||||
where: { isLive: false },
|
||||
include: { channel: true },
|
||||
}),
|
||||
]);
|
||||
|
||||
if (!user) {
|
||||
return <LandingPage />;
|
||||
}
|
||||
if (!streams.length) {
|
||||
|
||||
if (!liveStreams.length && !offlineStreams.length) {
|
||||
return (
|
||||
<div className="flex justify-center items-center text-center flex-col pt-4 gap-2">
|
||||
<h2>No streams found!</h2>
|
||||
<p>...maybe start one?</p>
|
||||
<ConfusedDino className='w-40 h-40' />
|
||||
<div className="flex min-h-[60vh] flex-col items-center justify-center gap-5 px-4 text-center">
|
||||
<ConfusedDino className="h-28 w-28 opacity-80" />
|
||||
<div className="space-y-1.5">
|
||||
<h2 className="pb-0 text-2xl font-semibold tracking-tight">Nothing live right now</h2>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Nobody's streaming yet — why not be the first?
|
||||
</p>
|
||||
</div>
|
||||
<Link
|
||||
href="/settings/channel"
|
||||
className="inline-flex h-9 items-center justify-center rounded-md bg-primary px-5 text-sm font-medium text-primary-foreground shadow transition-colors hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
>
|
||||
Start streaming
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="p-4">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
|
||||
{streams.map((stream) => (
|
||||
<Link href={`/${stream.username}`} key={stream.id}>
|
||||
<Card className="overflow-hidden hover:shadow-lg transition-shadow">
|
||||
<CardContent className="p-0">
|
||||
<div className="relative">
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src={`/api/stream/thumb/${stream.channel.name}`}
|
||||
width={512}
|
||||
height={512}
|
||||
alt={stream.title}
|
||||
className="w-full h-48 object-cover"
|
||||
/>
|
||||
<div className="absolute bottom-2 left-2 bg-red-600 text-white text-xs font-bold px-2 py-1 rounded">
|
||||
LIVE
|
||||
</div>
|
||||
<div className="absolute bottom-2 right-2 bg-black bg-opacity-70 text-white text-xs px-2 py-1 rounded">
|
||||
{stream.viewers} viewers
|
||||
</div>
|
||||
</div>
|
||||
<div className="p-4">
|
||||
<div className="flex items-start">
|
||||
<Avatar className="h-10 w-10 mr-3">
|
||||
<AvatarImage src={stream.channel.pfpUrl} />
|
||||
<AvatarFallback>{stream.channel.name}</AvatarFallback>
|
||||
</Avatar>
|
||||
<div>
|
||||
<h3 className="font-semibold line-clamp-1">{stream.title}</h3>
|
||||
<p className="text-sm text-muted-foreground">{stream.category}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
<div className="p-3 md:p-6">
|
||||
<StreamGrid liveStreams={liveStreams} offlineStreams={offlineStreams} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -59,10 +59,10 @@ export default async function RootLayout({
|
||||
<StreamInfoProvider>
|
||||
{/* this promise is ugly but i'm lazy to fix the type errors */}
|
||||
<Navbar editLivestream={Promise.resolve(<EditLivestream />)} />
|
||||
<div className="flex flex-1 pt-16">
|
||||
<div className="flex flex-1 pt-16 min-h-0 min-w-0">
|
||||
{/* pt-16 for navbar height */}
|
||||
<Sidebar className="pt-16" />
|
||||
<main className="flex-1 overflow-auto">{children}</main>
|
||||
<main className="flex-1 min-w-0">{children}</main>
|
||||
</div>
|
||||
<Toaster />
|
||||
</StreamInfoProvider>
|
||||
|
||||
58
apps/web/src/app/api/metrics/route.ts
Normal file
58
apps/web/src/app/api/metrics/route.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
import { webMetricsRegistry } from '@/lib/metrics';
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
if (process.env.NODE_ENV === 'production' && !isAuthenticated(req)) {
|
||||
return new NextResponse('Authentication required', {
|
||||
status: 401,
|
||||
headers: { 'WWW-Authenticate': 'Basic' },
|
||||
});
|
||||
}
|
||||
return new Response(await webMetricsRegistry.metrics(), {
|
||||
headers: {
|
||||
'Content-Type': webMetricsRegistry.contentType,
|
||||
'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// source: https://vancelucas.com/blog/how-to-add-http-basic-auth-to-next-js/
|
||||
function isAuthenticated(req: NextRequest) {
|
||||
const authheader = req.headers.get('authorization') ?? req.headers.get('Authorization');
|
||||
|
||||
if (!authheader) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const parts = authheader.split(' ');
|
||||
if (parts.length !== 2) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const scheme = parts[0];
|
||||
const encoded = parts[1];
|
||||
|
||||
if (scheme !== 'Basic' || !encoded) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let decoded: string;
|
||||
try {
|
||||
decoded = Buffer.from(encoded, 'base64').toString();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
|
||||
const separatorIndex = decoded.indexOf(':');
|
||||
if (separatorIndex === -1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const user = decoded.substring(0, separatorIndex);
|
||||
const pass = decoded.substring(separatorIndex + 1);
|
||||
|
||||
return user === process.env.METRICS_USER && pass === process.env.METRICS_PASS;
|
||||
}
|
||||
103
apps/web/src/components/app/BotCombobox/BotCombobox.tsx
Normal file
103
apps/web/src/components/app/BotCombobox/BotCombobox.tsx
Normal file
@@ -0,0 +1,103 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import { Check, ChevronsUpDown } from 'lucide-react';
|
||||
import type { BotAccount } from '@hctv/db';
|
||||
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Command,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandInput,
|
||||
CommandItem,
|
||||
CommandList,
|
||||
} from '@/components/ui/command';
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export function BotCombobox({ bots, filter, value, modal, onValueChange }: Props) {
|
||||
const [open, setOpen] = React.useState(false);
|
||||
|
||||
const selectedBot = bots.find((bot) => bot.id === value);
|
||||
const availableBots = bots.filter((bot) => !filter?.includes(bot.id));
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={setOpen} modal={modal}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
role="combobox"
|
||||
aria-expanded={open}
|
||||
className="w-full justify-between"
|
||||
>
|
||||
{selectedBot ? (
|
||||
<div className="flex items-center gap-2 overflow-hidden">
|
||||
<Avatar className="h-8 w-8 shrink-0">
|
||||
<AvatarImage
|
||||
src={selectedBot.pfpUrl}
|
||||
alt={selectedBot.displayName}
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
/>
|
||||
<AvatarFallback>{selectedBot.displayName[0]?.toUpperCase()}</AvatarFallback>
|
||||
</Avatar>
|
||||
<span className="truncate">{selectedBot.displayName}</span>
|
||||
</div>
|
||||
) : (
|
||||
'Select bot...'
|
||||
)}
|
||||
<ChevronsUpDown className="opacity-50" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-[var(--radix-popover-trigger-width)] p-0">
|
||||
<Command>
|
||||
<CommandInput placeholder="Search bot..." className="h-9" />
|
||||
<CommandList>
|
||||
<CommandEmpty>No bot found.</CommandEmpty>
|
||||
<CommandGroup>
|
||||
{availableBots.map((bot) => (
|
||||
<CommandItem
|
||||
key={bot.id}
|
||||
value={bot.id}
|
||||
onSelect={(currentValue) => {
|
||||
onValueChange(currentValue === value ? '' : currentValue);
|
||||
setOpen(false);
|
||||
}}
|
||||
>
|
||||
<Avatar className="h-8 w-8">
|
||||
<AvatarImage
|
||||
src={bot.pfpUrl}
|
||||
alt={bot.displayName}
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
/>
|
||||
<AvatarFallback>{bot.displayName[0]?.toUpperCase()}</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="flex flex-col">
|
||||
<span>{bot.displayName}</span>
|
||||
<span className="text-xs text-mantle-foreground">@{bot.slug}</span>
|
||||
</div>
|
||||
<Check
|
||||
className={cn('ml-auto', value === bot.id ? 'opacity-100' : 'opacity-0')}
|
||||
/>
|
||||
</CommandItem>
|
||||
))}
|
||||
</CommandGroup>
|
||||
</CommandList>
|
||||
</Command>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
|
||||
type BotLookupAccount = Pick<BotAccount, 'id' | 'displayName' | 'slug' | 'pfpUrl'>;
|
||||
|
||||
type Props = {
|
||||
bots: BotLookupAccount[];
|
||||
filter?: string[];
|
||||
value: string;
|
||||
modal?: boolean;
|
||||
onValueChange: (value: string) => void;
|
||||
};
|
||||
@@ -9,9 +9,11 @@ import { Message } from './message';
|
||||
import { useMap } from '@uidotdev/usehooks';
|
||||
import { EmojiSearch } from './EmojiSearch';
|
||||
import { useQueryState } from 'nuqs';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
export default function ChatPanel(props: Props) {
|
||||
const { username } = useParams();
|
||||
const channelName = (Array.isArray(username) ? username[0] : username) ?? '';
|
||||
const [grant, setGrant] = useQueryState('grant');
|
||||
const [message, setMessage] = useState('');
|
||||
const [chatMessages, setChatMessages] = useState<ChatMessage[]>([]);
|
||||
@@ -21,13 +23,19 @@ export default function ChatPanel(props: Props) {
|
||||
const [emojisToReq, setEmojisToReq] = useState<string[]>([]);
|
||||
const [cursorPosition, setCursorPosition] = useState(0);
|
||||
const textareaRef = useRef<HTMLTextAreaElement | null>(null);
|
||||
const [viewer, setViewer] = useState<{ id: string; username: string } | null>(null);
|
||||
const [canModerate, setCanModerate] = useState(false);
|
||||
const [chatAccess, setChatAccess] = useState<ChatAccessState>({
|
||||
canSend: true,
|
||||
restriction: null,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
console.log('Initializing WebSocket connection for user:', username);
|
||||
const socket = new WebSocket(
|
||||
`ws${window.location.protocol === 'https:' ? 's' : ''}://${
|
||||
window.location.host
|
||||
}/api/stream/chat/ws/${username}?grant=${grant}`
|
||||
}/api/stream/chat/ws/${channelName}?grant=${grant}`
|
||||
);
|
||||
socketRef.current = socket;
|
||||
|
||||
@@ -50,6 +58,35 @@ export default function ChatPanel(props: Props) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.type === 'session') {
|
||||
setViewer(data.viewer ?? null);
|
||||
setCanModerate(Boolean(data.permissions?.canModerate));
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.type === 'chatAccess') {
|
||||
setChatAccess({
|
||||
canSend: Boolean(data.canSend),
|
||||
restriction: data.restriction ?? null,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.type === 'systemMsg') {
|
||||
setChatMessages((prev) => [...prev, { message: data.message, type: 'systemMsg' }]);
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.type === 'messageDeleted') {
|
||||
setChatMessages((prev) => prev.filter((message) => message.msgId !== data.msgId));
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.type === 'moderationError') {
|
||||
toast.error(data.message || 'Message blocked by moderation rules.');
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.type === 'message') {
|
||||
console.log('Adding new chat message:', data);
|
||||
setChatMessages((prev) => [...prev, data]);
|
||||
@@ -72,7 +109,7 @@ export default function ChatPanel(props: Props) {
|
||||
return () => {
|
||||
socket.close();
|
||||
};
|
||||
}, [username]);
|
||||
}, [channelName]);
|
||||
|
||||
useEffect(() => {
|
||||
if (scrollRef.current) {
|
||||
@@ -84,6 +121,14 @@ export default function ChatPanel(props: Props) {
|
||||
}, [chatMessages]);
|
||||
|
||||
const sendMessage = () => {
|
||||
if (!chatAccess.canSend) {
|
||||
toast.error(
|
||||
chatAccess.restriction?.type === 'timeout'
|
||||
? 'You are currently timed out in this chat.'
|
||||
: 'You are currently banned from this chat.'
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!message.trim()) return;
|
||||
|
||||
if (socketRef.current && socketRef.current.readyState === WebSocket.OPEN) {
|
||||
@@ -93,7 +138,7 @@ export default function ChatPanel(props: Props) {
|
||||
const socket = new WebSocket(
|
||||
`ws${window.location.protocol === 'https:' ? 's' : ''}://${
|
||||
window.location.host
|
||||
}/api/stream/chat/ws/${username}?grant=${grant}`
|
||||
}/api/stream/chat/ws/${channelName}?grant=${grant}`
|
||||
);
|
||||
socket.onopen = () => {
|
||||
socket.send(JSON.stringify({ type: 'message', message }));
|
||||
@@ -102,6 +147,15 @@ export default function ChatPanel(props: Props) {
|
||||
}
|
||||
};
|
||||
|
||||
const sendModerationCommand = (command: ChatModerationCommand) => {
|
||||
if (!socketRef.current || socketRef.current.readyState !== WebSocket.OPEN) {
|
||||
toast.error('Chat connection is offline.');
|
||||
return;
|
||||
}
|
||||
|
||||
socketRef.current.send(JSON.stringify(command));
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const interval = setInterval(() => {
|
||||
if (socketRef.current && socketRef.current.readyState === WebSocket.OPEN) {
|
||||
@@ -146,7 +200,7 @@ export default function ChatPanel(props: Props) {
|
||||
const socket = new WebSocket(
|
||||
`ws${window.location.protocol === 'https:' ? 's' : ''}://${
|
||||
window.location.host
|
||||
}/api/stream/chat/ws/${username}?grant=${grant}`
|
||||
}/api/stream/chat/ws/${channelName}?grant=${grant}`
|
||||
);
|
||||
|
||||
socket.onopen = () => {
|
||||
@@ -209,7 +263,7 @@ export default function ChatPanel(props: Props) {
|
||||
setEmojisToReq([]);
|
||||
};
|
||||
}
|
||||
}, [emojisToReq, emojiMap, username]);
|
||||
}, [emojisToReq, emojiMap, channelName]);
|
||||
|
||||
const handleEmojiSelect = (emojiName: string) => {
|
||||
if (!textareaRef.current) return;
|
||||
@@ -260,12 +314,24 @@ export default function ChatPanel(props: Props) {
|
||||
message={msg.message}
|
||||
type={msg.type}
|
||||
emojiMap={emojiMap}
|
||||
msgId={msg.msgId}
|
||||
canModerate={canModerate && Boolean(viewer?.id)}
|
||||
viewerId={viewer?.id}
|
||||
channelName={channelName}
|
||||
onModerationCommand={sendModerationCommand}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
{!props.isObsPanel && (
|
||||
<div className="p-3 border-t border-border relative">
|
||||
{!chatAccess.canSend && (
|
||||
<p className="mb-2 text-xs text-destructive">
|
||||
{chatAccess.restriction?.type === 'timeout'
|
||||
? `Timed out${chatAccess.restriction.expiresAt ? ` until ${new Date(chatAccess.restriction.expiresAt).toLocaleTimeString()}` : ''}.`
|
||||
: 'You are banned from sending messages in this chat.'}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex gap-2">
|
||||
<Textarea
|
||||
ref={textareaRef}
|
||||
@@ -289,12 +355,13 @@ export default function ChatPanel(props: Props) {
|
||||
placeholder="Send a message..."
|
||||
className="flex-1 bg-background/50 border-border focus-visible:ring-1 focus-visible:ring-primary focus-visible:ring-offset-0 min-h-[40px] max-h-[100px] resize-none py-2 text-sm"
|
||||
rows={1}
|
||||
disabled={!chatAccess.canSend}
|
||||
/>
|
||||
<Button
|
||||
size="icon"
|
||||
className="shrink-0 transition-colors"
|
||||
onClick={sendMessage}
|
||||
disabled={!message.trim()}
|
||||
disabled={!message.trim() || !chatAccess.canSend}
|
||||
>
|
||||
<Send className="h-4 w-4" />
|
||||
</Button>
|
||||
@@ -317,6 +384,32 @@ export interface ChatMessage {
|
||||
user?: User;
|
||||
message: string;
|
||||
type: 'message' | 'systemMsg';
|
||||
msgId?: string;
|
||||
}
|
||||
|
||||
export interface ChatModerationCommand {
|
||||
type:
|
||||
| 'mod:deleteMessage'
|
||||
| 'mod:timeoutUser'
|
||||
| 'mod:banUser'
|
||||
| 'mod:unbanUser'
|
||||
| 'mod:liftTimeout';
|
||||
msgId?: string;
|
||||
targetUserId?: string;
|
||||
targetUsername?: string;
|
||||
durationSeconds?: number;
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
interface ChatAccessState {
|
||||
canSend: boolean;
|
||||
restriction: ChatRestriction | null;
|
||||
}
|
||||
|
||||
interface ChatRestriction {
|
||||
type: 'timeout' | 'ban';
|
||||
reason?: string;
|
||||
expiresAt?: string | null;
|
||||
}
|
||||
|
||||
export interface User {
|
||||
@@ -325,6 +418,8 @@ export interface User {
|
||||
pfpUrl: string;
|
||||
isBot: boolean;
|
||||
displayName?: string;
|
||||
isPlatformAdmin?: boolean;
|
||||
channelRole?: 'owner' | 'manager' | 'chatModerator' | 'botModerator' | null;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
|
||||
@@ -1,10 +1,164 @@
|
||||
import { User } from './ChatPanel';
|
||||
import React from 'react';
|
||||
'use client';
|
||||
|
||||
import { ChatModerationCommand, User } from './ChatPanel';
|
||||
import { useState } from 'react';
|
||||
import Image from 'next/image';
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
|
||||
import { Bot } from 'lucide-react';
|
||||
import {
|
||||
Ban,
|
||||
Bot,
|
||||
Clock3,
|
||||
Crown,
|
||||
EllipsisVertical,
|
||||
Eraser,
|
||||
Flag,
|
||||
Shield,
|
||||
ShieldAlert,
|
||||
ShieldCheck,
|
||||
UserRoundCheck,
|
||||
Wrench,
|
||||
} from 'lucide-react';
|
||||
import type { LucideIcon } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { toast } from 'sonner';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
type ChannelRole = NonNullable<User['channelRole']>;
|
||||
|
||||
const ROLE_META: Record<ChannelRole, { label: string; icon: LucideIcon; className: string }> = {
|
||||
owner: { label: 'Owner', icon: Crown, className: 'text-amber-500' },
|
||||
manager: { label: 'Manager', icon: Wrench, className: 'text-violet-500' },
|
||||
chatModerator: { label: 'Chat Mod', icon: Shield, className: 'text-emerald-500' },
|
||||
botModerator: { label: 'Bot Mod', icon: ShieldCheck, className: 'text-cyan-500' },
|
||||
};
|
||||
|
||||
function TooltipIcon({
|
||||
icon: Icon,
|
||||
label,
|
||||
className,
|
||||
}: {
|
||||
icon: LucideIcon;
|
||||
label: string;
|
||||
className?: string;
|
||||
}) {
|
||||
return (
|
||||
<Tooltip delayDuration={200}>
|
||||
<TooltipTrigger asChild>
|
||||
<Icon className={cn('size-3.5 shrink-0', className)} />
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top">{label}</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
function UsernameRow({ user, displayName }: { user?: User; displayName?: string }) {
|
||||
const role = user?.channelRole ? ROLE_META[user.channelRole] : null;
|
||||
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<span className="font-semibold text-primary shrink-0 flex items-center gap-1">
|
||||
{user?.isBot && <TooltipIcon icon={Bot} label="Bot" className="text-muted-foreground" />}
|
||||
{role && <TooltipIcon icon={role.icon} label={role.label} className={role.className} />}
|
||||
{user?.isPlatformAdmin && (
|
||||
<TooltipIcon icon={ShieldAlert} label="Platform Admin" className="text-destructive" />
|
||||
)}
|
||||
<span>{displayName}</span>
|
||||
<span className="font-normal text-muted-foreground select-none">:</span>
|
||||
</span>
|
||||
</TooltipProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function ReportDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
displayName,
|
||||
message,
|
||||
reportReason,
|
||||
onReasonChange,
|
||||
onSubmit,
|
||||
isSubmitting,
|
||||
}: {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
displayName?: string;
|
||||
message: string;
|
||||
reportReason: string;
|
||||
onReasonChange: (value: string) => void;
|
||||
onSubmit: () => void;
|
||||
isSubmitting: boolean;
|
||||
}) {
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Report message</DialogTitle>
|
||||
<DialogDescription>
|
||||
Message against Hack Club's Code of Conduct? Let us know!
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-3">
|
||||
<div className="text-sm text-muted-foreground rounded-md border p-3 bg-muted/30">
|
||||
<p className="font-medium text-foreground mb-1">Reported user</p>
|
||||
<p>{displayName}</p>
|
||||
<p className="mt-2">{message}</p>
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-sm font-medium">Reason</label>
|
||||
<Textarea
|
||||
value={reportReason}
|
||||
onChange={(e) => onReasonChange(e.target.value)}
|
||||
placeholder="Describe why this should be reviewed (harassment, hate speech, spam, threats, etc)."
|
||||
rows={5}
|
||||
className="mt-2"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground mt-1">Minimum 10 characters.</p>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={isSubmitting}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={onSubmit} disabled={isSubmitting || reportReason.trim().length < 10}>
|
||||
Submit report
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
export function Message({
|
||||
user,
|
||||
message,
|
||||
type,
|
||||
emojiMap,
|
||||
msgId,
|
||||
canModerate,
|
||||
viewerId,
|
||||
channelName,
|
||||
onModerationCommand,
|
||||
}: MessageProps) {
|
||||
const [reportOpen, setReportOpen] = useState(false);
|
||||
const [reportReason, setReportReason] = useState('');
|
||||
const [isSubmittingReport, setIsSubmittingReport] = useState(false);
|
||||
const displayName = user?.displayName || user?.username;
|
||||
|
||||
export function Message({ user, message, type, emojiMap }: MessageProps) {
|
||||
if (type === 'systemMsg') {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-1">
|
||||
@@ -13,66 +167,207 @@ export function Message({ user, message, type, emojiMap }: MessageProps) {
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="group hover:bg-primary/5 rounded px-2 py-1 -mx-2 transition-colors">
|
||||
<div className="flex items-start gap-2">
|
||||
<span className="font-semibold text-primary shrink-0 flex items-center gap-1">
|
||||
{user?.isBot && <Bot className="size-4 text-muted-foreground" />}
|
||||
<span>{user?.displayName || user?.username}</span>
|
||||
</span>
|
||||
<span
|
||||
lang="en"
|
||||
className="text-foreground break-words overflow-wrap-anywhere min-w-0 flex-1"
|
||||
style={{ overflowWrap: 'anywhere', wordBreak: 'break-word' }}
|
||||
>
|
||||
<EmojiRenderer text={message} emojiMap={emojiMap} />
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const submitReport = async () => {
|
||||
if (!user?.id || !viewerId || viewerId === user.id) return;
|
||||
|
||||
export function EmojiRenderer({ text, emojiMap }: EmojiRendererProps) {
|
||||
if (!text) return null;
|
||||
const reason = reportReason.trim();
|
||||
if (reason.length < 10) {
|
||||
toast.error('Please include at least 10 characters explaining the report.');
|
||||
return;
|
||||
}
|
||||
|
||||
const parts = text.split(/(:[\w\-+]+:)/g);
|
||||
setIsSubmittingReport(true);
|
||||
try {
|
||||
const res = await fetch('/api/stream/chat/report', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
channelName,
|
||||
targetUserId: user.id,
|
||||
targetUsername: displayName,
|
||||
msgId,
|
||||
message,
|
||||
reason,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
toast.error((await res.text()) || 'Failed to submit report.');
|
||||
return;
|
||||
}
|
||||
|
||||
toast.success('Report submitted. Thanks for helping keep chat safe.');
|
||||
setReportReason('');
|
||||
setReportOpen(false);
|
||||
} catch {
|
||||
toast.error('Failed to submit report.');
|
||||
} finally {
|
||||
setIsSubmittingReport(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleReportOpenChange = (open: boolean) => {
|
||||
setReportOpen(open);
|
||||
if (!open) setReportReason('');
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{parts.map((part, index) => {
|
||||
if (part.match(/^:[\w\-+]+:$/)) {
|
||||
const emojiName = part.replaceAll(':', '');
|
||||
const emojiUrl = emojiMap.get(emojiName);
|
||||
<div className="group hover:bg-primary/5 rounded px-2 py-1 -mx-2 transition-colors">
|
||||
<div className="flex items-start gap-1.5">
|
||||
<UsernameRow user={user} displayName={displayName} />
|
||||
<span
|
||||
lang="en"
|
||||
className="text-foreground min-w-0 flex-1"
|
||||
style={{ overflowWrap: 'anywhere', wordBreak: 'break-word' }}
|
||||
>
|
||||
<EmojiRenderer text={message} emojiMap={emojiMap} />
|
||||
</span>
|
||||
{type === 'message' && user?.id && (
|
||||
<MessageActionsMenu
|
||||
user={user}
|
||||
msgId={msgId}
|
||||
canModerate={canModerate}
|
||||
viewerId={viewerId}
|
||||
onModerationCommand={onModerationCommand}
|
||||
onOpenReport={() => setReportOpen(true)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<ReportDialog
|
||||
open={reportOpen}
|
||||
onOpenChange={handleReportOpenChange}
|
||||
displayName={displayName}
|
||||
message={message}
|
||||
reportReason={reportReason}
|
||||
onReasonChange={setReportReason}
|
||||
onSubmit={submitReport}
|
||||
isSubmitting={isSubmittingReport}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
if (emojiUrl) {
|
||||
return (
|
||||
<TooltipProvider key={index}>
|
||||
<Tooltip delayDuration={250}>
|
||||
function MessageActionsMenu({
|
||||
user,
|
||||
msgId,
|
||||
canModerate,
|
||||
viewerId,
|
||||
onModerationCommand,
|
||||
onOpenReport,
|
||||
}: {
|
||||
user: User;
|
||||
msgId?: string;
|
||||
canModerate?: boolean;
|
||||
viewerId?: string;
|
||||
onModerationCommand?: (command: ChatModerationCommand) => void;
|
||||
onOpenReport: () => void;
|
||||
}) {
|
||||
if (!viewerId || !user.id || user.id === viewerId) return null;
|
||||
|
||||
const displayName = user.displayName || user.username;
|
||||
const canMod = Boolean(canModerate && onModerationCommand);
|
||||
|
||||
const runModeration = (command: ChatModerationCommand) => onModerationCommand?.(command);
|
||||
|
||||
const timeout = (durationSeconds: number) =>
|
||||
runModeration({
|
||||
type: 'mod:timeoutUser',
|
||||
targetUserId: user.id,
|
||||
targetUsername: displayName,
|
||||
durationSeconds,
|
||||
reason: 'Timed out by moderator',
|
||||
});
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="h-7 w-7 opacity-0 group-hover:opacity-100">
|
||||
<EllipsisVertical className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-52">
|
||||
<DropdownMenuItem onClick={onOpenReport}>
|
||||
<Flag className="mr-2 h-4 w-4" />
|
||||
Report user
|
||||
</DropdownMenuItem>
|
||||
{canMod && (
|
||||
<>
|
||||
<DropdownMenuItem
|
||||
onClick={() => msgId && runModeration({ type: 'mod:deleteMessage', msgId })}
|
||||
>
|
||||
<Eraser className="mr-2 h-4 w-4" />
|
||||
Delete message
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => timeout(300)}>
|
||||
<Clock3 className="mr-2 h-4 w-4" />
|
||||
Timeout 5 min
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => timeout(3600)}>
|
||||
<Clock3 className="mr-2 h-4 w-4" />
|
||||
Timeout 1 hour
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
className="text-destructive"
|
||||
onClick={() =>
|
||||
runModeration({
|
||||
type: 'mod:banUser',
|
||||
targetUserId: user.id,
|
||||
targetUsername: displayName,
|
||||
reason: 'Banned by moderator',
|
||||
})
|
||||
}
|
||||
>
|
||||
<Ban className="mr-2 h-4 w-4" />
|
||||
Ban user
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() =>
|
||||
runModeration({
|
||||
type: 'mod:liftTimeout',
|
||||
targetUserId: user.id,
|
||||
targetUsername: displayName,
|
||||
})
|
||||
}
|
||||
>
|
||||
<UserRoundCheck className="mr-2 h-4 w-4" />
|
||||
Lift timeout/ban
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
}
|
||||
|
||||
export function EmojiRenderer({ text, emojiMap }: { text: string; emojiMap: Map<string, string> }) {
|
||||
if (!text) return null;
|
||||
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<>
|
||||
{text.split(/(:[\w\-+]+:)/g).map((part, i) => {
|
||||
if (part.match(/^:[\w\-+]+:$/)) {
|
||||
const name = part.replaceAll(':', '');
|
||||
const url = emojiMap.get(name);
|
||||
if (url) {
|
||||
return (
|
||||
<Tooltip key={i} delayDuration={250}>
|
||||
<TooltipTrigger asChild>
|
||||
<span className="inline-flex items-center align-middle mx-0.5">
|
||||
<Image
|
||||
src={emojiUrl}
|
||||
alt={part}
|
||||
width={20}
|
||||
height={20}
|
||||
className="inline-block"
|
||||
/>
|
||||
<Image src={url} alt={part} width={20} height={20} className="inline-block" />
|
||||
</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{part}</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
);
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Preserve text as-is, handling whitespace properly
|
||||
if (part) {
|
||||
return <span key={index}>{part}</span>;
|
||||
}
|
||||
return null;
|
||||
})}
|
||||
</>
|
||||
return part ? <span key={i}>{part}</span> : null;
|
||||
})}
|
||||
</>
|
||||
</TooltipProvider>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -81,9 +376,9 @@ interface MessageProps {
|
||||
message: string;
|
||||
type: 'message' | 'systemMsg';
|
||||
emojiMap: Map<string, string>;
|
||||
}
|
||||
|
||||
interface EmojiRendererProps {
|
||||
text: string;
|
||||
emojiMap: Map<string, string>;
|
||||
msgId?: string;
|
||||
canModerate?: boolean;
|
||||
viewerId?: string;
|
||||
channelName: string;
|
||||
onModerationCommand?: (command: ChatModerationCommand) => void;
|
||||
}
|
||||
|
||||
187
apps/web/src/components/app/StreamGrid/StreamGrid.tsx
Normal file
187
apps/web/src/components/app/StreamGrid/StreamGrid.tsx
Normal file
@@ -0,0 +1,187 @@
|
||||
'use client';
|
||||
|
||||
import Link from 'next/link';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import ConfusedDino from '@/components/ui/confuseddino';
|
||||
import {
|
||||
Carousel,
|
||||
CarouselContent,
|
||||
CarouselItem,
|
||||
CarouselNext,
|
||||
CarouselPrevious,
|
||||
} from '@/components/ui/carousel';
|
||||
import type { Channel, StreamInfo } from '@hctv/db';
|
||||
|
||||
type StreamWithChannel = StreamInfo & { channel: Channel };
|
||||
|
||||
interface StreamGridProps {
|
||||
liveStreams: StreamWithChannel[];
|
||||
offlineStreams: StreamWithChannel[];
|
||||
}
|
||||
|
||||
export default function StreamGrid({ liveStreams, offlineStreams }: StreamGridProps) {
|
||||
const sortedLiveStreams = [...liveStreams].sort((a, b) => b.viewers - a.viewers);
|
||||
|
||||
return (
|
||||
<div className="space-y-8 md:space-y-10 min-w-0">
|
||||
{sortedLiveStreams.length === 0 && (
|
||||
<div className="flex flex-col items-center gap-4 py-10 text-center">
|
||||
<ConfusedDino className="h-24 w-24 opacity-70" />
|
||||
<div className="space-y-1">
|
||||
<p className="font-semibold">Nobody's live right now</p>
|
||||
<p className="text-sm text-muted-foreground">Why not be the first?</p>
|
||||
</div>
|
||||
<Link
|
||||
href="/settings/channel"
|
||||
className="inline-flex h-9 items-center justify-center rounded-md bg-primary px-5 text-sm font-medium text-primary-foreground shadow-sm transition-colors hover:bg-primary/90"
|
||||
>
|
||||
Start streaming
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{sortedLiveStreams.length > 0 && (
|
||||
<section>
|
||||
<SectionHeading label="Live now" count={sortedLiveStreams.length} />
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 md:gap-4 lg:grid-cols-3 xl:grid-cols-4">
|
||||
{sortedLiveStreams.map((stream) => (
|
||||
<StreamCard key={stream.id} stream={stream} />
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{offlineStreams.length > 0 && (
|
||||
<section className="w-full min-w-0">
|
||||
<SectionHeading label="Offline channels" count={offlineStreams.length} />
|
||||
<div className="px-10">
|
||||
<Carousel className="w-full max-w-full" opts={{ dragFree: true, containScroll: 'trimSnaps' }}>
|
||||
<CarouselContent className="-ml-2">
|
||||
{offlineStreams.map((stream) => (
|
||||
<CarouselItem key={stream.id} className="basis-auto pl-2 md:pl-3">
|
||||
<OfflineCard stream={stream} />
|
||||
</CarouselItem>
|
||||
))}
|
||||
</CarouselContent>
|
||||
<CarouselPrevious className="hidden md:flex" />
|
||||
<CarouselNext className="hidden md:flex" />
|
||||
</Carousel>
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function StreamCard({ stream }: { stream: StreamWithChannel }) {
|
||||
return (
|
||||
<Link href={`/${stream.username}`} className="group block w-full max-w-sm">
|
||||
<div className="overflow-hidden rounded-lg border border-border bg-card shadow-sm transition-shadow duration-200 group-hover:shadow-md">
|
||||
<div className="relative aspect-video overflow-hidden bg-muted">
|
||||
<img
|
||||
src={`/api/stream/thumb/${stream.channel.name}`}
|
||||
alt={stream.title}
|
||||
className="absolute inset-0 object-cover"
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
/>
|
||||
<div className="absolute inset-0 bg-gradient-to-t from-black/60 via-transparent to-transparent" />
|
||||
<div className="absolute bottom-1.5 left-1.5 md:bottom-2 md:left-2">
|
||||
<LiveBadge small />
|
||||
</div>
|
||||
<div className="absolute bottom-1.5 right-1.5 md:bottom-2 md:right-2">
|
||||
<ViewerCount count={stream.viewers} small />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-start gap-2 p-2 md:gap-3 md:p-3">
|
||||
<Avatar className="h-7 w-7 shrink-0 ring-1 ring-primary/20 md:h-8 md:w-8">
|
||||
<AvatarImage
|
||||
src={stream.channel.pfpUrl}
|
||||
alt={stream.channel.name}
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
/>
|
||||
<AvatarFallback className="text-[10px]">
|
||||
{stream.channel.name.slice(0, 2).toUpperCase()}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate text-xs font-medium leading-snug md:text-sm">{stream.title}</p>
|
||||
<p className="truncate text-[10px] text-muted-foreground md:text-xs">
|
||||
{stream.channel.name}
|
||||
</p>
|
||||
{stream.category && (
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className="mt-1 rounded-full px-1.5 py-0 text-[9px] font-medium md:mt-1.5 md:px-2 md:text-[10px]"
|
||||
>
|
||||
{stream.category}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
function OfflineCard({ stream }: { stream: StreamWithChannel }) {
|
||||
return (
|
||||
<Link href={`/${stream.username}`} className="group inline-flex w-[70px]">
|
||||
<div className="flex w-[70px] flex-col items-center gap-1 rounded-lg p-1.5 transition-colors duration-150 hover:bg-muted/50 sm:w-[78px] md:w-[86px] md:gap-1.5 md:p-2">
|
||||
<div className="relative">
|
||||
<Avatar className="h-9 w-9 ring-2 ring-border transition-colors duration-150 group-hover:ring-border/60 sm:h-10 sm:w-10 md:h-11 md:w-11">
|
||||
<AvatarImage
|
||||
src={stream.channel.pfpUrl}
|
||||
alt={stream.channel.name}
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
/>
|
||||
<AvatarFallback className="text-xs font-semibold">
|
||||
{stream.channel.name.slice(0, 2).toUpperCase()}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<span className="absolute -bottom-0.5 -right-0.5 h-2.5 w-2.5 rounded-full border-2 border-background bg-muted-foreground/40" />
|
||||
</div>
|
||||
<p className="w-full truncate text-center text-[10px] font-medium">{stream.channel.name}</p>
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
function LiveBadge({ small }: { small?: boolean }) {
|
||||
return (
|
||||
<span
|
||||
className={`flex items-center gap-1 rounded-full bg-red-600 font-bold uppercase tracking-wide text-white ${small ? 'px-1.5 py-0.5 text-[9px]' : 'px-2 py-0.5 text-[10px]'}`}
|
||||
>
|
||||
<span className="inline-block h-1.5 w-1.5 animate-pulse rounded-full bg-white" />
|
||||
Live
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function ViewerCount({ count, small }: { count: number; small?: boolean }) {
|
||||
return (
|
||||
<span
|
||||
className={`flex items-center gap-1 rounded-full bg-black/70 font-medium text-white backdrop-blur-sm ${small ? 'px-1.5 py-0.5 text-[9px]' : 'px-2 py-0.5 text-xs'}`}
|
||||
>
|
||||
<span className="inline-block h-1.5 w-1.5 rounded-full bg-red-400" />
|
||||
{count.toLocaleString()}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function SectionHeading({ label, count }: { label: string; count?: number }) {
|
||||
return (
|
||||
<div className="mb-3 flex items-center gap-2">
|
||||
<h2 className="pb-0 text-sm font-semibold tracking-tight md:text-base">{label}</h2>
|
||||
{count !== undefined && (
|
||||
<span className="rounded-full bg-primary/10 px-2 py-0.5 text-xs font-medium text-primary">
|
||||
{count}
|
||||
</span>
|
||||
)}
|
||||
<div className="ml-2 h-px flex-1 bg-border" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -20,7 +20,7 @@ export default function StreamPlayer() {
|
||||
const { username } = useParams();
|
||||
const { session } = useSession();
|
||||
const { streamInfo: userInfo } = useUserStreamInfo(username!.toString());
|
||||
|
||||
|
||||
const videoRef = useRef(null);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -38,7 +38,7 @@ export default function StreamPlayer() {
|
||||
debug: process.env.NODE_ENV === 'development',
|
||||
backBufferLength: 90,
|
||||
enableWorker: true,
|
||||
maxLiveSyncPlaybackRate: 1.5,
|
||||
maxLiveSyncPlaybackRate: 1,
|
||||
liveSyncDurationCount: 2,
|
||||
liveMaxLatencyDurationCount: 4,
|
||||
};
|
||||
@@ -57,12 +57,7 @@ export default function StreamPlayer() {
|
||||
|
||||
return (
|
||||
<MediaController className="w-full aspect-video">
|
||||
<HlsVideo
|
||||
ref={videoRef}
|
||||
slot="media"
|
||||
crossOrigin="anonymous"
|
||||
autoplay
|
||||
/>
|
||||
<HlsVideo ref={videoRef} slot="media" crossOrigin="anonymous" autoplay />
|
||||
<MediaLoadingIndicator slot="centered-chrome" noAutohide />
|
||||
<MediaControlBar className="w-full px-2">
|
||||
<div className="flex items-center gap-2">
|
||||
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
editBotSchema,
|
||||
onboardSchema,
|
||||
streamInfoEditSchema,
|
||||
updateChatModerationSchema,
|
||||
updateChannelSettingsSchema,
|
||||
} from '@/lib/form/zod';
|
||||
|
||||
@@ -37,6 +38,7 @@ export const schemaDb = [
|
||||
{ name: 'createBot', zod: createBotSchema },
|
||||
{ name: 'editBot', zod: editBotSchema },
|
||||
{ name: 'changeUsername', zod: changeUsernameSchema },
|
||||
{ name: 'updateChatModeration', zod: updateChatModerationSchema },
|
||||
] as const;
|
||||
|
||||
export function UniversalForm<T extends z.ZodType>({
|
||||
|
||||
@@ -22,7 +22,7 @@ import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
export function UserCombobox(props: Props) {
|
||||
const [open, setOpen] = React.useState(false);
|
||||
const [internalValue, setInternalValue] = React.useState('');
|
||||
|
||||
|
||||
// Use external value if provided, otherwise use internal state
|
||||
const value = props.value ?? internalValue;
|
||||
const setValue = props.onValueChange ?? setInternalValue;
|
||||
@@ -30,10 +30,7 @@ export function UserCombobox(props: Props) {
|
||||
data: fetchedUsers,
|
||||
error,
|
||||
isLoading,
|
||||
} = useSWR<APIResponse>(
|
||||
props.users ? null : '/api/stream/info?personal=true',
|
||||
fetcher
|
||||
);
|
||||
} = useSWR<APIResponse>(props.users ? null : '/api/stream/info?personal=true', fetcher);
|
||||
|
||||
const users = props.users || fetchedUsers;
|
||||
|
||||
@@ -48,17 +45,22 @@ export function UserCombobox(props: Props) {
|
||||
aria-expanded={open}
|
||||
className="w-[200px] justify-between"
|
||||
>
|
||||
{value
|
||||
? (
|
||||
<div className='flex items-center gap-2'>
|
||||
<Avatar className="h-8 w-8">
|
||||
<AvatarImage src={users?.find((user) => user.username === value)?.channel.pfpUrl} alt={value} />
|
||||
<AvatarFallback>{value[0]}</AvatarFallback>
|
||||
</Avatar>
|
||||
<span>{users?.find((user) => user.username === value)?.username}</span>
|
||||
</div>
|
||||
)
|
||||
: 'Select user...'}
|
||||
{value ? (
|
||||
<div className="flex items-center gap-2">
|
||||
<Avatar className="h-8 w-8">
|
||||
<AvatarImage
|
||||
src={users?.find((user) => user.username === value)?.channel.pfpUrl}
|
||||
alt={value}
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
/>
|
||||
<AvatarFallback>{value[0]}</AvatarFallback>
|
||||
</Avatar>
|
||||
<span>{users?.find((user) => user.username === value)?.username}</span>
|
||||
</div>
|
||||
) : (
|
||||
'Select user...'
|
||||
)}
|
||||
<ChevronsUpDown className="opacity-50" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
@@ -68,28 +70,35 @@ export function UserCombobox(props: Props) {
|
||||
<CommandList>
|
||||
<CommandEmpty>No user found.</CommandEmpty>
|
||||
<CommandGroup>
|
||||
{users?.filter(user => !props.filter?.some(filterStr => user.userId === filterStr)).map((user) => (
|
||||
<CommandItem
|
||||
key={user.channelId}
|
||||
value={user.username}
|
||||
onSelect={(currentValue) => {
|
||||
setValue(currentValue === value ? '' : currentValue);
|
||||
setOpen(false);
|
||||
}}
|
||||
>
|
||||
<Avatar className="h-8 w-8">
|
||||
<AvatarImage src={user.channel.pfpUrl} alt={user.username} />
|
||||
<AvatarFallback>{user.username[0]}</AvatarFallback>
|
||||
</Avatar>
|
||||
{user.username}
|
||||
<Check
|
||||
className={cn(
|
||||
'ml-auto',
|
||||
value === user.username ? 'opacity-100' : 'opacity-0'
|
||||
)}
|
||||
/>
|
||||
</CommandItem>
|
||||
))}
|
||||
{users
|
||||
?.filter((user) => !props.filter?.some((filterStr) => user.userId === filterStr))
|
||||
.map((user) => (
|
||||
<CommandItem
|
||||
key={user.channelId}
|
||||
value={user.username}
|
||||
onSelect={(currentValue) => {
|
||||
setValue(currentValue === value ? '' : currentValue);
|
||||
setOpen(false);
|
||||
}}
|
||||
>
|
||||
<Avatar className="h-8 w-8">
|
||||
<AvatarImage
|
||||
src={user.channel.pfpUrl}
|
||||
alt={user.username}
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
/>
|
||||
<AvatarFallback>{user.username[0]}</AvatarFallback>
|
||||
</Avatar>
|
||||
{user.username}
|
||||
<Check
|
||||
className={cn(
|
||||
'ml-auto',
|
||||
value === user.username ? 'opacity-100' : 'opacity-0'
|
||||
)}
|
||||
/>
|
||||
</CommandItem>
|
||||
))}
|
||||
</CommandGroup>
|
||||
</CommandList>
|
||||
</Command>
|
||||
@@ -105,4 +114,4 @@ type Props = {
|
||||
filter?: string[];
|
||||
modal?: boolean;
|
||||
onValueChange?: (value: string) => void;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Avatar, AvatarImage } from '@/components/ui/avatar';
|
||||
import type { StreamInfo, Channel } from '@hctv/db';
|
||||
import FollowButton from './follow';
|
||||
import FollowCountText from './followCount';
|
||||
import StreamUptime from './streamUptime';
|
||||
import ViewerCount from './viewerCount';
|
||||
import { Preview } from '@/components/ui/channel-desc-fancy-area/preview';
|
||||
|
||||
@@ -21,6 +22,7 @@ export default function UserInfoCard(props: Props) {
|
||||
</div>
|
||||
<div className="flex items-center space-x-4">
|
||||
<ViewerCount />
|
||||
<StreamUptime />
|
||||
<FollowButton channel={props.streamInfo.username} />
|
||||
</div>
|
||||
</div>
|
||||
@@ -33,4 +35,4 @@ export default function UserInfoCard(props: Props) {
|
||||
|
||||
interface Props {
|
||||
streamInfo: StreamInfo & { channel: Channel };
|
||||
}
|
||||
}
|
||||
|
||||
55
apps/web/src/components/app/UserInfoCard/streamUptime.tsx
Normal file
55
apps/web/src/components/app/UserInfoCard/streamUptime.tsx
Normal file
@@ -0,0 +1,55 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { Clock3 } from 'lucide-react';
|
||||
import { useParams } from 'next/navigation';
|
||||
import { useStreams } from '@/lib/providers/StreamInfoProvider';
|
||||
|
||||
export default function StreamUptime() {
|
||||
const { stream, isLoading } = useStreams();
|
||||
const { username } = useParams<{ username: string }>();
|
||||
const [now, setNow] = useState(Date.now());
|
||||
|
||||
useEffect(() => {
|
||||
const timer = window.setInterval(() => {
|
||||
setNow(Date.now());
|
||||
}, 1000);
|
||||
|
||||
return () => {
|
||||
window.clearInterval(timer);
|
||||
};
|
||||
}, []);
|
||||
|
||||
const startedAt = useMemo(() => {
|
||||
if (!stream || !username) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const currentStream = stream.find((entry) => entry.username === username);
|
||||
if (!currentStream?.isLive) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return new Date(currentStream.startedAt).getTime();
|
||||
}, [stream, username]);
|
||||
|
||||
if (isLoading || !startedAt) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const elapsedSeconds = Math.max(0, Math.floor((now - startedAt) / 1000));
|
||||
const hours = Math.floor(elapsedSeconds / 3600)
|
||||
.toString()
|
||||
.padStart(2, '0');
|
||||
const minutes = Math.floor((elapsedSeconds % 3600) / 60)
|
||||
.toString()
|
||||
.padStart(2, '0');
|
||||
const seconds = (elapsedSeconds % 60).toString().padStart(2, '0');
|
||||
|
||||
return (
|
||||
<div className="flex items-center space-x-2 text-sm text-muted-foreground">
|
||||
<Clock3 className="h-4 w-4" />
|
||||
<span>{`${hours}:${minutes}:${seconds}`}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
262
apps/web/src/components/ui/carousel.tsx
Normal file
262
apps/web/src/components/ui/carousel.tsx
Normal file
@@ -0,0 +1,262 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import useEmblaCarousel, {
|
||||
type UseEmblaCarouselType,
|
||||
} from "embla-carousel-react"
|
||||
import { ArrowLeft, ArrowRight } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Button } from "@/components/ui/button"
|
||||
|
||||
type CarouselApi = UseEmblaCarouselType[1]
|
||||
type UseCarouselParameters = Parameters<typeof useEmblaCarousel>
|
||||
type CarouselOptions = UseCarouselParameters[0]
|
||||
type CarouselPlugin = UseCarouselParameters[1]
|
||||
|
||||
type CarouselProps = {
|
||||
opts?: CarouselOptions
|
||||
plugins?: CarouselPlugin
|
||||
orientation?: "horizontal" | "vertical"
|
||||
setApi?: (api: CarouselApi) => void
|
||||
}
|
||||
|
||||
type CarouselContextProps = {
|
||||
carouselRef: ReturnType<typeof useEmblaCarousel>[0]
|
||||
api: ReturnType<typeof useEmblaCarousel>[1]
|
||||
scrollPrev: () => void
|
||||
scrollNext: () => void
|
||||
canScrollPrev: boolean
|
||||
canScrollNext: boolean
|
||||
} & CarouselProps
|
||||
|
||||
const CarouselContext = React.createContext<CarouselContextProps | null>(null)
|
||||
|
||||
function useCarousel() {
|
||||
const context = React.useContext(CarouselContext)
|
||||
|
||||
if (!context) {
|
||||
throw new Error("useCarousel must be used within a <Carousel />")
|
||||
}
|
||||
|
||||
return context
|
||||
}
|
||||
|
||||
const Carousel = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement> & CarouselProps
|
||||
>(
|
||||
(
|
||||
{
|
||||
orientation = "horizontal",
|
||||
opts,
|
||||
setApi,
|
||||
plugins,
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
},
|
||||
ref
|
||||
) => {
|
||||
const [carouselRef, api] = useEmblaCarousel(
|
||||
{
|
||||
...opts,
|
||||
axis: orientation === "horizontal" ? "x" : "y",
|
||||
},
|
||||
plugins
|
||||
)
|
||||
const [canScrollPrev, setCanScrollPrev] = React.useState(false)
|
||||
const [canScrollNext, setCanScrollNext] = React.useState(false)
|
||||
|
||||
const onSelect = React.useCallback((api: CarouselApi) => {
|
||||
if (!api) {
|
||||
return
|
||||
}
|
||||
|
||||
setCanScrollPrev(api.canScrollPrev())
|
||||
setCanScrollNext(api.canScrollNext())
|
||||
}, [])
|
||||
|
||||
const scrollPrev = React.useCallback(() => {
|
||||
api?.scrollPrev()
|
||||
}, [api])
|
||||
|
||||
const scrollNext = React.useCallback(() => {
|
||||
api?.scrollNext()
|
||||
}, [api])
|
||||
|
||||
const handleKeyDown = React.useCallback(
|
||||
(event: React.KeyboardEvent<HTMLDivElement>) => {
|
||||
if (event.key === "ArrowLeft") {
|
||||
event.preventDefault()
|
||||
scrollPrev()
|
||||
} else if (event.key === "ArrowRight") {
|
||||
event.preventDefault()
|
||||
scrollNext()
|
||||
}
|
||||
},
|
||||
[scrollPrev, scrollNext]
|
||||
)
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!api || !setApi) {
|
||||
return
|
||||
}
|
||||
|
||||
setApi(api)
|
||||
}, [api, setApi])
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!api) {
|
||||
return
|
||||
}
|
||||
|
||||
onSelect(api)
|
||||
api.on("reInit", onSelect)
|
||||
api.on("select", onSelect)
|
||||
|
||||
return () => {
|
||||
api?.off("select", onSelect)
|
||||
}
|
||||
}, [api, onSelect])
|
||||
|
||||
return (
|
||||
<CarouselContext.Provider
|
||||
value={{
|
||||
carouselRef,
|
||||
api: api,
|
||||
opts,
|
||||
orientation:
|
||||
orientation || (opts?.axis === "y" ? "vertical" : "horizontal"),
|
||||
scrollPrev,
|
||||
scrollNext,
|
||||
canScrollPrev,
|
||||
canScrollNext,
|
||||
}}
|
||||
>
|
||||
<div
|
||||
ref={ref}
|
||||
onKeyDownCapture={handleKeyDown}
|
||||
className={cn("relative", className)}
|
||||
role="region"
|
||||
aria-roledescription="carousel"
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</CarouselContext.Provider>
|
||||
)
|
||||
}
|
||||
)
|
||||
Carousel.displayName = "Carousel"
|
||||
|
||||
const CarouselContent = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement>
|
||||
>(({ className, ...props }, ref) => {
|
||||
const { carouselRef, orientation } = useCarousel()
|
||||
|
||||
return (
|
||||
<div ref={carouselRef} className="overflow-hidden">
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex",
|
||||
orientation === "horizontal" ? "-ml-4" : "-mt-4 flex-col",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
CarouselContent.displayName = "CarouselContent"
|
||||
|
||||
const CarouselItem = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement>
|
||||
>(({ className, ...props }, ref) => {
|
||||
const { orientation } = useCarousel()
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
role="group"
|
||||
aria-roledescription="slide"
|
||||
className={cn(
|
||||
"min-w-0 shrink-0 grow-0 basis-full",
|
||||
orientation === "horizontal" ? "pl-4" : "pt-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
CarouselItem.displayName = "CarouselItem"
|
||||
|
||||
const CarouselPrevious = React.forwardRef<
|
||||
HTMLButtonElement,
|
||||
React.ComponentProps<typeof Button>
|
||||
>(({ className, variant = "outline", size = "icon", ...props }, ref) => {
|
||||
const { orientation, scrollPrev, canScrollPrev } = useCarousel()
|
||||
|
||||
return (
|
||||
<Button
|
||||
ref={ref}
|
||||
variant={variant}
|
||||
size={size}
|
||||
className={cn(
|
||||
"absolute h-8 w-8 rounded-full",
|
||||
orientation === "horizontal"
|
||||
? "-left-12 top-1/2 -translate-y-1/2"
|
||||
: "-top-12 left-1/2 -translate-x-1/2 rotate-90",
|
||||
className
|
||||
)}
|
||||
disabled={!canScrollPrev}
|
||||
onClick={scrollPrev}
|
||||
{...props}
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
<span className="sr-only">Previous slide</span>
|
||||
</Button>
|
||||
)
|
||||
})
|
||||
CarouselPrevious.displayName = "CarouselPrevious"
|
||||
|
||||
const CarouselNext = React.forwardRef<
|
||||
HTMLButtonElement,
|
||||
React.ComponentProps<typeof Button>
|
||||
>(({ className, variant = "outline", size = "icon", ...props }, ref) => {
|
||||
const { orientation, scrollNext, canScrollNext } = useCarousel()
|
||||
|
||||
return (
|
||||
<Button
|
||||
ref={ref}
|
||||
variant={variant}
|
||||
size={size}
|
||||
className={cn(
|
||||
"absolute h-8 w-8 rounded-full",
|
||||
orientation === "horizontal"
|
||||
? "-right-12 top-1/2 -translate-y-1/2"
|
||||
: "-bottom-12 left-1/2 -translate-x-1/2 rotate-90",
|
||||
className
|
||||
)}
|
||||
disabled={!canScrollNext}
|
||||
onClick={scrollNext}
|
||||
{...props}
|
||||
>
|
||||
<ArrowRight className="h-4 w-4" />
|
||||
<span className="sr-only">Next slide</span>
|
||||
</Button>
|
||||
)
|
||||
})
|
||||
CarouselNext.displayName = "CarouselNext"
|
||||
|
||||
export {
|
||||
type CarouselApi,
|
||||
Carousel,
|
||||
CarouselContent,
|
||||
CarouselItem,
|
||||
CarouselPrevious,
|
||||
CarouselNext,
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
editBotSchema,
|
||||
onboardSchema,
|
||||
streamInfoEditSchema,
|
||||
updateChatModerationSchema,
|
||||
updateChannelSettingsSchema,
|
||||
} from './zod';
|
||||
import { initializeStreamInfo } from '../instrumentation/streamInfo';
|
||||
@@ -261,6 +262,9 @@ export async function addChannelManager(channelId: string, userChannel: string)
|
||||
managers: {
|
||||
connect: { id: userDb.id },
|
||||
},
|
||||
chatModerators: {
|
||||
connect: { id: userDb.id },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -268,6 +272,224 @@ export async function addChannelManager(channelId: string, userChannel: string)
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
export async function addChatModerator(channelId: string, userChannel: string) {
|
||||
const { user } = await validateRequest();
|
||||
if (!user) {
|
||||
return { success: false, error: 'Unauthorized' };
|
||||
}
|
||||
|
||||
const channel = await prisma.channel.findUnique({
|
||||
where: { id: channelId },
|
||||
include: { owner: true, managers: true, chatModerators: true },
|
||||
});
|
||||
|
||||
if (!channel) {
|
||||
return { success: false, error: 'Channel not found' };
|
||||
}
|
||||
|
||||
if (!can(user, 'update', 'channel', { channel })) {
|
||||
return { success: false, error: 'Unauthorized' };
|
||||
}
|
||||
|
||||
const userDb = await resolveUserFromPersonalChannelName(userChannel);
|
||||
if (!userDb) {
|
||||
return { success: false, error: 'User not found' };
|
||||
}
|
||||
|
||||
if (
|
||||
channel.ownerId === userDb.id ||
|
||||
channel.managers.some((manager) => manager.id === userDb.id)
|
||||
) {
|
||||
return { success: false, error: 'This user is already a built-in moderator' };
|
||||
}
|
||||
|
||||
if (channel.chatModerators.some((moderator) => moderator.id === userDb.id)) {
|
||||
return { success: false, error: 'User is already a chat moderator' };
|
||||
}
|
||||
|
||||
await prisma.channel.update({
|
||||
where: { id: channelId },
|
||||
data: {
|
||||
chatModerators: {
|
||||
connect: { id: userDb.id },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
revalidatePath(`/settings/channel/${channel.name}`);
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
export async function removeChatModerator(channelId: string, userId: string) {
|
||||
const { user } = await validateRequest();
|
||||
if (!user) {
|
||||
return { success: false, error: 'Unauthorized' };
|
||||
}
|
||||
|
||||
const channel = await prisma.channel.findUnique({
|
||||
where: { id: channelId },
|
||||
include: { owner: true, managers: true },
|
||||
});
|
||||
|
||||
if (!channel) {
|
||||
return { success: false, error: 'Channel not found' };
|
||||
}
|
||||
|
||||
if (!can(user, 'update', 'channel', { channel })) {
|
||||
return { success: false, error: 'Unauthorized' };
|
||||
}
|
||||
|
||||
await prisma.channel.update({
|
||||
where: { id: channelId },
|
||||
data: {
|
||||
chatModerators: {
|
||||
disconnect: { id: userId },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
revalidatePath(`/settings/channel/${channel.name}`);
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
export async function addChatBotModerator(channelId: string, botId: string) {
|
||||
const { user } = await validateRequest();
|
||||
if (!user) {
|
||||
return { success: false, error: 'Unauthorized' };
|
||||
}
|
||||
|
||||
const channel = await prisma.channel.findUnique({
|
||||
where: { id: channelId },
|
||||
include: { owner: true, managers: true, chatModeratorBots: true },
|
||||
});
|
||||
|
||||
if (!channel) {
|
||||
return { success: false, error: 'Channel not found' };
|
||||
}
|
||||
|
||||
if (!can(user, 'update', 'channel', { channel })) {
|
||||
return { success: false, error: 'Unauthorized' };
|
||||
}
|
||||
|
||||
const bot = await prisma.botAccount.findUnique({
|
||||
where: { id: botId },
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
if (!bot) {
|
||||
return { success: false, error: 'Bot not found' };
|
||||
}
|
||||
|
||||
if (channel.chatModeratorBots.some((existingBot) => existingBot.id === bot.id)) {
|
||||
return { success: false, error: 'Bot is already a chat moderator' };
|
||||
}
|
||||
|
||||
await prisma.channel.update({
|
||||
where: { id: channelId },
|
||||
data: {
|
||||
chatModeratorBots: {
|
||||
connect: { id: bot.id },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
revalidatePath(`/settings/channel/${channel.name}`);
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
export async function removeChatBotModerator(channelId: string, botId: string) {
|
||||
const { user } = await validateRequest();
|
||||
if (!user) {
|
||||
return { success: false, error: 'Unauthorized' };
|
||||
}
|
||||
|
||||
const channel = await prisma.channel.findUnique({
|
||||
where: { id: channelId },
|
||||
include: { owner: true, managers: true },
|
||||
});
|
||||
|
||||
if (!channel) {
|
||||
return { success: false, error: 'Channel not found' };
|
||||
}
|
||||
|
||||
if (!can(user, 'update', 'channel', { channel })) {
|
||||
return { success: false, error: 'Unauthorized' };
|
||||
}
|
||||
|
||||
await prisma.channel.update({
|
||||
where: { id: channelId },
|
||||
data: {
|
||||
chatModeratorBots: {
|
||||
disconnect: { id: botId },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
revalidatePath(`/settings/channel/${channel.name}`);
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
export async function updateChatModeration(prev: any, formData: FormData) {
|
||||
const { user } = await validateRequest();
|
||||
if (!user) {
|
||||
return { success: false, error: 'Unauthorized' };
|
||||
}
|
||||
|
||||
const zod = await zodVerify(updateChatModerationSchema, formData);
|
||||
if (!zod.success) {
|
||||
return zod;
|
||||
}
|
||||
|
||||
const channel = await prisma.channel.findUnique({
|
||||
where: { id: zod.data.channelId },
|
||||
include: {
|
||||
owner: true,
|
||||
managers: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!channel) {
|
||||
return { success: false, error: 'Channel not found' };
|
||||
}
|
||||
|
||||
if (!can(user, 'update', 'channel', { channel })) {
|
||||
return { success: false, error: 'Unauthorized' };
|
||||
}
|
||||
|
||||
const blockedTerms = (zod.data.blockedTerms ?? '')
|
||||
.split(/[\n,]/)
|
||||
.map((term) => term.trim().toLowerCase())
|
||||
.filter((term) => term.length >= 2)
|
||||
.slice(0, 200);
|
||||
|
||||
await prisma.chatModerationSettings.upsert({
|
||||
where: {
|
||||
channelId: channel.id,
|
||||
},
|
||||
create: {
|
||||
channelId: channel.id,
|
||||
blockedTerms,
|
||||
slowModeSeconds: zod.data.slowModeSeconds,
|
||||
maxMessageLength: zod.data.maxMessageLength,
|
||||
rateLimitCount: zod.data.rateLimitCount,
|
||||
rateLimitWindowSeconds: zod.data.rateLimitWindowSeconds,
|
||||
},
|
||||
update: {
|
||||
blockedTerms,
|
||||
slowModeSeconds: zod.data.slowModeSeconds,
|
||||
maxMessageLength: zod.data.maxMessageLength,
|
||||
rateLimitCount: zod.data.rateLimitCount,
|
||||
rateLimitWindowSeconds: zod.data.rateLimitWindowSeconds,
|
||||
},
|
||||
});
|
||||
|
||||
const redis = getRedisConnection();
|
||||
await redis.del(`chat:moderation:settings:${channel.id}`);
|
||||
|
||||
revalidatePath(`/settings/channel/${channel.name}`);
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
export async function removeChannelManager(channelId: string, userId: string) {
|
||||
const { user } = await validateRequest();
|
||||
if (!user) {
|
||||
@@ -293,6 +515,9 @@ export async function removeChannelManager(channelId: string, userId: string) {
|
||||
managers: {
|
||||
disconnect: { id: userId },
|
||||
},
|
||||
chatModerators: {
|
||||
disconnect: { id: userId },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -1,13 +1,6 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
const disallowedUsernames = [
|
||||
'admin',
|
||||
'administrator',
|
||||
'settings',
|
||||
'create',
|
||||
// i hope this doesn't age well tbh
|
||||
'zrl',
|
||||
];
|
||||
const disallowedUsernames = ['admin', 'administrator', 'settings', 'create'];
|
||||
const username = z
|
||||
.string()
|
||||
.min(1)
|
||||
@@ -39,6 +32,15 @@ export const updateChannelSettingsSchema = z.object({
|
||||
is247: z.boolean(),
|
||||
});
|
||||
|
||||
export const updateChatModerationSchema = z.object({
|
||||
channelId: z.string().min(1),
|
||||
blockedTerms: z.string().max(5000).optional(),
|
||||
slowModeSeconds: z.coerce.number().int().min(0).max(120),
|
||||
maxMessageLength: z.coerce.number().int().min(50).max(2000),
|
||||
rateLimitCount: z.coerce.number().int().min(3).max(30),
|
||||
rateLimitWindowSeconds: z.coerce.number().int().min(5).max(60),
|
||||
});
|
||||
|
||||
export const createBotSchema = z.object({
|
||||
name: z.string().min(1, { message: 'Name is required' }),
|
||||
slug: username.refine((val) => val !== 'settings', { message: 'This slug is reserved' }),
|
||||
|
||||
@@ -1,23 +1,30 @@
|
||||
import { prisma } from "@hctv/db";
|
||||
import { getThumbnailQueue } from "../workers";
|
||||
import { prisma } from '@hctv/db';
|
||||
import { recordThumbnailJobsEnqueued, setThumbnailRefreshTargets, trackWebJob } from '../metrics';
|
||||
import { getThumbnailQueue } from '../workers';
|
||||
|
||||
export default async function getLiveThumb() {
|
||||
const liveChannels = await prisma.streamInfo.findMany({
|
||||
where: {
|
||||
isLive: true,
|
||||
},
|
||||
include: {
|
||||
channel: true,
|
||||
}
|
||||
});
|
||||
const liveChannelNames = liveChannels.map((channel) => channel.channel.name);
|
||||
|
||||
const thumbQueue = getThumbnailQueue();
|
||||
for (const channel of liveChannelNames) {
|
||||
const lc = liveChannels.find(c => c.channel.name === channel)!;
|
||||
await thumbQueue.add("getLiveThumb", {
|
||||
name: channel,
|
||||
server: lc.streamRegion,
|
||||
return trackWebJob('thumbnail_refresh', async () => {
|
||||
const liveChannels = await prisma.streamInfo.findMany({
|
||||
where: {
|
||||
isLive: true,
|
||||
},
|
||||
include: {
|
||||
channel: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
const thumbQueue = getThumbnailQueue();
|
||||
const jobsByRegion: Record<string, number> = {};
|
||||
|
||||
setThumbnailRefreshTargets(liveChannels.length);
|
||||
|
||||
for (const liveChannel of liveChannels) {
|
||||
await thumbQueue.add('getLiveThumb', {
|
||||
name: liveChannel.channel.name,
|
||||
server: liveChannel.streamRegion,
|
||||
});
|
||||
jobsByRegion[liveChannel.streamRegion] = (jobsByRegion[liveChannel.streamRegion] ?? 0) + 1;
|
||||
}
|
||||
|
||||
recordThumbnailJobsEnqueued(jobsByRegion);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,4 +1,13 @@
|
||||
import { prisma } from '@hctv/db';
|
||||
import {
|
||||
recordLiveStreamTransition,
|
||||
recordNotificationsEnqueued,
|
||||
recordStreamSyncScrape,
|
||||
setLiveStreamsByRegion,
|
||||
setPlatformInventory,
|
||||
setStreamPathsByRegion,
|
||||
trackWebJob,
|
||||
} from '../metrics';
|
||||
import { HttpFlv } from '../types/liveBackendJson';
|
||||
import { getNotificationQueue } from '../workers';
|
||||
import client from '../services/slackNotifier';
|
||||
@@ -10,9 +19,29 @@ export default async function runner() {
|
||||
if ((await prisma.user.count()) === 0) {
|
||||
return;
|
||||
}
|
||||
await refreshPlatformInventory();
|
||||
await initializeStreamInfo();
|
||||
await syncStream();
|
||||
setInterval(syncStream, 5000);
|
||||
setInterval(refreshPlatformInventory, 60_000);
|
||||
}
|
||||
|
||||
async function refreshPlatformInventory() {
|
||||
const [channels, liveStreams, follows, botAccounts, users] = await Promise.all([
|
||||
prisma.channel.count(),
|
||||
prisma.streamInfo.count({ where: { isLive: true } }),
|
||||
prisma.follow.count(),
|
||||
prisma.botAccount.count(),
|
||||
prisma.user.count(),
|
||||
]);
|
||||
|
||||
setPlatformInventory({
|
||||
bot_accounts: botAccounts,
|
||||
channels,
|
||||
follows,
|
||||
live_stream_rows: liveStreams,
|
||||
users,
|
||||
});
|
||||
}
|
||||
|
||||
export async function initializeStreamInfo(channelId?: string) {
|
||||
@@ -50,103 +79,122 @@ export async function initializeStreamInfo(channelId?: string) {
|
||||
|
||||
export async function syncStream() {
|
||||
try {
|
||||
const regions = Object.keys(MEDIAMTX_SERVER_REGIONS) as Array<
|
||||
keyof typeof MEDIAMTX_SERVER_REGIONS
|
||||
>;
|
||||
await trackWebJob('stream_sync', async () => {
|
||||
const regions = Object.keys(MEDIAMTX_SERVER_REGIONS) as Array<
|
||||
keyof typeof MEDIAMTX_SERVER_REGIONS
|
||||
>;
|
||||
|
||||
const allActiveStreams = new Map<string, keyof typeof MEDIAMTX_SERVER_REGIONS>();
|
||||
const allActiveStreams = new Map<string, keyof typeof MEDIAMTX_SERVER_REGIONS>();
|
||||
const liveStreamsByRegion = Object.fromEntries(regions.map((region) => [region, 0]));
|
||||
const pathsSeenByRegion = Object.fromEntries(regions.map((region) => [region, 0]));
|
||||
|
||||
for (const r of regions) {
|
||||
const region = MEDIAMTX_SERVER_REGIONS[r];
|
||||
const response = await fetch(`${region.apiUrl}/v3/paths/list?itemsPerPage=1000`);
|
||||
for (const r of regions) {
|
||||
const region = MEDIAMTX_SERVER_REGIONS[r];
|
||||
const response = await fetch(`${region.apiUrl}/v3/paths/list?itemsPerPage=1000`);
|
||||
|
||||
if (!response.ok) {
|
||||
console.error(
|
||||
`Failed to fetch ${r} stream stats: ${response.status} ${response.statusText}`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if (!response.ok) {
|
||||
recordStreamSyncScrape(r, 'error');
|
||||
console.error(
|
||||
`Failed to fetch ${r} stream stats: ${response.status} ${response.statusText}`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
type ResponseType =
|
||||
paths['/v3/paths/list']['get']['responses']['200']['content']['application/json'];
|
||||
const data = (await response.json()) as ResponseType;
|
||||
recordStreamSyncScrape(r, 'success');
|
||||
|
||||
if (data?.items) {
|
||||
for (const stream of data.items) {
|
||||
if (stream.ready && stream.name) {
|
||||
allActiveStreams.set(stream.name, r);
|
||||
type ResponseType =
|
||||
paths['/v3/paths/list']['get']['responses']['200']['content']['application/json'];
|
||||
const data = (await response.json()) as ResponseType;
|
||||
|
||||
if (data?.items) {
|
||||
for (const stream of data.items) {
|
||||
if (stream.ready && stream.name) {
|
||||
allActiveStreams.set(stream.name, r);
|
||||
liveStreamsByRegion[r] += 1;
|
||||
pathsSeenByRegion[r] += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// handle streams going offline
|
||||
const currentLiveStreams = await prisma.streamInfo.findMany({
|
||||
where: { isLive: true },
|
||||
});
|
||||
setLiveStreamsByRegion(liveStreamsByRegion);
|
||||
setStreamPathsByRegion(pathsSeenByRegion);
|
||||
|
||||
for (const dbStream of currentLiveStreams) {
|
||||
if (!allActiveStreams.has(dbStream.username)) {
|
||||
await prisma.streamInfo.update({
|
||||
where: { username: dbStream.username },
|
||||
data: {
|
||||
isLive: false,
|
||||
viewers: 0,
|
||||
startedAt: new Date(0),
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// handle streams going online
|
||||
for (const [username, regionKey] of allActiveStreams) {
|
||||
const existingStream = await prisma.streamInfo.findUnique({
|
||||
where: { username },
|
||||
include: { channel: true },
|
||||
const currentLiveStreams = await prisma.streamInfo.findMany({
|
||||
where: { isLive: true },
|
||||
});
|
||||
|
||||
if (existingStream && !existingStream.isLive) {
|
||||
console.log(`Stream ${username} is now live in region ${regionKey}`);
|
||||
await prisma.streamInfo.update({
|
||||
where: { username },
|
||||
data: {
|
||||
isLive: true,
|
||||
startedAt: new Date(),
|
||||
streamRegion: regionKey,
|
||||
},
|
||||
});
|
||||
|
||||
const subscribedFollowers = await prisma.follow.findMany({
|
||||
where: {
|
||||
channelId: existingStream.channelId,
|
||||
notifyStream: true,
|
||||
},
|
||||
include: {
|
||||
user: true,
|
||||
},
|
||||
});
|
||||
|
||||
const queue = getNotificationQueue();
|
||||
|
||||
if (!existingStream.channel.is247) {
|
||||
queue.add(`streamStartChannel:${existingStream.username}`, {
|
||||
text: `${existingStream.username} is now *live*, streaming *${existingStream.title}* (${existingStream.category})!\n<https://hackclub.tv/${existingStream.username}|Go check them out>`,
|
||||
channel: process.env.NOTIFICATION_CHANNEL_ID!,
|
||||
unfurl_links: true,
|
||||
for (const dbStream of currentLiveStreams) {
|
||||
if (!allActiveStreams.has(dbStream.username)) {
|
||||
recordLiveStreamTransition('offline', dbStream.streamRegion);
|
||||
await prisma.streamInfo.update({
|
||||
where: { username: dbStream.username },
|
||||
data: {
|
||||
isLive: false,
|
||||
viewers: 0,
|
||||
startedAt: new Date(0),
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (existingStream.enableNotifications && !existingStream.channel.is247) {
|
||||
for (const follower of subscribedFollowers) {
|
||||
queue.add(`streamStartDm:${follower.user.id}`, {
|
||||
text: `${existingStream.username} is now *live*, streaming *${existingStream.title}* (${existingStream.category})!\n<https://hackclub.tv/${existingStream.username}|Go check them out>\n_Stream notifications are enabled for this user. If you want to disable them, you can do so in \`Profile > Follows\`._`,
|
||||
channel: follower.user.slack_id,
|
||||
for (const [username, regionKey] of allActiveStreams) {
|
||||
const existingStream = await prisma.streamInfo.findUnique({
|
||||
where: { username },
|
||||
include: { channel: true },
|
||||
});
|
||||
|
||||
if (existingStream && !existingStream.isLive) {
|
||||
console.log(`Stream ${username} is now live in region ${regionKey}`);
|
||||
recordLiveStreamTransition('online', regionKey);
|
||||
await prisma.streamInfo.update({
|
||||
where: { username },
|
||||
data: {
|
||||
isLive: true,
|
||||
startedAt: new Date(),
|
||||
streamRegion: regionKey,
|
||||
},
|
||||
});
|
||||
|
||||
const subscribedFollowers = await prisma.follow.findMany({
|
||||
where: {
|
||||
channelId: existingStream.channelId,
|
||||
notifyStream: true,
|
||||
},
|
||||
include: {
|
||||
user: true,
|
||||
},
|
||||
});
|
||||
|
||||
const queue = getNotificationQueue();
|
||||
if (!existingStream.channel.is247) {
|
||||
queue.add(`streamStartChannel:${existingStream.username}`, {
|
||||
text: `${existingStream.username} is now *live*, streaming *${existingStream.title}* (${existingStream.category})!\n<https://hackclub.tv/${existingStream.username}|Go check them out>`,
|
||||
channel: process.env.NOTIFICATION_CHANNEL_ID!,
|
||||
unfurl_links: true,
|
||||
});
|
||||
}
|
||||
|
||||
if (existingStream.enableNotifications && !existingStream.channel.is247) {
|
||||
for (const follower of subscribedFollowers) {
|
||||
queue.add(`streamStartDm:${follower.user.id}`, {
|
||||
text: `${existingStream.username} is now *live*, streaming *${existingStream.title}* (${existingStream.category})!\n<https://hackclub.tv/${existingStream.username}|Go check them out>\n_Stream notifications are enabled for this user. If you want to disable them, you can do so in \`Profile > Follows\`._`,
|
||||
channel: follower.user.slack_id,
|
||||
unfurl_links: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
recordNotificationsEnqueued('channel', existingStream.channel.is247 ? 0 : 1);
|
||||
recordNotificationsEnqueued(
|
||||
'dm',
|
||||
existingStream.enableNotifications && !existingStream.channel.is247
|
||||
? subscribedFollowers.length
|
||||
: 0
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error syncing stream status:', error);
|
||||
}
|
||||
|
||||
@@ -1,30 +1,37 @@
|
||||
import { prisma, getRedisConnection } from '@hctv/db';
|
||||
import { setCacheEntryCount, trackWebJob } from '../metrics';
|
||||
|
||||
export default async function syncStreamKeys() {
|
||||
console.log('Syncing stream keys to Redis...');
|
||||
try {
|
||||
const keys = await prisma.streamKey.findMany({
|
||||
include: {
|
||||
channel: true,
|
||||
},
|
||||
});
|
||||
await trackWebJob('sync_stream_keys', async () => {
|
||||
const keys = await prisma.streamKey.findMany({
|
||||
include: {
|
||||
channel: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (keys.length === 0) {
|
||||
console.log('No stream keys found to sync.');
|
||||
return;
|
||||
}
|
||||
|
||||
const redis = getRedisConnection();
|
||||
const pipeline = redis.pipeline();
|
||||
|
||||
for (const key of keys) {
|
||||
if (key.channel && key.channel.name) {
|
||||
pipeline.set(`streamKey:${key.channel.name}`, key.key);
|
||||
if (keys.length === 0) {
|
||||
setCacheEntryCount('stream_keys', 0);
|
||||
console.log('No stream keys found to sync.');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
await pipeline.exec();
|
||||
console.log(`Synced ${keys.length} stream keys to Redis`);
|
||||
const redis = getRedisConnection();
|
||||
const pipeline = redis.pipeline();
|
||||
|
||||
let syncedKeyCount = 0;
|
||||
for (const key of keys) {
|
||||
if (key.channel && key.channel.name) {
|
||||
pipeline.set(`streamKey:${key.channel.name}`, key.key);
|
||||
syncedKeyCount += 1;
|
||||
}
|
||||
}
|
||||
|
||||
await pipeline.exec();
|
||||
setCacheEntryCount('stream_keys', syncedKeyCount);
|
||||
console.log(`Synced ${syncedKeyCount} stream keys to Redis`);
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Failed to sync stream keys to Redis:', error);
|
||||
}
|
||||
|
||||
@@ -1,40 +1,101 @@
|
||||
import { getRedisConnection, prisma } from "@hctv/db";
|
||||
import { getRedisConnection, prisma } from '@hctv/db';
|
||||
import { setViewerSnapshot, trackWebJob } from '../metrics';
|
||||
|
||||
async function countViewersForChannel(channelName: string): Promise<number> {
|
||||
const redis = getRedisConnection();
|
||||
let cursor = '0';
|
||||
let total = 0;
|
||||
|
||||
do {
|
||||
const [nextCursor, keys] = await redis.scan(
|
||||
cursor,
|
||||
'MATCH',
|
||||
`viewer:${channelName}:*`,
|
||||
'COUNT',
|
||||
200
|
||||
);
|
||||
cursor = nextCursor;
|
||||
total += keys.length;
|
||||
} while (cursor !== '0');
|
||||
|
||||
return total;
|
||||
}
|
||||
|
||||
export async function viewerCountSync() {
|
||||
const streams = await prisma.streamInfo.findMany({
|
||||
where: {
|
||||
isLive: true
|
||||
},
|
||||
include: {
|
||||
channel: true
|
||||
}
|
||||
})
|
||||
|
||||
if (streams.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const redis = getRedisConnection();
|
||||
const multi = redis.multi();
|
||||
for (const stream of streams) {
|
||||
multi.keys(`viewer:${stream.channel.name}:*`);
|
||||
}
|
||||
const results = await multi.exec();
|
||||
|
||||
await prisma.$transaction(async (tx) => {
|
||||
const updates = results?.map((res, index) => {
|
||||
const count = Array.isArray(res[1]) ? res[1].length : 0;
|
||||
const stream = streams[index];
|
||||
return tx.streamInfo.update({
|
||||
try {
|
||||
await trackWebJob('viewer_count_sync', async () => {
|
||||
const streams = await prisma.streamInfo.findMany({
|
||||
where: {
|
||||
// using username here because it uses a map
|
||||
username: stream.username
|
||||
isLive: true,
|
||||
},
|
||||
data: {
|
||||
viewers: count
|
||||
select: {
|
||||
username: true,
|
||||
streamRegion: true,
|
||||
channel: {
|
||||
select: {
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (streams.length === 0) {
|
||||
setViewerSnapshot({
|
||||
totalViewers: 0,
|
||||
trackedStreams: 0,
|
||||
streamsWithViewers: 0,
|
||||
hottestStreamViewers: 0,
|
||||
viewersByRegion: {},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const viewersByRegion: Record<string, number> = {};
|
||||
let totalViewers = 0;
|
||||
let streamsWithViewers = 0;
|
||||
let hottestStreamViewers = 0;
|
||||
|
||||
const streamCounts = await Promise.all(
|
||||
streams.map(async (stream) => ({
|
||||
stream,
|
||||
count: await countViewersForChannel(stream.channel.name),
|
||||
}))
|
||||
);
|
||||
|
||||
for (const { stream, count } of streamCounts) {
|
||||
totalViewers += count;
|
||||
|
||||
if (stream.streamRegion) {
|
||||
viewersByRegion[stream.streamRegion] =
|
||||
(viewersByRegion[stream.streamRegion] ?? 0) + count;
|
||||
}
|
||||
})
|
||||
})
|
||||
await Promise.all(updates || []);
|
||||
})
|
||||
}
|
||||
|
||||
if (count > 0) {
|
||||
streamsWithViewers += 1;
|
||||
}
|
||||
if (count > hottestStreamViewers) {
|
||||
hottestStreamViewers = count;
|
||||
}
|
||||
|
||||
await prisma.streamInfo.update({
|
||||
where: {
|
||||
username: stream.username,
|
||||
},
|
||||
data: {
|
||||
viewers: count,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
setViewerSnapshot({
|
||||
totalViewers,
|
||||
trackedStreams: streams.length,
|
||||
streamsWithViewers,
|
||||
hottestStreamViewers,
|
||||
viewersByRegion,
|
||||
});
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error syncing viewer counts:', error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,17 +1,35 @@
|
||||
import { prisma } from "@hctv/db";
|
||||
import { getRedisConnection } from "@hctv/db";
|
||||
import { getRedisConnection, prisma } from '@hctv/db';
|
||||
import { setCacheEntryCount, trackWebJob } from '../metrics';
|
||||
|
||||
async function deleteSessionKeys() {
|
||||
const redis = getRedisConnection();
|
||||
let cursor = '0';
|
||||
|
||||
do {
|
||||
const [nextCursor, keys] = await redis.scan(cursor, 'MATCH', 'sessions:*', 'COUNT', 200);
|
||||
cursor = nextCursor;
|
||||
|
||||
if (keys.length > 0) {
|
||||
await redis.unlink(...keys);
|
||||
}
|
||||
} while (cursor !== '0');
|
||||
}
|
||||
|
||||
export default async function writeSessions() {
|
||||
const sessions = await prisma.session.findMany();
|
||||
const sessionIds = sessions.map((session) => session.id);
|
||||
|
||||
const redis = getRedisConnection();
|
||||
const multi = redis.multi();
|
||||
multi.del('sessions:*')
|
||||
for (const sessionId of sessionIds) {
|
||||
multi.set(`sessions:${sessionId}`, '');
|
||||
}
|
||||
await multi.exec();
|
||||
return trackWebJob('write_sessions', async () => {
|
||||
const sessions = await prisma.session.findMany();
|
||||
const sessionIds = sessions.map((session) => session.id);
|
||||
|
||||
console.log("Sessions written to Redis");
|
||||
}
|
||||
await deleteSessionKeys();
|
||||
|
||||
const redis = getRedisConnection();
|
||||
const multi = redis.multi();
|
||||
for (const sessionId of sessionIds) {
|
||||
multi.set(`sessions:${sessionId}`, '');
|
||||
}
|
||||
await multi.exec();
|
||||
setCacheEntryCount('sessions', sessionIds.length);
|
||||
|
||||
console.log('Sessions written to Redis');
|
||||
});
|
||||
}
|
||||
|
||||
261
apps/web/src/lib/metrics.ts
Normal file
261
apps/web/src/lib/metrics.ts
Normal file
@@ -0,0 +1,261 @@
|
||||
import { collectDefaultMetrics, Counter, Gauge, Histogram, Registry } from 'prom-client';
|
||||
|
||||
function createMetricsStore() {
|
||||
const register = new Registry();
|
||||
register.setDefaultLabels({ app: 'web' });
|
||||
|
||||
collectDefaultMetrics({
|
||||
prefix: 'hctv_web_',
|
||||
register,
|
||||
});
|
||||
|
||||
const backgroundJobRuns = new Counter({
|
||||
name: 'hctv_web_background_job_runs_total',
|
||||
help: 'Total number of background jobs run by the web app.',
|
||||
labelNames: ['job', 'status'],
|
||||
registers: [register],
|
||||
});
|
||||
|
||||
const backgroundJobDuration = new Histogram({
|
||||
name: 'hctv_web_background_job_duration_seconds',
|
||||
help: 'Background job execution time in seconds.',
|
||||
labelNames: ['job', 'status'],
|
||||
buckets: [0.01, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30],
|
||||
registers: [register],
|
||||
});
|
||||
|
||||
const liveStreams = new Gauge({
|
||||
name: 'hctv_web_live_streams',
|
||||
help: 'Current number of live streams grouped by MediaMTX region.',
|
||||
labelNames: ['region'],
|
||||
registers: [register],
|
||||
});
|
||||
|
||||
const streamPathsSeen = new Gauge({
|
||||
name: 'hctv_web_stream_paths_seen',
|
||||
help: 'Current number of ready MediaMTX paths seen during the latest sync.',
|
||||
labelNames: ['region'],
|
||||
registers: [register],
|
||||
});
|
||||
|
||||
const liveStreamTransitions = new Counter({
|
||||
name: 'hctv_web_live_stream_transitions_total',
|
||||
help: 'Live stream state transitions observed by the web app.',
|
||||
labelNames: ['transition', 'region'],
|
||||
registers: [register],
|
||||
});
|
||||
|
||||
const streamSyncScrapes = new Counter({
|
||||
name: 'hctv_web_stream_sync_scrapes_total',
|
||||
help: 'MediaMTX region scrapes attempted by stream sync.',
|
||||
labelNames: ['region', 'status'],
|
||||
registers: [register],
|
||||
});
|
||||
|
||||
const activeViewers = new Gauge({
|
||||
name: 'hctv_web_active_viewers',
|
||||
help: 'Current number of active viewers across all live streams.',
|
||||
registers: [register],
|
||||
});
|
||||
|
||||
const activeViewersByRegion = new Gauge({
|
||||
name: 'hctv_web_active_viewers_by_region',
|
||||
help: 'Current number of active viewers grouped by stream region.',
|
||||
labelNames: ['region'],
|
||||
registers: [register],
|
||||
});
|
||||
|
||||
const viewerCountTrackedStreams = new Gauge({
|
||||
name: 'hctv_web_viewer_count_tracked_streams',
|
||||
help: 'Number of live streams included in the latest viewer sync.',
|
||||
registers: [register],
|
||||
});
|
||||
|
||||
const streamsWithViewers = new Gauge({
|
||||
name: 'hctv_web_streams_with_viewers',
|
||||
help: 'Current number of live streams with at least one viewer.',
|
||||
registers: [register],
|
||||
});
|
||||
|
||||
const hottestStreamViewers = new Gauge({
|
||||
name: 'hctv_web_hottest_stream_viewers',
|
||||
help: 'Current viewer count of the most watched live stream.',
|
||||
registers: [register],
|
||||
});
|
||||
|
||||
const thumbnailJobsEnqueued = new Counter({
|
||||
name: 'hctv_web_thumbnail_jobs_enqueued_total',
|
||||
help: 'Total thumbnail refresh jobs enqueued by region.',
|
||||
labelNames: ['region'],
|
||||
registers: [register],
|
||||
});
|
||||
|
||||
const thumbnailRefreshTargets = new Gauge({
|
||||
name: 'hctv_web_thumbnail_refresh_targets',
|
||||
help: 'Number of live streams targeted in the latest thumbnail refresh run.',
|
||||
registers: [register],
|
||||
});
|
||||
|
||||
const notificationsEnqueued = new Counter({
|
||||
name: 'hctv_web_notifications_enqueued_total',
|
||||
help: 'Notification jobs enqueued when streams go live.',
|
||||
labelNames: ['target'],
|
||||
registers: [register],
|
||||
});
|
||||
|
||||
const cacheEntries = new Gauge({
|
||||
name: 'hctv_web_cache_entries',
|
||||
help: 'Current number of records mirrored into Redis by cache-sync jobs.',
|
||||
labelNames: ['cache'],
|
||||
registers: [register],
|
||||
});
|
||||
|
||||
const platformInventory = new Gauge({
|
||||
name: 'hctv_web_platform_inventory',
|
||||
help: 'High-level counts of important platform records.',
|
||||
labelNames: ['entity'],
|
||||
registers: [register],
|
||||
});
|
||||
|
||||
const mediamtxAuthRequests = new Counter({
|
||||
name: 'hctv_web_mediamtx_auth_requests_total',
|
||||
help: 'Total MediaMTX auth decisions handled by the web app.',
|
||||
labelNames: ['action', 'protocol', 'outcome'],
|
||||
registers: [register],
|
||||
});
|
||||
|
||||
const mediamtxAuthDuration = new Histogram({
|
||||
name: 'hctv_web_mediamtx_auth_duration_seconds',
|
||||
help: 'MediaMTX auth request duration in seconds.',
|
||||
labelNames: ['action', 'protocol', 'outcome'],
|
||||
buckets: [0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5],
|
||||
registers: [register],
|
||||
});
|
||||
|
||||
return {
|
||||
register,
|
||||
activeViewers,
|
||||
activeViewersByRegion,
|
||||
backgroundJobDuration,
|
||||
backgroundJobRuns,
|
||||
cacheEntries,
|
||||
hottestStreamViewers,
|
||||
liveStreams,
|
||||
liveStreamTransitions,
|
||||
mediamtxAuthDuration,
|
||||
mediamtxAuthRequests,
|
||||
notificationsEnqueued,
|
||||
platformInventory,
|
||||
streamPathsSeen,
|
||||
streamsWithViewers,
|
||||
streamSyncScrapes,
|
||||
thumbnailRefreshTargets,
|
||||
thumbnailJobsEnqueued,
|
||||
viewerCountTrackedStreams,
|
||||
};
|
||||
}
|
||||
|
||||
const globalForMetrics = globalThis as typeof globalThis & {
|
||||
__hctvWebMetrics?: ReturnType<typeof createMetricsStore>;
|
||||
};
|
||||
|
||||
const metrics = (globalForMetrics.__hctvWebMetrics ??= createMetricsStore());
|
||||
|
||||
export const webMetricsRegistry = metrics.register;
|
||||
|
||||
export async function trackWebJob<T>(job: string, fn: () => Promise<T>): Promise<T> {
|
||||
const stopTimer = metrics.backgroundJobDuration.startTimer({ job });
|
||||
let status = 'success';
|
||||
|
||||
try {
|
||||
return await fn();
|
||||
} catch (error) {
|
||||
status = 'error';
|
||||
throw error;
|
||||
} finally {
|
||||
metrics.backgroundJobRuns.inc({ job, status });
|
||||
stopTimer({ job, status });
|
||||
}
|
||||
}
|
||||
|
||||
export function setLiveStreamsByRegion(streamsByRegion: Record<string, number>): void {
|
||||
metrics.liveStreams.reset();
|
||||
|
||||
for (const [region, count] of Object.entries(streamsByRegion)) {
|
||||
metrics.liveStreams.set({ region }, count);
|
||||
}
|
||||
}
|
||||
|
||||
export function setStreamPathsByRegion(pathsByRegion: Record<string, number>): void {
|
||||
metrics.streamPathsSeen.reset();
|
||||
|
||||
for (const [region, count] of Object.entries(pathsByRegion)) {
|
||||
metrics.streamPathsSeen.set({ region }, count);
|
||||
}
|
||||
}
|
||||
|
||||
export function recordLiveStreamTransition(transition: 'online' | 'offline', region: string): void {
|
||||
metrics.liveStreamTransitions.inc({ transition, region });
|
||||
}
|
||||
|
||||
export function recordStreamSyncScrape(region: string, status: 'success' | 'error'): void {
|
||||
metrics.streamSyncScrapes.inc({ region, status });
|
||||
}
|
||||
|
||||
export function setViewerSnapshot(snapshot: {
|
||||
totalViewers: number;
|
||||
trackedStreams: number;
|
||||
viewersByRegion: Record<string, number>;
|
||||
streamsWithViewers: number;
|
||||
hottestStreamViewers: number;
|
||||
}): void {
|
||||
metrics.activeViewers.set(snapshot.totalViewers);
|
||||
metrics.viewerCountTrackedStreams.set(snapshot.trackedStreams);
|
||||
metrics.streamsWithViewers.set(snapshot.streamsWithViewers);
|
||||
metrics.hottestStreamViewers.set(snapshot.hottestStreamViewers);
|
||||
metrics.activeViewersByRegion.reset();
|
||||
|
||||
for (const [region, count] of Object.entries(snapshot.viewersByRegion)) {
|
||||
metrics.activeViewersByRegion.set({ region }, count);
|
||||
}
|
||||
}
|
||||
|
||||
export function recordThumbnailJobsEnqueued(jobsByRegion: Record<string, number>): void {
|
||||
for (const [region, count] of Object.entries(jobsByRegion)) {
|
||||
if (count > 0) {
|
||||
metrics.thumbnailJobsEnqueued.inc({ region }, count);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function setThumbnailRefreshTargets(count: number): void {
|
||||
metrics.thumbnailRefreshTargets.set(count);
|
||||
}
|
||||
|
||||
export function recordNotificationsEnqueued(target: 'channel' | 'dm', count: number): void {
|
||||
if (count > 0) {
|
||||
metrics.notificationsEnqueued.inc({ target }, count);
|
||||
}
|
||||
}
|
||||
|
||||
export function setCacheEntryCount(cache: 'sessions' | 'stream_keys', count: number): void {
|
||||
metrics.cacheEntries.set({ cache }, count);
|
||||
}
|
||||
|
||||
export function setPlatformInventory(snapshot: Record<string, number>): void {
|
||||
metrics.platformInventory.reset();
|
||||
|
||||
for (const [entity, count] of Object.entries(snapshot)) {
|
||||
metrics.platformInventory.set({ entity }, count);
|
||||
}
|
||||
}
|
||||
|
||||
export function recordMediamtxAuth(
|
||||
action: string,
|
||||
protocol: string,
|
||||
outcome: string,
|
||||
durationSeconds: number
|
||||
): void {
|
||||
metrics.mediamtxAuthRequests.inc({ action, protocol, outcome });
|
||||
metrics.mediamtxAuthDuration.observe({ action, protocol, outcome }, durationSeconds);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { utapi } from "../services/uploadthing/server";
|
||||
import sharp from "sharp";
|
||||
import sharp from 'sharp';
|
||||
import { utapi } from '../services/uploadthing/server';
|
||||
|
||||
export async function genIdenticonUpload(str: string, type?: string) {
|
||||
const identicon = await fetch(`https://api.dicebear.com/9.x/identicon/svg?seed=${str}&size=256`);
|
||||
@@ -7,13 +7,13 @@ export async function genIdenticonUpload(str: string, type?: string) {
|
||||
.webp({ quality: 80 })
|
||||
.toBuffer();
|
||||
|
||||
const file = new File([webpBuffer], `${str}${type ? `-${type}` : ""}.webp`, {
|
||||
type: "image/webp",
|
||||
const file = new File([new Uint8Array(webpBuffer)], `${str}${type ? `-${type}` : ''}.webp`, {
|
||||
type: 'image/webp',
|
||||
});
|
||||
const ul = await utapi.uploadFiles(file);
|
||||
if (ul.error) {
|
||||
throw new Error("Failed to upload identicon: " + ul.error);
|
||||
throw new Error('Failed to upload identicon: ' + ul.error);
|
||||
}
|
||||
|
||||
return ul.data?.ufsUrl
|
||||
}
|
||||
return ul.data?.ufsUrl;
|
||||
}
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import { registerNotificationWorker } from './worker/notification';
|
||||
import { registerThumbnailWorker } from './worker/thumbnails';
|
||||
import { trackWebJob } from '../metrics';
|
||||
|
||||
export async function registerWorkers(): Promise<void> {
|
||||
await registerNotificationWorker();
|
||||
await registerThumbnailWorker();
|
||||
console.log('All workers registered successfully');
|
||||
}
|
||||
await trackWebJob('register_workers', async () => {
|
||||
await registerNotificationWorker();
|
||||
await registerThumbnailWorker();
|
||||
console.log('All workers registered successfully');
|
||||
});
|
||||
}
|
||||
|
||||
62
compose.yml
62
compose.yml
@@ -8,8 +8,9 @@ services:
|
||||
condition: service_started
|
||||
env_file:
|
||||
- .env
|
||||
restart: unless-stopped
|
||||
image: srizan10/hclive
|
||||
build:
|
||||
context: .
|
||||
dockerfile: apps/web/Dockerfile
|
||||
chat:
|
||||
depends_on:
|
||||
postgres:
|
||||
@@ -18,14 +19,17 @@ services:
|
||||
condition: service_started
|
||||
env_file:
|
||||
- .env
|
||||
restart: unless-stopped
|
||||
image: srizan10/hclive-chat
|
||||
build:
|
||||
context: .
|
||||
dockerfile: apps/chat/Dockerfile
|
||||
postgres:
|
||||
image: 'postgres:17-alpine'
|
||||
ports:
|
||||
- '6767:5432'
|
||||
environment:
|
||||
POSTGRES_USER: postgres
|
||||
POSTGRES_PASSWORD: '${PG_PASS}'
|
||||
restart: unless-stopped
|
||||
POSTGRES_DB: hctv
|
||||
volumes:
|
||||
- 'hctv_pgdata:/var/lib/postgresql/data'
|
||||
healthcheck:
|
||||
@@ -42,19 +46,61 @@ services:
|
||||
- POSTGRESQL_PORT=5432
|
||||
- POSTGRESQL_USERNAME=postgres
|
||||
- 'POSTGRESQL_PASSWORD=${PG_PASS}'
|
||||
- PGBOUNCER_DATABASE=hctv
|
||||
- POSTGRESQL_DATABASE=hctv
|
||||
- PGBOUNCER_POOL_MODE=transaction
|
||||
- PGBOUNCER_MAX_CLIENT_CONN=100
|
||||
- PGBOUNCER_DEFAULT_POOL_SIZE=20
|
||||
depends_on:
|
||||
- postgres
|
||||
restart: unless-stopped
|
||||
redis:
|
||||
image: 'redis:7.4-alpine'
|
||||
volumes:
|
||||
- 'hctv_redis:/data'
|
||||
mediamtx:
|
||||
image: 'bluenviron/mediamtx:latest'
|
||||
build:
|
||||
context: .
|
||||
dockerfile: docker/mediamtx/Dockerfile
|
||||
ports:
|
||||
- '8890:8890/udp'
|
||||
postgres-exporter:
|
||||
image: 'prometheuscommunity/postgres-exporter:v0.17.1'
|
||||
environment:
|
||||
DATA_SOURCE_NAME: 'postgresql://postgres:${PG_PASS}@postgres:5432/hctv?sslmode=disable'
|
||||
redis-exporter:
|
||||
image: 'oliver006/redis_exporter:v1.67.0'
|
||||
environment:
|
||||
REDIS_ADDR: 'redis://redis:6379'
|
||||
prometheus:
|
||||
image: 'prom/prometheus:v3.4.2'
|
||||
command:
|
||||
- '--config.file=/etc/prometheus/prometheus.yml'
|
||||
- '--config.expand-env'
|
||||
- '--storage.tsdb.path=/prometheus'
|
||||
- '--web.enable-lifecycle'
|
||||
env_file:
|
||||
- .env
|
||||
volumes:
|
||||
- './mediamtx.yml:/mediamtx.yml'
|
||||
- './observability/prometheus.yml:/etc/prometheus/prometheus.yml:ro'
|
||||
- 'hctv_prometheus_data:/prometheus'
|
||||
extra_hosts:
|
||||
- 'host.docker.internal:host-gateway'
|
||||
grafana:
|
||||
image: 'grafana/grafana:11.6.0'
|
||||
depends_on:
|
||||
- prometheus
|
||||
environment:
|
||||
GF_SECURITY_ADMIN_USER: '${GRAFANA_ADMIN_USER:-admin}'
|
||||
GF_SECURITY_ADMIN_PASSWORD: '${GRAFANA_ADMIN_PASSWORD:-admin}'
|
||||
GF_USERS_DEFAULT_THEME: light
|
||||
volumes:
|
||||
- './observability/grafana/provisioning/datasources:/etc/grafana/provisioning/datasources:ro'
|
||||
- './observability/grafana/provisioning/dashboards:/etc/grafana/provisioning/dashboards:ro'
|
||||
- './observability/grafana/dashboards:/var/lib/grafana/dashboards:ro'
|
||||
- 'hctv_grafana_data:/var/lib/grafana'
|
||||
|
||||
volumes:
|
||||
hctv_pgdata:
|
||||
hctv_redis:
|
||||
hctv_prometheus_data:
|
||||
hctv_grafana_data:
|
||||
|
||||
@@ -9,22 +9,59 @@ services:
|
||||
- ./psql:/var/lib/postgresql
|
||||
ports:
|
||||
- 5555:5432
|
||||
postgres-exporter:
|
||||
image: prometheuscommunity/postgres-exporter:v0.17.1
|
||||
environment:
|
||||
DATA_SOURCE_NAME: postgresql://postgres:skbiditoilet@psql:5432/postgres?sslmode=disable
|
||||
redis:
|
||||
image: redis:7.4-alpine
|
||||
volumes:
|
||||
- ./redis:/data
|
||||
ports:
|
||||
- 6379:6379
|
||||
redis-exporter:
|
||||
image: oliver006/redis_exporter:v1.67.0
|
||||
environment:
|
||||
REDIS_ADDR: redis://redis:6379
|
||||
mediamtx:
|
||||
image: bluenviron/mediamtx:latest
|
||||
ports:
|
||||
- 8890:8890/udp
|
||||
- 8891:8888
|
||||
- 9997:9997
|
||||
- 9998:9998
|
||||
volumes:
|
||||
- ./mediamtx.yml:/mediamtx.yml
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
- 'host.docker.internal:host-gateway'
|
||||
prometheus:
|
||||
image: prom/prometheus:v3.4.2
|
||||
command:
|
||||
- --config.file=/etc/prometheus/prometheus.yml
|
||||
- --storage.tsdb.path=/prometheus
|
||||
- --web.enable-lifecycle
|
||||
volumes:
|
||||
- ../observability/prometheus.dev.yml:/etc/prometheus/prometheus.yml:ro
|
||||
- prometheus_data:/prometheus
|
||||
ports:
|
||||
- 9090:9090
|
||||
extra_hosts:
|
||||
- 'host.docker.internal:host-gateway'
|
||||
grafana:
|
||||
image: grafana/grafana:11.6.0
|
||||
depends_on:
|
||||
- prometheus
|
||||
environment:
|
||||
GF_SECURITY_ADMIN_USER: admin
|
||||
GF_SECURITY_ADMIN_PASSWORD: admin
|
||||
GF_USERS_DEFAULT_THEME: light
|
||||
volumes:
|
||||
- ../observability/grafana/provisioning/datasources:/etc/grafana/provisioning/datasources:ro
|
||||
- ../observability/grafana/provisioning/dashboards:/etc/grafana/provisioning/dashboards:ro
|
||||
- ../observability/grafana/dashboards:/var/lib/grafana/dashboards:ro
|
||||
- grafana_data:/var/lib/grafana
|
||||
ports:
|
||||
- 3001:3000
|
||||
# mediamtx2:
|
||||
# image: bluenviron/mediamtx:latest
|
||||
# ports:
|
||||
@@ -34,4 +71,8 @@ services:
|
||||
# volumes:
|
||||
# - ./mediamtx.yml:/mediamtx.yml
|
||||
# extra_hosts:
|
||||
# - "host.docker.internal:host-gateway"
|
||||
# - "host.docker.internal:host-gateway"
|
||||
|
||||
volumes:
|
||||
prometheus_data:
|
||||
grafana_data:
|
||||
|
||||
@@ -6,13 +6,14 @@ srt: yes
|
||||
srtAddress: :8890
|
||||
|
||||
hls: yes
|
||||
hlsAddress: :8891
|
||||
hlsSegmentCount: 7
|
||||
hlsSegmentDuration: 500ms
|
||||
hlsPartDuration: 200ms
|
||||
hlsMuxerCloseAfter: 5s
|
||||
hlsVariant: lowLatency
|
||||
hlsSegmentDuration: 2s
|
||||
hlsPartDuration: 500ms
|
||||
hlsSegmentCount: 10
|
||||
|
||||
authMethod: http
|
||||
authHTTPAddress: http://host.docker.internal:3000/api/mediamtx/publish
|
||||
|
||||
api: yes
|
||||
metrics: yes
|
||||
metricsAddress: :9998
|
||||
|
||||
8
docker/mediamtx/Dockerfile
Normal file
8
docker/mediamtx/Dockerfile
Normal file
@@ -0,0 +1,8 @@
|
||||
FROM bluenviron/mediamtx:1 AS mediamtx
|
||||
|
||||
FROM ubuntu:24.04
|
||||
|
||||
COPY --from=mediamtx /mediamtx /
|
||||
COPY ./docker/mediamtx/mediamtx.yml /mediamtx.yml
|
||||
|
||||
ENTRYPOINT ["/mediamtx"]
|
||||
19
docker/mediamtx/mediamtx.yml
Normal file
19
docker/mediamtx/mediamtx.yml
Normal file
@@ -0,0 +1,19 @@
|
||||
paths:
|
||||
all:
|
||||
source: publisher
|
||||
|
||||
srt: yes
|
||||
srtAddress: :8890
|
||||
|
||||
hls: yes
|
||||
hlsVariant: lowLatency
|
||||
hlsSegmentDuration: 2s
|
||||
hlsPartDuration: 1s
|
||||
hlsSegmentCount: 10
|
||||
|
||||
authMethod: http
|
||||
authHTTPAddress: http://hctv:3000/api/mediamtx/publish
|
||||
|
||||
api: yes
|
||||
metrics: yes
|
||||
metricsAddress: :9998
|
||||
2848
observability/grafana/dashboards/hctv-overview.json
Normal file
2848
observability/grafana/dashboards/hctv-overview.json
Normal file
File diff suppressed because it is too large
Load Diff
10
observability/grafana/provisioning/dashboards/dashboard.yml
Normal file
10
observability/grafana/provisioning/dashboards/dashboard.yml
Normal file
@@ -0,0 +1,10 @@
|
||||
apiVersion: 1
|
||||
|
||||
providers:
|
||||
- name: HackClubTV
|
||||
folder: HackClub TV
|
||||
type: file
|
||||
disableDeletion: false
|
||||
editable: true
|
||||
options:
|
||||
path: /var/lib/grafana/dashboards
|
||||
@@ -0,0 +1,10 @@
|
||||
apiVersion: 1
|
||||
|
||||
datasources:
|
||||
- name: Prometheus
|
||||
uid: prometheus
|
||||
type: prometheus
|
||||
access: proxy
|
||||
url: http://prometheus:9090
|
||||
isDefault: true
|
||||
editable: false
|
||||
39
observability/prometheus.dev.yml
Normal file
39
observability/prometheus.dev.yml
Normal file
@@ -0,0 +1,39 @@
|
||||
global:
|
||||
scrape_interval: 15s
|
||||
evaluation_interval: 15s
|
||||
|
||||
scrape_configs:
|
||||
- job_name: web
|
||||
metrics_path: /api/metrics
|
||||
static_configs:
|
||||
- targets:
|
||||
- host.docker.internal:3000
|
||||
|
||||
- job_name: chat
|
||||
metrics_path: /metrics
|
||||
static_configs:
|
||||
- targets:
|
||||
- host.docker.internal:8000
|
||||
|
||||
- job_name: mediamtx
|
||||
metrics_path: /metrics
|
||||
static_configs:
|
||||
- targets:
|
||||
- mediamtx:9998
|
||||
|
||||
- job_name: redis
|
||||
metrics_path: /metrics
|
||||
static_configs:
|
||||
- targets:
|
||||
- redis-exporter:9121
|
||||
|
||||
- job_name: postgres
|
||||
metrics_path: /metrics
|
||||
static_configs:
|
||||
- targets:
|
||||
- postgres-exporter:9187
|
||||
|
||||
- job_name: prometheus
|
||||
static_configs:
|
||||
- targets:
|
||||
- localhost:9090
|
||||
45
observability/prometheus.yml
Normal file
45
observability/prometheus.yml
Normal file
@@ -0,0 +1,45 @@
|
||||
global:
|
||||
scrape_interval: 15s
|
||||
evaluation_interval: 15s
|
||||
|
||||
scrape_configs:
|
||||
- job_name: web
|
||||
metrics_path: /api/metrics
|
||||
basic_auth:
|
||||
username: ${METRICS_USER}
|
||||
password: ${METRICS_PASS}
|
||||
static_configs:
|
||||
- targets:
|
||||
- hctv:3000
|
||||
|
||||
- job_name: chat
|
||||
metrics_path: /metrics
|
||||
basic_auth:
|
||||
username: ${METRICS_USER}
|
||||
password: ${METRICS_PASS}
|
||||
static_configs:
|
||||
- targets:
|
||||
- chat:8000
|
||||
|
||||
- job_name: mediamtx
|
||||
metrics_path: /metrics
|
||||
static_configs:
|
||||
- targets:
|
||||
- mediamtx:9998
|
||||
|
||||
- job_name: redis
|
||||
metrics_path: /metrics
|
||||
static_configs:
|
||||
- targets:
|
||||
- redis-exporter:9121
|
||||
|
||||
- job_name: postgres
|
||||
metrics_path: /metrics
|
||||
static_configs:
|
||||
- targets:
|
||||
- postgres-exporter:9187
|
||||
|
||||
- job_name: prometheus
|
||||
static_configs:
|
||||
- targets:
|
||||
- localhost:9090
|
||||
@@ -10,9 +10,9 @@
|
||||
},
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"@prisma/client": "^6.5.0",
|
||||
"@prisma/client": "6.5.0",
|
||||
"ioredis": "5.7.0",
|
||||
"prisma": "^6.5.0"
|
||||
"prisma": "6.5.0"
|
||||
},
|
||||
"scripts": {
|
||||
"db:generate": "prisma generate",
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "ChatModerationAction" AS ENUM (
|
||||
'MESSAGE_BLOCKED',
|
||||
'MESSAGE_DELETED',
|
||||
'USER_TIMEOUT',
|
||||
'USER_BANNED',
|
||||
'USER_UNBANNED'
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "ChatModerationSettings" (
|
||||
"id" TEXT NOT NULL,
|
||||
"channelId" TEXT NOT NULL,
|
||||
"blockedTerms" TEXT[] DEFAULT ARRAY[]::TEXT[],
|
||||
"slowModeSeconds" INTEGER NOT NULL DEFAULT 0,
|
||||
"maxMessageLength" INTEGER NOT NULL DEFAULT 400,
|
||||
"rateLimitCount" INTEGER NOT NULL DEFAULT 8,
|
||||
"rateLimitWindowSeconds" INTEGER NOT NULL DEFAULT 10,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "ChatModerationSettings_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "ChatUserBan" (
|
||||
"id" TEXT NOT NULL,
|
||||
"channelId" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"reason" TEXT NOT NULL,
|
||||
"bannedById" TEXT NOT NULL,
|
||||
"expiresAt" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "ChatUserBan_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "ChatModerationEvent" (
|
||||
"id" TEXT NOT NULL,
|
||||
"channelId" TEXT NOT NULL,
|
||||
"action" "ChatModerationAction" NOT NULL,
|
||||
"moderatorId" TEXT NOT NULL,
|
||||
"targetUserId" TEXT,
|
||||
"reason" TEXT,
|
||||
"details" JSONB,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "ChatModerationEvent_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "ChatModerationSettings_channelId_key" ON "ChatModerationSettings"("channelId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "ChatModerationSettings_channelId_idx" ON "ChatModerationSettings"("channelId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "ChatUserBan_channelId_userId_key" ON "ChatUserBan"("channelId", "userId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "ChatUserBan_channelId_userId_idx" ON "ChatUserBan"("channelId", "userId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "ChatUserBan_expiresAt_idx" ON "ChatUserBan"("expiresAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "ChatModerationEvent_channelId_createdAt_idx" ON "ChatModerationEvent"("channelId", "createdAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "ChatModerationEvent_moderatorId_idx" ON "ChatModerationEvent"("moderatorId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "ChatModerationEvent_targetUserId_idx" ON "ChatModerationEvent"("targetUserId");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "ChatModerationSettings" ADD CONSTRAINT "ChatModerationSettings_channelId_fkey" FOREIGN KEY ("channelId") REFERENCES "Channel"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "ChatUserBan" ADD CONSTRAINT "ChatUserBan_channelId_fkey" FOREIGN KEY ("channelId") REFERENCES "Channel"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "ChatUserBan" ADD CONSTRAINT "ChatUserBan_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "ChatUserBan" ADD CONSTRAINT "ChatUserBan_bannedById_fkey" FOREIGN KEY ("bannedById") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "ChatModerationEvent" ADD CONSTRAINT "ChatModerationEvent_channelId_fkey" FOREIGN KEY ("channelId") REFERENCES "Channel"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "ChatModerationEvent" ADD CONSTRAINT "ChatModerationEvent_moderatorId_fkey" FOREIGN KEY ("moderatorId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "ChatModerationEvent" ADD CONSTRAINT "ChatModerationEvent_targetUserId_fkey" FOREIGN KEY ("targetUserId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,35 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "AdminAuditAction" AS ENUM (
|
||||
'USER_BANNED',
|
||||
'USER_UNBANNED',
|
||||
'USER_PROMOTED',
|
||||
'USER_DEMOTED',
|
||||
'CHANNEL_RESTRICTED',
|
||||
'CHANNEL_UNRESTRICTED'
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "AdminAuditLog" (
|
||||
"id" TEXT NOT NULL,
|
||||
"action" "AdminAuditAction" NOT NULL,
|
||||
"actorId" TEXT NOT NULL,
|
||||
"targetUserId" TEXT,
|
||||
"targetChannel" TEXT,
|
||||
"reason" TEXT,
|
||||
"details" JSONB,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "AdminAuditLog_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "AdminAuditLog_actorId_idx" ON "AdminAuditLog"("actorId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "AdminAuditLog_createdAt_idx" ON "AdminAuditLog"("createdAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "AdminAuditLog_action_createdAt_idx" ON "AdminAuditLog"("action", "createdAt");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "AdminAuditLog" ADD CONSTRAINT "AdminAuditLog_actorId_fkey" FOREIGN KEY ("actorId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,37 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "ChatReportStatus" AS ENUM ('OPEN', 'REVIEWED', 'DISMISSED');
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "ChatUserReport" (
|
||||
"id" TEXT NOT NULL,
|
||||
"channelId" TEXT NOT NULL,
|
||||
"reporterId" TEXT NOT NULL,
|
||||
"targetUserId" TEXT,
|
||||
"targetUsername" TEXT,
|
||||
"reportedMessage" TEXT,
|
||||
"reportedMessageId" TEXT,
|
||||
"reason" TEXT NOT NULL,
|
||||
"status" "ChatReportStatus" NOT NULL DEFAULT 'OPEN',
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "ChatUserReport_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "ChatUserReport_channelId_createdAt_idx" ON "ChatUserReport"("channelId", "createdAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "ChatUserReport_reporterId_createdAt_idx" ON "ChatUserReport"("reporterId", "createdAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "ChatUserReport_status_createdAt_idx" ON "ChatUserReport"("status", "createdAt");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "ChatUserReport" ADD CONSTRAINT "ChatUserReport_channelId_fkey" FOREIGN KEY ("channelId") REFERENCES "Channel"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "ChatUserReport" ADD CONSTRAINT "ChatUserReport_reporterId_fkey" FOREIGN KEY ("reporterId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "ChatUserReport" ADD CONSTRAINT "ChatUserReport_targetUserId_fkey" FOREIGN KEY ("targetUserId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,30 @@
|
||||
-- AlterEnum
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'REPORT_REVIEWED';
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'REPORT_DISMISSED';
|
||||
ALTER TYPE "AdminAuditAction" ADD VALUE 'REPORT_ENFORCEMENT';
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "ChatReportAction" AS ENUM (
|
||||
'REVIEW',
|
||||
'DISMISS',
|
||||
'DELETE_REPORTED_MESSAGE',
|
||||
'TIMEOUT_10M',
|
||||
'TIMEOUT_1H',
|
||||
'BAN_CHAT',
|
||||
'LIFT_CHAT_BAN',
|
||||
'BAN_PLATFORM',
|
||||
'UNBAN_PLATFORM'
|
||||
);
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "ChatUserReport"
|
||||
ADD COLUMN "handledById" TEXT,
|
||||
ADD COLUMN "handledAt" TIMESTAMP(3),
|
||||
ADD COLUMN "handlingNote" TEXT,
|
||||
ADD COLUMN "lastAction" "ChatReportAction";
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "ChatUserReport_handledById_handledAt_idx" ON "ChatUserReport"("handledById", "handledAt");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "ChatUserReport" ADD CONSTRAINT "ChatUserReport_handledById_fkey" FOREIGN KEY ("handledById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,33 @@
|
||||
-- CreateTable
|
||||
CREATE TABLE "_ChannelChatModerators" (
|
||||
"A" TEXT NOT NULL,
|
||||
"B" TEXT NOT NULL,
|
||||
|
||||
CONSTRAINT "_ChannelChatModerators_AB_pkey" PRIMARY KEY ("A","B")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "_ChannelChatBotModerators" (
|
||||
"A" TEXT NOT NULL,
|
||||
"B" TEXT NOT NULL,
|
||||
|
||||
CONSTRAINT "_ChannelChatBotModerators_AB_pkey" PRIMARY KEY ("A","B")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "_ChannelChatModerators_B_index" ON "_ChannelChatModerators"("B");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "_ChannelChatBotModerators_B_index" ON "_ChannelChatBotModerators"("B");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "_ChannelChatModerators" ADD CONSTRAINT "_ChannelChatModerators_A_fkey" FOREIGN KEY ("A") REFERENCES "Channel"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "_ChannelChatModerators" ADD CONSTRAINT "_ChannelChatModerators_B_fkey" FOREIGN KEY ("B") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "_ChannelChatBotModerators" ADD CONSTRAINT "_ChannelChatBotModerators_A_fkey" FOREIGN KEY ("A") REFERENCES "BotAccount"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "_ChannelChatBotModerators" ADD CONSTRAINT "_ChannelChatBotModerators_B_fkey" FOREIGN KEY ("B") REFERENCES "Channel"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -30,11 +30,20 @@ model User {
|
||||
|
||||
ownedChannels Channel[] @relation("ChannelOwner")
|
||||
managedChannels Channel[] @relation("ChannelManagers")
|
||||
chatModeratedChannels Channel[] @relation("ChannelChatModerators")
|
||||
sessions Session[]
|
||||
streams StreamInfo[]
|
||||
followers Follow[] @relation("UserFollows")
|
||||
botAccounts BotAccount[]
|
||||
ban UserBan?
|
||||
chatBans ChatUserBan[] @relation("ChatBannedUser")
|
||||
issuedChatBans ChatUserBan[] @relation("ChatBannedBy")
|
||||
chatModActions ChatModerationEvent[] @relation("ChatModerationActor")
|
||||
chatModTargets ChatModerationEvent[] @relation("ChatModerationTarget")
|
||||
adminAuditLogs AdminAuditLog[] @relation("AdminAuditActor")
|
||||
chatReportsMade ChatUserReport[] @relation("ChatReportReporter")
|
||||
chatReportsSeen ChatUserReport[] @relation("ChatReportTarget")
|
||||
chatReportsHandled ChatUserReport[] @relation("ChatReportHandler")
|
||||
|
||||
@@index([personalChannelId])
|
||||
}
|
||||
@@ -54,12 +63,18 @@ model Channel {
|
||||
owner User @relation("ChannelOwner", fields: [ownerId], references: [id])
|
||||
ownerId String
|
||||
managers User[] @relation("ChannelManagers")
|
||||
chatModerators User[] @relation("ChannelChatModerators")
|
||||
chatModeratorBots BotAccount[] @relation("ChannelChatBotModerators")
|
||||
streamInfo StreamInfo[]
|
||||
followers Follow[] @relation("ChannelFollowers")
|
||||
streamKey StreamKey?
|
||||
obsChatGrantToken String @unique @default(cuid())
|
||||
is247 Boolean @default(false)
|
||||
restriction ChannelRestriction?
|
||||
chatSettings ChatModerationSettings?
|
||||
chatBans ChatUserBan[]
|
||||
chatModEvents ChatModerationEvent[]
|
||||
chatReports ChatUserReport[]
|
||||
|
||||
@@index([ownerId])
|
||||
}
|
||||
@@ -126,6 +141,7 @@ model BotAccount {
|
||||
pfpUrl String
|
||||
owner User @relation(fields: [ownerId], references: [id])
|
||||
ownerId String
|
||||
moderatingChannels Channel[] @relation("ChannelChatBotModerators")
|
||||
apiKeys BotApiKey[]
|
||||
|
||||
createdAt DateTime @default(now())
|
||||
@@ -169,3 +185,135 @@ model ChannelRestriction {
|
||||
|
||||
@@index([channelId])
|
||||
}
|
||||
|
||||
model ChatModerationSettings {
|
||||
id String @id @default(cuid())
|
||||
channel Channel @relation(fields: [channelId], references: [id], onDelete: Cascade)
|
||||
channelId String @unique
|
||||
blockedTerms String[] @default([])
|
||||
slowModeSeconds Int @default(0)
|
||||
maxMessageLength Int @default(400)
|
||||
rateLimitCount Int @default(8)
|
||||
rateLimitWindowSeconds Int @default(10)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@index([channelId])
|
||||
}
|
||||
|
||||
model ChatUserBan {
|
||||
id String @id @default(cuid())
|
||||
channel Channel @relation(fields: [channelId], references: [id], onDelete: Cascade)
|
||||
channelId String
|
||||
user User @relation("ChatBannedUser", fields: [userId], references: [id], onDelete: Cascade)
|
||||
userId String
|
||||
reason String
|
||||
bannedBy User @relation("ChatBannedBy", fields: [bannedById], references: [id], onDelete: Cascade)
|
||||
bannedById String
|
||||
expiresAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@unique([channelId, userId])
|
||||
@@index([channelId, userId])
|
||||
@@index([expiresAt])
|
||||
}
|
||||
|
||||
model ChatModerationEvent {
|
||||
id String @id @default(cuid())
|
||||
channel Channel @relation(fields: [channelId], references: [id], onDelete: Cascade)
|
||||
channelId String
|
||||
action ChatModerationAction
|
||||
moderator User @relation("ChatModerationActor", fields: [moderatorId], references: [id], onDelete: Cascade)
|
||||
moderatorId String
|
||||
targetUser User? @relation("ChatModerationTarget", fields: [targetUserId], references: [id], onDelete: SetNull)
|
||||
targetUserId String?
|
||||
reason String?
|
||||
details Json?
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@index([channelId, createdAt])
|
||||
@@index([moderatorId])
|
||||
@@index([targetUserId])
|
||||
}
|
||||
|
||||
model AdminAuditLog {
|
||||
id String @id @default(cuid())
|
||||
action AdminAuditAction
|
||||
actor User @relation("AdminAuditActor", fields: [actorId], references: [id], onDelete: Cascade)
|
||||
actorId String
|
||||
targetUserId String?
|
||||
targetChannel String?
|
||||
reason String?
|
||||
details Json?
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@index([actorId])
|
||||
@@index([createdAt])
|
||||
@@index([action, createdAt])
|
||||
}
|
||||
|
||||
model ChatUserReport {
|
||||
id String @id @default(cuid())
|
||||
channel Channel @relation(fields: [channelId], references: [id], onDelete: Cascade)
|
||||
channelId String
|
||||
reporter User @relation("ChatReportReporter", fields: [reporterId], references: [id], onDelete: Cascade)
|
||||
reporterId String
|
||||
targetUser User? @relation("ChatReportTarget", fields: [targetUserId], references: [id], onDelete: SetNull)
|
||||
targetUserId String?
|
||||
targetUsername String?
|
||||
reportedMessage String?
|
||||
reportedMessageId String?
|
||||
reason String
|
||||
status ChatReportStatus @default(OPEN)
|
||||
handledBy User? @relation("ChatReportHandler", fields: [handledById], references: [id], onDelete: SetNull)
|
||||
handledById String?
|
||||
handledAt DateTime?
|
||||
handlingNote String?
|
||||
lastAction ChatReportAction?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@index([channelId, createdAt])
|
||||
@@index([reporterId, createdAt])
|
||||
@@index([status, createdAt])
|
||||
@@index([handledById, handledAt])
|
||||
}
|
||||
|
||||
enum ChatReportStatus {
|
||||
OPEN
|
||||
REVIEWED
|
||||
DISMISSED
|
||||
}
|
||||
|
||||
enum ChatReportAction {
|
||||
REVIEW
|
||||
DISMISS
|
||||
DELETE_REPORTED_MESSAGE
|
||||
TIMEOUT_10M
|
||||
TIMEOUT_1H
|
||||
BAN_CHAT
|
||||
LIFT_CHAT_BAN
|
||||
BAN_PLATFORM
|
||||
UNBAN_PLATFORM
|
||||
}
|
||||
|
||||
enum AdminAuditAction {
|
||||
USER_BANNED
|
||||
USER_UNBANNED
|
||||
USER_PROMOTED
|
||||
USER_DEMOTED
|
||||
CHANNEL_RESTRICTED
|
||||
CHANNEL_UNRESTRICTED
|
||||
REPORT_REVIEWED
|
||||
REPORT_DISMISSED
|
||||
REPORT_ENFORCEMENT
|
||||
}
|
||||
|
||||
enum ChatModerationAction {
|
||||
MESSAGE_BLOCKED
|
||||
MESSAGE_DELETED
|
||||
USER_TIMEOUT
|
||||
USER_BANNED
|
||||
USER_UNBANNED
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@hctv/sdk",
|
||||
"version": "1.0.0",
|
||||
"version": "0.1.0",
|
||||
"scripts": {
|
||||
"test": "vitest run",
|
||||
"build": "tsup",
|
||||
@@ -23,6 +23,9 @@
|
||||
"LICENSE",
|
||||
"package.json"
|
||||
],
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"repository": "https://github.com/SrIzan10/ts-lib-boilerplate.git",
|
||||
"author": "Izan Gil <npm@srizan.dev>",
|
||||
"license": "MIT",
|
||||
|
||||
@@ -1,8 +1,15 @@
|
||||
// most code here has been written by claude opus 4.5
|
||||
import type {
|
||||
ChatAccessHandler,
|
||||
ChatAccessState,
|
||||
ChatMessage,
|
||||
HistoryHandler,
|
||||
MessageHandler,
|
||||
ModerationCommand,
|
||||
ModerationError,
|
||||
ModerationErrorHandler,
|
||||
ModerationEvent,
|
||||
ModerationEventHandler,
|
||||
ServerChatMessage,
|
||||
SystemMessage,
|
||||
SystemMessageHandler,
|
||||
@@ -17,6 +24,9 @@ interface ChannelConnection {
|
||||
messageHandlers: Set<MessageHandler>;
|
||||
systemMessageHandlers: Set<SystemMessageHandler>;
|
||||
historyHandlers: Set<HistoryHandler>;
|
||||
moderationErrorHandlers: Set<ModerationErrorHandler>;
|
||||
moderationEventHandlers: Set<ModerationEventHandler>;
|
||||
chatAccessHandlers: Set<ChatAccessHandler>;
|
||||
}
|
||||
|
||||
export class ChatClient {
|
||||
@@ -27,6 +37,9 @@ export class ChatClient {
|
||||
private globalMessageHandlers: Set<MessageHandler> = new Set();
|
||||
private globalSystemMessageHandlers: Set<SystemMessageHandler> = new Set();
|
||||
private globalHistoryHandlers: Set<HistoryHandler> = new Set();
|
||||
private globalModerationErrorHandlers: Set<ModerationErrorHandler> = new Set();
|
||||
private globalModerationEventHandlers: Set<ModerationEventHandler> = new Set();
|
||||
private globalChatAccessHandlers: Set<ChatAccessHandler> = new Set();
|
||||
|
||||
constructor(botToken: string, options?: ChatClientOptions) {
|
||||
this.botToken = botToken;
|
||||
@@ -54,6 +67,9 @@ export class ChatClient {
|
||||
messageHandlers: new Set(),
|
||||
systemMessageHandlers: new Set(),
|
||||
historyHandlers: new Set(),
|
||||
moderationErrorHandlers: new Set(),
|
||||
moderationEventHandlers: new Set(),
|
||||
chatAccessHandlers: new Set(),
|
||||
};
|
||||
|
||||
this.connections.set(channelName, connection);
|
||||
@@ -131,6 +147,46 @@ export class ChatClient {
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.type === 'chatAccess') {
|
||||
const access: ChatAccessState = {
|
||||
canSend: Boolean(data.canSend),
|
||||
restriction: data.restriction ?? null,
|
||||
};
|
||||
this.emitChatAccess(access, channelName, connection);
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.type === 'moderationError') {
|
||||
const error: ModerationError = {
|
||||
code: data.code,
|
||||
message: data.message,
|
||||
restriction: data.restriction,
|
||||
};
|
||||
this.emitModerationError(error, channelName, connection);
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.type === 'messageDeleted' && typeof data.msgId === 'string') {
|
||||
const event: ModerationEvent = {
|
||||
type: 'messageDeleted',
|
||||
msgId: data.msgId,
|
||||
channelName,
|
||||
};
|
||||
this.emitModerationEvent(event, connection);
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.type === 'systemMsg' && typeof data.message === 'string') {
|
||||
const systemMsg: SystemMessage = {
|
||||
type: 'connected',
|
||||
channelName,
|
||||
message: data.message,
|
||||
timestamp: Date.now(),
|
||||
};
|
||||
this.emitSystem(systemMsg, connection);
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle emoji responses
|
||||
if (data.type === 'emojiMsgResponse' || data.type === 'emojiSearchResponse') {
|
||||
// Could add emoji handlers in the future
|
||||
@@ -141,6 +197,7 @@ export class ChatClient {
|
||||
private parseServerMessage(msg: ServerChatMessage, channelName: string): ChatMessage {
|
||||
return {
|
||||
id: `${Date.now()}-${Math.random().toString(36).substring(2, 9)}`,
|
||||
msgId: msg.msgId,
|
||||
channelName,
|
||||
username: msg.user.username,
|
||||
displayName: msg.user.displayName,
|
||||
@@ -203,6 +260,59 @@ export class ChatClient {
|
||||
}
|
||||
}
|
||||
|
||||
sendModerationCommand(command: ModerationCommand, channelName: string): void {
|
||||
const connection = this.connections.get(channelName);
|
||||
if (!connection || connection.ws.readyState !== WebSocket.OPEN) {
|
||||
throw new Error(`Not connected to channel: ${channelName}`);
|
||||
}
|
||||
connection.ws.send(JSON.stringify(command));
|
||||
}
|
||||
|
||||
timeoutUser(
|
||||
channelName: string,
|
||||
targetUserId: string,
|
||||
targetUsername: string,
|
||||
durationSeconds = 300
|
||||
): void {
|
||||
this.sendModerationCommand(
|
||||
{
|
||||
type: 'mod:timeoutUser',
|
||||
targetUserId,
|
||||
targetUsername,
|
||||
durationSeconds,
|
||||
},
|
||||
channelName
|
||||
);
|
||||
}
|
||||
|
||||
banUser(
|
||||
channelName: string,
|
||||
targetUserId: string,
|
||||
targetUsername: string,
|
||||
reason?: string
|
||||
): void {
|
||||
this.sendModerationCommand(
|
||||
{
|
||||
type: 'mod:banUser',
|
||||
targetUserId,
|
||||
targetUsername,
|
||||
reason,
|
||||
},
|
||||
channelName
|
||||
);
|
||||
}
|
||||
|
||||
liftTimeout(channelName: string, targetUserId: string, targetUsername: string): void {
|
||||
this.sendModerationCommand(
|
||||
{
|
||||
type: 'mod:liftTimeout',
|
||||
targetUserId,
|
||||
targetUsername,
|
||||
},
|
||||
channelName
|
||||
);
|
||||
}
|
||||
|
||||
onMessage(handler: MessageHandler, channelName?: string): () => void {
|
||||
if (channelName) {
|
||||
// Channel-specific handler
|
||||
@@ -251,6 +361,48 @@ export class ChatClient {
|
||||
}
|
||||
}
|
||||
|
||||
onModerationError(handler: ModerationErrorHandler, channelName?: string): () => void {
|
||||
if (channelName) {
|
||||
const connection = this.connections.get(channelName);
|
||||
if (!connection) {
|
||||
throw new Error(`Not connected to channel: ${channelName}`);
|
||||
}
|
||||
connection.moderationErrorHandlers.add(handler);
|
||||
return () => connection.moderationErrorHandlers.delete(handler);
|
||||
}
|
||||
|
||||
this.globalModerationErrorHandlers.add(handler);
|
||||
return () => this.globalModerationErrorHandlers.delete(handler);
|
||||
}
|
||||
|
||||
onModerationEvent(handler: ModerationEventHandler, channelName?: string): () => void {
|
||||
if (channelName) {
|
||||
const connection = this.connections.get(channelName);
|
||||
if (!connection) {
|
||||
throw new Error(`Not connected to channel: ${channelName}`);
|
||||
}
|
||||
connection.moderationEventHandlers.add(handler);
|
||||
return () => connection.moderationEventHandlers.delete(handler);
|
||||
}
|
||||
|
||||
this.globalModerationEventHandlers.add(handler);
|
||||
return () => this.globalModerationEventHandlers.delete(handler);
|
||||
}
|
||||
|
||||
onChatAccess(handler: ChatAccessHandler, channelName?: string): () => void {
|
||||
if (channelName) {
|
||||
const connection = this.connections.get(channelName);
|
||||
if (!connection) {
|
||||
throw new Error(`Not connected to channel: ${channelName}`);
|
||||
}
|
||||
connection.chatAccessHandlers.add(handler);
|
||||
return () => connection.chatAccessHandlers.delete(handler);
|
||||
}
|
||||
|
||||
this.globalChatAccessHandlers.add(handler);
|
||||
return () => this.globalChatAccessHandlers.delete(handler);
|
||||
}
|
||||
|
||||
private emitMessage(message: ChatMessage, connection: ChannelConnection): void {
|
||||
// Emit to channel-specific handlers
|
||||
connection.messageHandlers.forEach((handler) => handler(message));
|
||||
@@ -265,6 +417,29 @@ export class ChatClient {
|
||||
this.globalSystemMessageHandlers.forEach((handler) => handler(message));
|
||||
}
|
||||
|
||||
private emitModerationError(
|
||||
error: ModerationError,
|
||||
channelName: string,
|
||||
connection: ChannelConnection
|
||||
): void {
|
||||
connection.moderationErrorHandlers.forEach((handler) => handler(error, channelName));
|
||||
this.globalModerationErrorHandlers.forEach((handler) => handler(error, channelName));
|
||||
}
|
||||
|
||||
private emitModerationEvent(event: ModerationEvent, connection: ChannelConnection): void {
|
||||
connection.moderationEventHandlers.forEach((handler) => handler(event));
|
||||
this.globalModerationEventHandlers.forEach((handler) => handler(event));
|
||||
}
|
||||
|
||||
private emitChatAccess(
|
||||
access: ChatAccessState,
|
||||
channelName: string,
|
||||
connection: ChannelConnection
|
||||
): void {
|
||||
connection.chatAccessHandlers.forEach((handler) => handler(access, channelName));
|
||||
this.globalChatAccessHandlers.forEach((handler) => handler(access, channelName));
|
||||
}
|
||||
|
||||
isConnectedTo(channelName: string): boolean {
|
||||
const connection = this.connections.get(channelName);
|
||||
return connection ? connection.ws.readyState === WebSocket.OPEN : false;
|
||||
|
||||
@@ -15,4 +15,17 @@ interface ConstructorArgs {
|
||||
chatOptions?: import('./chat.js').ChatClientOptions;
|
||||
}
|
||||
export { ChatClient, type ChatClientOptions } from './chat.js';
|
||||
export type { ChatMessage, MessageHandler, SystemMessage, SystemMessageHandler, HistoryHandler } from './types.js';
|
||||
export type {
|
||||
ChatAccessHandler,
|
||||
ChatAccessState,
|
||||
ChatMessage,
|
||||
HistoryHandler,
|
||||
MessageHandler,
|
||||
ModerationCommand,
|
||||
ModerationError,
|
||||
ModerationErrorHandler,
|
||||
ModerationEvent,
|
||||
ModerationEventHandler,
|
||||
SystemMessage,
|
||||
SystemMessageHandler,
|
||||
} from './types.js';
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
export interface ChatMessage {
|
||||
id: string;
|
||||
msgId?: string;
|
||||
channelName: string;
|
||||
username: string;
|
||||
displayName?: string;
|
||||
@@ -27,9 +28,48 @@ export interface ServerChatMessage {
|
||||
isBot?: boolean;
|
||||
};
|
||||
message: string;
|
||||
msgId?: string;
|
||||
type?: 'message' | 'systemMsg';
|
||||
}
|
||||
|
||||
export interface ChatAccessState {
|
||||
canSend: boolean;
|
||||
restriction?: {
|
||||
type: 'timeout' | 'ban';
|
||||
reason?: string;
|
||||
expiresAt?: string | null;
|
||||
} | null;
|
||||
}
|
||||
|
||||
export interface ModerationError {
|
||||
code: string;
|
||||
message: string;
|
||||
restriction?: ChatAccessState['restriction'];
|
||||
}
|
||||
|
||||
export interface ModerationEvent {
|
||||
type: 'messageDeleted';
|
||||
msgId: string;
|
||||
channelName: string;
|
||||
}
|
||||
|
||||
export interface ModerationCommand {
|
||||
type:
|
||||
| 'mod:deleteMessage'
|
||||
| 'mod:timeoutUser'
|
||||
| 'mod:banUser'
|
||||
| 'mod:unbanUser'
|
||||
| 'mod:liftTimeout';
|
||||
msgId?: string;
|
||||
targetUserId?: string;
|
||||
targetUsername?: string;
|
||||
durationSeconds?: number;
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
export type MessageHandler = (message: ChatMessage) => void;
|
||||
export type SystemMessageHandler = (message: SystemMessage) => void;
|
||||
export type HistoryHandler = (messages: ChatMessage[]) => void;
|
||||
export type ChatAccessHandler = (state: ChatAccessState, channelName: string) => void;
|
||||
export type ModerationErrorHandler = (error: ModerationError, channelName: string) => void;
|
||||
export type ModerationEventHandler = (event: ModerationEvent) => void;
|
||||
|
||||
197
pnpm-lock.yaml
generated
197
pnpm-lock.yaml
generated
@@ -41,6 +41,9 @@ importers:
|
||||
hono:
|
||||
specifier: ^4.7.5
|
||||
version: 4.11.3
|
||||
prom-client:
|
||||
specifier: ^15.1.3
|
||||
version: 15.1.3
|
||||
devDependencies:
|
||||
'@types/node':
|
||||
specifier: ^20.11.17
|
||||
@@ -183,6 +186,9 @@ importers:
|
||||
date-fns:
|
||||
specifier: ^4.1.0
|
||||
version: 4.1.0
|
||||
embla-carousel-react:
|
||||
specifier: ^8.6.0
|
||||
version: 8.6.0(react@19.2.3)
|
||||
hls-video-element:
|
||||
specifier: ^1.5.0
|
||||
version: 1.5.10
|
||||
@@ -216,6 +222,9 @@ importers:
|
||||
pg-boss:
|
||||
specifier: ^10.1.6
|
||||
version: 10.4.0
|
||||
prom-client:
|
||||
specifier: ^15.1.3
|
||||
version: 15.1.3
|
||||
react:
|
||||
specifier: ^19.2.3
|
||||
version: 19.2.3
|
||||
@@ -333,14 +342,14 @@ importers:
|
||||
packages/db:
|
||||
dependencies:
|
||||
'@prisma/client':
|
||||
specifier: ^6.5.0
|
||||
version: 6.19.1(prisma@6.19.1(typescript@5.9.3))(typescript@5.9.3)
|
||||
specifier: 6.5.0
|
||||
version: 6.5.0(prisma@6.5.0(typescript@5.9.3))(typescript@5.9.3)
|
||||
ioredis:
|
||||
specifier: 5.7.0
|
||||
version: 5.7.0
|
||||
prisma:
|
||||
specifier: ^6.5.0
|
||||
version: 6.19.1(typescript@5.9.3)
|
||||
specifier: 6.5.0
|
||||
version: 6.5.0(typescript@5.9.3)
|
||||
devDependencies:
|
||||
'@types/node':
|
||||
specifier: ^24.0.1
|
||||
@@ -1920,24 +1929,54 @@ packages:
|
||||
typescript:
|
||||
optional: true
|
||||
|
||||
'@prisma/client@6.5.0':
|
||||
resolution: {integrity: sha512-M6w1Ql/BeiGoZmhMdAZUXHu5sz5HubyVcKukbLs3l0ELcQb8hTUJxtGEChhv4SVJ0QJlwtLnwOLgIRQhpsm9dw==}
|
||||
engines: {node: '>=18.18'}
|
||||
peerDependencies:
|
||||
prisma: '*'
|
||||
typescript: '>=5.1.0'
|
||||
peerDependenciesMeta:
|
||||
prisma:
|
||||
optional: true
|
||||
typescript:
|
||||
optional: true
|
||||
|
||||
'@prisma/config@6.19.1':
|
||||
resolution: {integrity: sha512-bUL/aYkGXLwxVGhJmQMtslLT7KPEfUqmRa919fKI4wQFX4bIFUKiY8Jmio/2waAjjPYrtuDHa7EsNCnJTXxiOw==}
|
||||
|
||||
'@prisma/config@6.5.0':
|
||||
resolution: {integrity: sha512-sOH/2Go9Zer67DNFLZk6pYOHj+rumSb0VILgltkoxOjYnlLqUpHPAN826vnx8HigqnOCxj9LRhT6U7uLiIIWgw==}
|
||||
|
||||
'@prisma/debug@6.19.1':
|
||||
resolution: {integrity: sha512-h1JImhlAd/s5nhY/e9qkAzausWldbeT+e4nZF7A4zjDYBF4BZmKDt4y0jK7EZapqOm1kW7V0e9agV/iFDy3fWw==}
|
||||
|
||||
'@prisma/debug@6.5.0':
|
||||
resolution: {integrity: sha512-fc/nusYBlJMzDmDepdUtH9aBsJrda2JNErP9AzuHbgUEQY0/9zQYZdNlXmKoIWENtio+qarPNe/+DQtrX5kMcQ==}
|
||||
|
||||
'@prisma/engines-version@6.5.0-73.173f8d54f8d52e692c7e27e72a88314ec7aeff60':
|
||||
resolution: {integrity: sha512-iK3EmiVGFDCmXjSpdsKGNqy9hOdLnvYBrJB61far/oP03hlIxrb04OWmDjNTwtmZ3UZdA5MCvI+f+3k2jPTflQ==}
|
||||
|
||||
'@prisma/engines-version@7.1.1-3.c2990dca591cba766e3b7ef5d9e8a84796e47ab7':
|
||||
resolution: {integrity: sha512-03bgb1VD5gvuumNf+7fVGBzfpJPjmqV423l/WxsWk2cNQ42JD0/SsFBPhN6z8iAvdHs07/7ei77SKu7aZfq8bA==}
|
||||
|
||||
'@prisma/engines@6.19.1':
|
||||
resolution: {integrity: sha512-xy95dNJ7DiPf9IJ3oaVfX785nbFl7oNDzclUF+DIiJw6WdWCvPl0LPU0YqQLsrwv8N64uOQkH391ujo3wSo+Nw==}
|
||||
|
||||
'@prisma/engines@6.5.0':
|
||||
resolution: {integrity: sha512-FVPQYHgOllJklN9DUyujXvh3hFJCY0NX86sDmBErLvoZjy2OXGiZ5FNf3J/C4/RZZmCypZBYpBKEhx7b7rEsdw==}
|
||||
|
||||
'@prisma/fetch-engine@6.19.1':
|
||||
resolution: {integrity: sha512-mmgcotdaq4VtAHO6keov3db+hqlBzQS6X7tR7dFCbvXjLVTxBYdSJFRWz+dq7F9p6dvWyy1X0v8BlfRixyQK6g==}
|
||||
|
||||
'@prisma/fetch-engine@6.5.0':
|
||||
resolution: {integrity: sha512-3LhYA+FXP6pqY8FLHCjewyE8pGXXJ7BxZw2rhPq+CZAhvflVzq4K8Qly3OrmOkn6wGlz79nyLQdknyCG2HBTuA==}
|
||||
|
||||
'@prisma/get-platform@6.19.1':
|
||||
resolution: {integrity: sha512-zsg44QUiQAnFUyh6Fbt7c9HjMXHwFTqtrgcX7DAZmRgnkPyYT7Sh8Mn8D5PuuDYNtMOYcpLGg576MLfIORsBYw==}
|
||||
|
||||
'@prisma/get-platform@6.5.0':
|
||||
resolution: {integrity: sha512-xYcvyJwNMg2eDptBYFqFLUCfgi+wZLcj6HDMsj0Qw0irvauG4IKmkbywnqwok0B+k+W+p+jThM2DKTSmoPCkzw==}
|
||||
|
||||
'@prisma/instrumentation@6.19.0':
|
||||
resolution: {integrity: sha512-QcuYy25pkXM8BJ37wVFBO7Zh34nyRV1GOb2n3lPkkbRYfl4hWl3PTcImP41P0KrzVXfa/45p6eVCos27x3exIg==}
|
||||
peerDependencies:
|
||||
@@ -3857,6 +3896,9 @@ packages:
|
||||
resolution: {integrity: sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==}
|
||||
engines: {node: '>=8'}
|
||||
|
||||
bintrees@1.0.2:
|
||||
resolution: {integrity: sha512-VOMgTMwjAaUG580SXn3LacVgjurrbMme7ZZNYGSSV7mmtY6QQRh0Eg3pwIcntQ77DErK1L0NxkbetjcoXzVwKw==}
|
||||
|
||||
bl@5.1.0:
|
||||
resolution: {integrity: sha512-tv1ZJHLfTDnXE6tMHv73YgSJaWR2AFuPwMntBe7XL/GBFHnT0CLnsHMogfk5+GzCDC5ZWarSCYaIGATZt9dNsQ==}
|
||||
|
||||
@@ -4565,6 +4607,19 @@ packages:
|
||||
electron-to-chromium@1.5.267:
|
||||
resolution: {integrity: sha512-0Drusm6MVRXSOJpGbaSVgcQsuB4hEkMpHXaVstcPmhu5LIedxs1xNK/nIxmQIU/RPC0+1/o0AVZfBTkTNJOdUw==}
|
||||
|
||||
embla-carousel-react@8.6.0:
|
||||
resolution: {integrity: sha512-0/PjqU7geVmo6F734pmPqpyHqiM99olvyecY7zdweCw+6tKEXnrE90pBiBbMMU8s5tICemzpQ3hi5EpxzGW+JA==}
|
||||
peerDependencies:
|
||||
react: ^16.8.0 || ^17.0.1 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc
|
||||
|
||||
embla-carousel-reactive-utils@8.6.0:
|
||||
resolution: {integrity: sha512-fMVUDUEx0/uIEDM0Mz3dHznDhfX+znCCDCeIophYb1QGVM7YThSWX+wz11zlYwWFOr74b4QLGg0hrGPJeG2s4A==}
|
||||
peerDependencies:
|
||||
embla-carousel: 8.6.0
|
||||
|
||||
embla-carousel@8.6.0:
|
||||
resolution: {integrity: sha512-SjWyZBHJPbqxHOzckOfo8lHisEaJWmwd23XppYFYVh10bU66/Pn5tkVkbkCMZVdbUE5eTCI2nD8OyIP4Z+uwkA==}
|
||||
|
||||
emoji-regex@10.6.0:
|
||||
resolution: {integrity: sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==}
|
||||
|
||||
@@ -4648,6 +4703,11 @@ packages:
|
||||
esast-util-from-js@2.0.1:
|
||||
resolution: {integrity: sha512-8Ja+rNJ0Lt56Pcf3TAmpBZjmx8ZcK5Ts4cAzIOjsjevg9oSXJnl6SUQ2EevU8tv3h6ZLWmoKL5H4fgWvdvfETw==}
|
||||
|
||||
esbuild-register@3.6.0:
|
||||
resolution: {integrity: sha512-H2/S7Pm8a9CL1uhp9OvjwrBh5Pvx0H8qVOxNu8Wed9Y7qv56MPtq+GGM8RJpq6glYJn9Wspr8uw7l55uyinNeg==}
|
||||
peerDependencies:
|
||||
esbuild: '>=0.12 <1'
|
||||
|
||||
esbuild@0.25.12:
|
||||
resolution: {integrity: sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==}
|
||||
engines: {node: '>=18'}
|
||||
@@ -5108,11 +5168,12 @@ packages:
|
||||
|
||||
glob@10.5.0:
|
||||
resolution: {integrity: sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==}
|
||||
deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me
|
||||
hasBin: true
|
||||
|
||||
glob@7.2.3:
|
||||
resolution: {integrity: sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==}
|
||||
deprecated: Glob versions prior to v9 are no longer supported
|
||||
deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me
|
||||
|
||||
globals@13.24.0:
|
||||
resolution: {integrity: sha512-AhO5QUcj8llrbG09iWhPU2B204J1xnPeL8kQmVorSsy+Sjj1sk8gIyh6cUocGmH4L0UuhAJy+hJMRA4mgA4mFQ==}
|
||||
@@ -6613,6 +6674,16 @@ packages:
|
||||
typescript:
|
||||
optional: true
|
||||
|
||||
prisma@6.5.0:
|
||||
resolution: {integrity: sha512-yUGXmWqv5F4PByMSNbYFxke/WbnyTLjnJ5bKr8fLkcnY7U5rU9rUTh/+Fja+gOrRxEgtCbCtca94IeITj4j/pg==}
|
||||
engines: {node: '>=18.18'}
|
||||
hasBin: true
|
||||
peerDependencies:
|
||||
typescript: '>=5.1.0'
|
||||
peerDependenciesMeta:
|
||||
typescript:
|
||||
optional: true
|
||||
|
||||
prismjs@1.30.0:
|
||||
resolution: {integrity: sha512-DEvV2ZF2r2/63V+tK8hQvrR2ZGn10srHbXviTlcv7Kpzw8jWiNTqbVgjO3IY8RxrrOUF8VPMQQFysYYYv0YZxw==}
|
||||
engines: {node: '>=6'}
|
||||
@@ -6621,6 +6692,10 @@ packages:
|
||||
resolution: {integrity: sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==}
|
||||
engines: {node: '>=0.4.0'}
|
||||
|
||||
prom-client@15.1.3:
|
||||
resolution: {integrity: sha512-6ZiOBfCywsD4k1BN9IX0uZhF+tJkV8q8llP64G5Hajs4JOeVLPCwpPVcpXy3BwYiUGgyJzsJJQeOIv7+hDSq8g==}
|
||||
engines: {node: ^16 || ^18 || >=20}
|
||||
|
||||
prompts@2.4.2:
|
||||
resolution: {integrity: sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q==}
|
||||
engines: {node: '>= 6'}
|
||||
@@ -7289,6 +7364,9 @@ packages:
|
||||
resolution: {integrity: sha512-g9ljZiwki/LfxmQADO3dEY1CbpmXT5Hm2fJ+QaGKwSXUylMybePR7/67YW7jOrrvjEgL1Fmz5kzyAjWVWLlucg==}
|
||||
engines: {node: '>=6'}
|
||||
|
||||
tdigest@0.1.2:
|
||||
resolution: {integrity: sha512-+G0LLgjjo9BZX2MfdvPfH+MKLCrxlXSYec5DaPYP1fe6Iyhf0/fSmJ0bFiZ1F8BT6cGXl2LpltQptzjXKWEkKA==}
|
||||
|
||||
terser-webpack-plugin@5.3.16:
|
||||
resolution: {integrity: sha512-h9oBFCWrq78NyWWVcSwZarJkZ01c2AyGrzs1crmHZO3QUg9D61Wu4NPjBy69n7JqylFF5y+CsUZYmYEIZ3mR+Q==}
|
||||
engines: {node: '>= 10.13.0'}
|
||||
@@ -9760,6 +9838,11 @@ snapshots:
|
||||
prisma: 6.19.1(typescript@5.9.3)
|
||||
typescript: 5.9.3
|
||||
|
||||
'@prisma/client@6.5.0(prisma@6.5.0(typescript@5.9.3))(typescript@5.9.3)':
|
||||
optionalDependencies:
|
||||
prisma: 6.5.0(typescript@5.9.3)
|
||||
typescript: 5.9.3
|
||||
|
||||
'@prisma/config@6.19.1':
|
||||
dependencies:
|
||||
c12: 3.1.0
|
||||
@@ -9768,10 +9851,24 @@ snapshots:
|
||||
empathic: 2.0.0
|
||||
transitivePeerDependencies:
|
||||
- magicast
|
||||
optional: true
|
||||
|
||||
'@prisma/debug@6.19.1': {}
|
||||
'@prisma/config@6.5.0':
|
||||
dependencies:
|
||||
esbuild: 0.27.2
|
||||
esbuild-register: 3.6.0(esbuild@0.27.2)
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
'@prisma/engines-version@7.1.1-3.c2990dca591cba766e3b7ef5d9e8a84796e47ab7': {}
|
||||
'@prisma/debug@6.19.1':
|
||||
optional: true
|
||||
|
||||
'@prisma/debug@6.5.0': {}
|
||||
|
||||
'@prisma/engines-version@6.5.0-73.173f8d54f8d52e692c7e27e72a88314ec7aeff60': {}
|
||||
|
||||
'@prisma/engines-version@7.1.1-3.c2990dca591cba766e3b7ef5d9e8a84796e47ab7':
|
||||
optional: true
|
||||
|
||||
'@prisma/engines@6.19.1':
|
||||
dependencies:
|
||||
@@ -9779,16 +9876,36 @@ snapshots:
|
||||
'@prisma/engines-version': 7.1.1-3.c2990dca591cba766e3b7ef5d9e8a84796e47ab7
|
||||
'@prisma/fetch-engine': 6.19.1
|
||||
'@prisma/get-platform': 6.19.1
|
||||
optional: true
|
||||
|
||||
'@prisma/engines@6.5.0':
|
||||
dependencies:
|
||||
'@prisma/debug': 6.5.0
|
||||
'@prisma/engines-version': 6.5.0-73.173f8d54f8d52e692c7e27e72a88314ec7aeff60
|
||||
'@prisma/fetch-engine': 6.5.0
|
||||
'@prisma/get-platform': 6.5.0
|
||||
|
||||
'@prisma/fetch-engine@6.19.1':
|
||||
dependencies:
|
||||
'@prisma/debug': 6.19.1
|
||||
'@prisma/engines-version': 7.1.1-3.c2990dca591cba766e3b7ef5d9e8a84796e47ab7
|
||||
'@prisma/get-platform': 6.19.1
|
||||
optional: true
|
||||
|
||||
'@prisma/fetch-engine@6.5.0':
|
||||
dependencies:
|
||||
'@prisma/debug': 6.5.0
|
||||
'@prisma/engines-version': 6.5.0-73.173f8d54f8d52e692c7e27e72a88314ec7aeff60
|
||||
'@prisma/get-platform': 6.5.0
|
||||
|
||||
'@prisma/get-platform@6.19.1':
|
||||
dependencies:
|
||||
'@prisma/debug': 6.19.1
|
||||
optional: true
|
||||
|
||||
'@prisma/get-platform@6.5.0':
|
||||
dependencies:
|
||||
'@prisma/debug': 6.5.0
|
||||
|
||||
'@prisma/instrumentation@6.19.0(@opentelemetry/api@1.9.0)':
|
||||
dependencies:
|
||||
@@ -12230,6 +12347,8 @@ snapshots:
|
||||
|
||||
binary-extensions@2.3.0: {}
|
||||
|
||||
bintrees@1.0.2: {}
|
||||
|
||||
bl@5.1.0:
|
||||
dependencies:
|
||||
buffer: 6.0.3
|
||||
@@ -12328,6 +12447,7 @@ snapshots:
|
||||
perfect-debounce: 1.0.0
|
||||
pkg-types: 2.3.0
|
||||
rc9: 2.1.2
|
||||
optional: true
|
||||
|
||||
cac@6.7.14: {}
|
||||
|
||||
@@ -12439,6 +12559,7 @@ snapshots:
|
||||
citty@0.1.6:
|
||||
dependencies:
|
||||
consola: 3.4.2
|
||||
optional: true
|
||||
|
||||
cjs-module-lexer@1.4.3: {}
|
||||
|
||||
@@ -12528,7 +12649,8 @@ snapshots:
|
||||
|
||||
confbox@0.1.8: {}
|
||||
|
||||
confbox@0.2.2: {}
|
||||
confbox@0.2.2:
|
||||
optional: true
|
||||
|
||||
consola@3.4.2: {}
|
||||
|
||||
@@ -12848,7 +12970,8 @@ snapshots:
|
||||
|
||||
deep-is@0.1.4: {}
|
||||
|
||||
deepmerge-ts@7.1.5: {}
|
||||
deepmerge-ts@7.1.5:
|
||||
optional: true
|
||||
|
||||
deepmerge@4.3.1: {}
|
||||
|
||||
@@ -12961,16 +13084,30 @@ snapshots:
|
||||
dependencies:
|
||||
'@standard-schema/spec': 1.1.0
|
||||
fast-check: 3.23.2
|
||||
optional: true
|
||||
|
||||
electron-to-chromium@1.5.267: {}
|
||||
|
||||
embla-carousel-react@8.6.0(react@19.2.3):
|
||||
dependencies:
|
||||
embla-carousel: 8.6.0
|
||||
embla-carousel-reactive-utils: 8.6.0(embla-carousel@8.6.0)
|
||||
react: 19.2.3
|
||||
|
||||
embla-carousel-reactive-utils@8.6.0(embla-carousel@8.6.0):
|
||||
dependencies:
|
||||
embla-carousel: 8.6.0
|
||||
|
||||
embla-carousel@8.6.0: {}
|
||||
|
||||
emoji-regex@10.6.0: {}
|
||||
|
||||
emoji-regex@8.0.0: {}
|
||||
|
||||
emoji-regex@9.2.2: {}
|
||||
|
||||
empathic@2.0.0: {}
|
||||
empathic@2.0.0:
|
||||
optional: true
|
||||
|
||||
encodeurl@2.0.0: {}
|
||||
|
||||
@@ -13113,6 +13250,13 @@ snapshots:
|
||||
esast-util-from-estree: 2.0.0
|
||||
vfile-message: 4.0.3
|
||||
|
||||
esbuild-register@3.6.0(esbuild@0.27.2):
|
||||
dependencies:
|
||||
debug: 4.4.3
|
||||
esbuild: 0.27.2
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
esbuild@0.25.12:
|
||||
optionalDependencies:
|
||||
'@esbuild/aix-ppc64': 0.25.12
|
||||
@@ -13545,7 +13689,8 @@ snapshots:
|
||||
'@expressive-code/plugin-shiki': 0.41.5
|
||||
'@expressive-code/plugin-text-markers': 0.41.5
|
||||
|
||||
exsolve@1.0.8: {}
|
||||
exsolve@1.0.8:
|
||||
optional: true
|
||||
|
||||
extend@3.0.2: {}
|
||||
|
||||
@@ -13771,6 +13916,7 @@ snapshots:
|
||||
node-fetch-native: 1.6.7
|
||||
nypm: 0.6.2
|
||||
pathe: 2.0.3
|
||||
optional: true
|
||||
|
||||
github-slugger@2.0.0: {}
|
||||
|
||||
@@ -14400,7 +14546,8 @@ snapshots:
|
||||
|
||||
jiti@1.21.7: {}
|
||||
|
||||
jiti@2.6.1: {}
|
||||
jiti@2.6.1:
|
||||
optional: true
|
||||
|
||||
jose@6.1.3: {}
|
||||
|
||||
@@ -15327,6 +15474,7 @@ snapshots:
|
||||
pathe: 2.0.3
|
||||
pkg-types: 2.3.0
|
||||
tinyexec: 1.0.2
|
||||
optional: true
|
||||
|
||||
object-assign@4.1.1: {}
|
||||
|
||||
@@ -15561,7 +15709,8 @@ snapshots:
|
||||
|
||||
pathe@2.0.3: {}
|
||||
|
||||
perfect-debounce@1.0.0: {}
|
||||
perfect-debounce@1.0.0:
|
||||
optional: true
|
||||
|
||||
pg-boss@10.4.0:
|
||||
dependencies:
|
||||
@@ -15631,6 +15780,7 @@ snapshots:
|
||||
confbox: 0.2.2
|
||||
exsolve: 1.0.8
|
||||
pathe: 2.0.3
|
||||
optional: true
|
||||
|
||||
points-on-curve@0.2.0: {}
|
||||
|
||||
@@ -15723,11 +15873,27 @@ snapshots:
|
||||
typescript: 5.9.3
|
||||
transitivePeerDependencies:
|
||||
- magicast
|
||||
optional: true
|
||||
|
||||
prisma@6.5.0(typescript@5.9.3):
|
||||
dependencies:
|
||||
'@prisma/config': 6.5.0
|
||||
'@prisma/engines': 6.5.0
|
||||
optionalDependencies:
|
||||
fsevents: 2.3.3
|
||||
typescript: 5.9.3
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
prismjs@1.30.0: {}
|
||||
|
||||
progress@2.0.3: {}
|
||||
|
||||
prom-client@15.1.3:
|
||||
dependencies:
|
||||
'@opentelemetry/api': 1.9.0
|
||||
tdigest: 0.1.2
|
||||
|
||||
prompts@2.4.2:
|
||||
dependencies:
|
||||
kleur: 3.0.3
|
||||
@@ -15798,6 +15964,7 @@ snapshots:
|
||||
dependencies:
|
||||
defu: 6.1.4
|
||||
destr: 2.0.5
|
||||
optional: true
|
||||
|
||||
react-day-picker@9.13.0(react@19.2.3):
|
||||
dependencies:
|
||||
@@ -16669,6 +16836,10 @@ snapshots:
|
||||
|
||||
tapable@2.3.0: {}
|
||||
|
||||
tdigest@0.1.2:
|
||||
dependencies:
|
||||
bintrees: 1.0.2
|
||||
|
||||
terser-webpack-plugin@5.3.16(webpack@5.104.1):
|
||||
dependencies:
|
||||
'@jridgewell/trace-mapping': 0.3.31
|
||||
|
||||
Reference in New Issue
Block a user