Compare commits
121 Commits
feat/sdk-m
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| de25bc5cd1 | |||
| 184ea9c973 | |||
| beec80fee6 | |||
| 796313348b | |||
| 8d13c86159 | |||
| a2dfe81265 | |||
| ed3ebc9e3a | |||
| 50d92f6787 | |||
|
|
3ac4f59efd | ||
|
|
3de374392c | ||
| 61c005a585 | |||
|
|
c35e3ae1ba | ||
| 7481006dbe | |||
| d5aa3217ac | |||
| 6701090c7a | |||
| d95b935c7a | |||
| efec8602fc | |||
| 0597cb1157 | |||
| 8a924f2d52 | |||
| 79093c5057 | |||
| 2bf452c9ed | |||
| 01b2e88969 | |||
| b42b4be2d9 | |||
| 22f3cff3c1 | |||
| d01cc9f68d | |||
| 12617b3d59 | |||
| aff01be9e1 | |||
| 995a14387c | |||
| 2ce6fea782 | |||
| ab6a788b36 | |||
| 953bc38c12 | |||
| 728dcd9712 | |||
| 9e60e1dfe2 | |||
| 90d73275b2 | |||
| da968232ad | |||
| be758685d1 | |||
| 0add39f8e1 | |||
| 5c4284d552 | |||
|
|
ae5dee33bb | ||
| 4a708ac92f | |||
| 2b270db2ed | |||
| 1a77980218 | |||
| cc5a6a4fd3 | |||
| 503e863fe7 | |||
| 27a65a1893 | |||
| 56eb49b52f | |||
| dcd643784f | |||
| dee32a03d9 | |||
| abffa281d1 | |||
| 77a0d6c945 | |||
| 7974d4434e | |||
| bcdc4122f8 | |||
| d552836845 | |||
| ca6218c494 | |||
| a14762d3a1 | |||
| f1f6d20d53 | |||
| 4d63552254 | |||
| 81e78a622f | |||
| 3dcb726207 | |||
| 5b7e9e7a82 | |||
| 462a51e376 | |||
| 9caeb9f97e | |||
| 1c06020092 | |||
| 1697530ac0 | |||
|
|
29c5b2c24d | ||
|
|
616110dba6 | ||
| fe888d2e72 | |||
| c4774a53f1 | |||
|
|
671dadde08 | ||
|
|
f7634010d6 | ||
|
|
dd122ffa92 | ||
|
|
f1fb3f7bf6 | ||
|
|
7b29aa10d4 | ||
|
|
484aa30878 | ||
| e31c7a1620 | |||
| 3e86ad70c2 | |||
| 14a0ecd763 | |||
| 43ead562a8 | |||
| 71a48c29c3 | |||
| 1f0ba1cd08 | |||
| 63fc35c62c | |||
| 38ec518695 | |||
| 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 |
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
|
||||
|
||||
4
.gitignore
vendored
@@ -50,4 +50,6 @@ slack-import-emojis/target
|
||||
|
||||
.idea
|
||||
|
||||
/apps/docs/src/content/docs/typedoc-sdk
|
||||
/apps/docs/src/content/docs/typedoc-sdk
|
||||
|
||||
.codex
|
||||
@@ -1,4 +1,4 @@
|
||||
# Agent Guidelines for HackClub.tv
|
||||
# Agent Guidelines for tv
|
||||
|
||||
This document provides essential information for AI coding agents working on the HackClub.tv codebase.
|
||||
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
# hackclub.tv
|
||||
|
||||
This is the source code for [hackclub.tv](https://hackclub.tv), a livestreaming website for hackclubbers.
|
||||
This is the source code for [hackclub.tv](https://hackclub.tv), a livestreaming website for Hack Clubbers.
|
||||
|
||||
The development setup guide can be read at <https://docs.hackclub.tv/guides/dev/>
|
||||
|
||||
Join [#hctv](https://hackclub.slack.com/archives/C08HGLXGXAB) on the Hack Club Slack for discussion and updates!
|
||||
|
||||
## Streaming
|
||||
|
||||
To stream to the platform, open [hackclub.tv](https://hackclub.tv), log in, create a channel, press "Edit Livestream" and follow the streaming guide under the "Stream" tab. You can also find the streaming guide at <https://docs.hackclub.tv/guides/streaming/>.
|
||||
@@ -1,6 +1,6 @@
|
||||
FROM node:lts-alpine AS base
|
||||
ENV PNPM_HOME="/pnpm"
|
||||
ENV PATH="$PNPM_HOME:$PATH"
|
||||
ENV PATH="$PNPM_HOME/bin:$PATH"
|
||||
RUN corepack enable
|
||||
|
||||
FROM base AS builder
|
||||
@@ -44,4 +44,4 @@ WORKDIR /app/apps/chat
|
||||
|
||||
EXPOSE 8000
|
||||
|
||||
ENTRYPOINT ["node", "dist/index.js"]
|
||||
ENTRYPOINT ["node", "dist/index.js"]
|
||||
|
||||
@@ -10,15 +10,16 @@
|
||||
"@hctv/auth": "workspace:*",
|
||||
"@hctv/db": "workspace:*",
|
||||
"@hctv/hono-ws": "workspace:*",
|
||||
"@hono/node-server": "^1.14.0",
|
||||
"@hono/node-ws": "^1.1.0",
|
||||
"@leeoniya/ufuzzy": "^1.0.18",
|
||||
"@hono/node-server": "^2.0.1",
|
||||
"@hono/node-ws": "^1.3.1",
|
||||
"@leeoniya/ufuzzy": "^1.0.19",
|
||||
"@oslojs/encoding": "^1.1.0",
|
||||
"hono": "^4.7.5"
|
||||
"hono": "^4.12.16",
|
||||
"prom-client": "^15.1.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.11.17",
|
||||
"tsx": "^4.7.1",
|
||||
"typescript": "^5.8.2"
|
||||
"@types/node": "^25.6.0",
|
||||
"tsx": "^4.21.0",
|
||||
"typescript": "^6.0.3"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,43 @@
|
||||
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 { 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 = 100;
|
||||
@@ -16,6 +46,35 @@ 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,
|
||||
@@ -182,6 +241,14 @@ async function broadcastRestrictionStateToUser(
|
||||
});
|
||||
}
|
||||
|
||||
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,
|
||||
@@ -189,12 +256,7 @@ async function isRateLimited(
|
||||
windowSeconds: number
|
||||
): Promise<boolean> {
|
||||
const key = `chat:ratelimit:${channelId}:${userId}`;
|
||||
const currentCount = await redis.incr(key);
|
||||
|
||||
if (currentCount === 1) {
|
||||
await redis.expire(key, windowSeconds);
|
||||
}
|
||||
|
||||
const currentCount = (await redis.eval(RATE_LIMIT_LUA, 1, key, String(windowSeconds))) as number;
|
||||
return currentCount > count;
|
||||
}
|
||||
|
||||
@@ -218,46 +280,72 @@ async function logModerationEvent(payload: {
|
||||
});
|
||||
}
|
||||
|
||||
async function deleteMessageFromHistory(targetUsername: string, msgId: string): Promise<boolean> {
|
||||
async function deleteMessageFromHistory(
|
||||
targetUsername: string,
|
||||
msgId: string
|
||||
): Promise<{ deleted: boolean; messageContent?: string }> {
|
||||
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 };
|
||||
const parsed = JSON.parse(entry) as { msgId?: string; message?: string };
|
||||
if (parsed.msgId === msgId) {
|
||||
await redis.zrem(channelKey, entry);
|
||||
return true;
|
||||
return {
|
||||
deleted: true,
|
||||
messageContent:
|
||||
typeof parsed.message === 'string' && parsed.message.length > 0
|
||||
? parsed.message
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
return { deleted: 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_PASSWORD! })
|
||||
);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -284,6 +372,7 @@ app.get(
|
||||
});
|
||||
|
||||
if (botAccount) {
|
||||
authMethod = 'bot_api_key';
|
||||
chatUser = {
|
||||
id: botAccount.botAccount.id,
|
||||
username: botAccount.botAccount.slug,
|
||||
@@ -307,6 +396,7 @@ app.get(
|
||||
if (session.user) {
|
||||
const userChannel = await getPersonalChannel(session.user.id);
|
||||
if (userChannel) {
|
||||
authMethod = 'session';
|
||||
chatUser = {
|
||||
id: session.user.id,
|
||||
username: userChannel.name,
|
||||
@@ -329,16 +419,21 @@ 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: {
|
||||
@@ -363,6 +458,7 @@ app.get(
|
||||
});
|
||||
|
||||
if (!channel) {
|
||||
recordChatConnectionRejected(authMethod, 'channel_not_found');
|
||||
ws.close();
|
||||
return;
|
||||
}
|
||||
@@ -391,14 +487,15 @@ app.get(
|
||||
|
||||
chatUser = {
|
||||
...chatUser,
|
||||
isPlatformAdmin: Boolean(moderatorUser?.isAdmin),
|
||||
isPlatformAdmin: chatUser.isBot ? false : Boolean(moderatorUser?.isAdmin),
|
||||
channelRole,
|
||||
};
|
||||
}
|
||||
|
||||
const isModerator = Boolean(
|
||||
chatUser &&
|
||||
(chatUser.channelRole === 'owner' ||
|
||||
(chatUser.isPlatformAdmin ||
|
||||
chatUser.channelRole === 'owner' ||
|
||||
chatUser.channelRole === 'manager' ||
|
||||
chatUser.channelRole === 'chatModerator' ||
|
||||
chatUser.channelRole === 'botModerator')
|
||||
@@ -415,6 +512,7 @@ app.get(
|
||||
socket.personalChannel = personalChannel;
|
||||
socket.viewerId = randomString(10);
|
||||
socket.isModerator = isModerator;
|
||||
socket.excludeFromViewerCount = Boolean(dbGrant);
|
||||
|
||||
socketState.targetUsername = username;
|
||||
socketState.channelId = channel.id;
|
||||
@@ -422,6 +520,21 @@ app.get(
|
||||
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({
|
||||
@@ -451,6 +564,7 @@ app.get(
|
||||
const messages = await redis.zrange(channelKey, 0, MESSAGE_HISTORY_SIZE - 1);
|
||||
|
||||
if (messages.length > 0) {
|
||||
recordHistoryMessagesLoaded(username, messages.length);
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: 'history',
|
||||
@@ -458,6 +572,7 @@ app.get(
|
||||
})
|
||||
);
|
||||
}
|
||||
setChannelHistorySize(username, messages.length);
|
||||
},
|
||||
async onClose(evt, ws) {
|
||||
const socket = ws as unknown as ChatSocket;
|
||||
@@ -465,6 +580,14 @@ app.get(
|
||||
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: socketState.targetUsername,
|
||||
@@ -476,68 +599,44 @@ app.get(
|
||||
|
||||
if (!streamInfo) return;
|
||||
|
||||
await redis.del(`viewer:${socketState.targetUsername}:${socketState.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 socket = ws as unknown as ChatSocket;
|
||||
const socketState = resolveSocketState(socket);
|
||||
const msg = JSON.parse(evt.data.toString());
|
||||
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:${socketState.targetUsername}:${socketState.viewerId}`,
|
||||
30,
|
||||
'1'
|
||||
);
|
||||
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') {
|
||||
if (
|
||||
!socketState.isModerator ||
|
||||
!socketState.chatUser ||
|
||||
!socketState.targetUsername ||
|
||||
!socketState.channelId
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const msgId = typeof msg.msgId === 'string' ? msg.msgId : '';
|
||||
if (!msgId) {
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: 'moderationError',
|
||||
code: 'INVALID_REQUEST',
|
||||
message: 'Invalid message id.',
|
||||
})
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const deleted = await deleteMessageFromHistory(socketState.targetUsername, msgId);
|
||||
if (!deleted) {
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: 'moderationError',
|
||||
code: 'NOT_FOUND',
|
||||
message: 'Message not found.',
|
||||
})
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
await logModerationEvent({
|
||||
action: ChatModerationAction.MESSAGE_DELETED,
|
||||
channelId: socketState.channelId,
|
||||
moderatorId: socketState.chatUser.moderatorUserId,
|
||||
reason: 'Message deleted by moderator',
|
||||
details: { msgId },
|
||||
await handleDeleteMessageCommand(socket, socketState, msg as ChatModerationCommand, {
|
||||
deleteMessageFromHistory,
|
||||
logModerationEvent,
|
||||
broadcastToChannel,
|
||||
});
|
||||
|
||||
broadcastToChannel(socketState.targetUsername, socket, { type: 'messageDeleted', msgId });
|
||||
|
||||
outcome = 'moderation';
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -547,159 +646,12 @@ app.get(
|
||||
msg.type === 'mod:unbanUser' ||
|
||||
msg.type === 'mod:liftTimeout'
|
||||
) {
|
||||
if (
|
||||
!socketState.isModerator ||
|
||||
!socketState.chatUser ||
|
||||
!socketState.targetUsername ||
|
||||
!socketState.channelId
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const actingModeratorUserId = socketState.chatUser.moderatorUserId;
|
||||
|
||||
const targetUserId = typeof msg.targetUserId === 'string' ? msg.targetUserId : '';
|
||||
|
||||
if (!targetUserId || targetUserId === actingModeratorUserId) {
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: 'moderationError',
|
||||
code: 'INVALID_TARGET',
|
||||
message: 'Invalid moderation target.',
|
||||
})
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const targetUserRecord = await prisma.user.findUnique({
|
||||
where: { id: targetUserId },
|
||||
select: {
|
||||
isAdmin: true,
|
||||
personalChannel: { select: { name: true } },
|
||||
},
|
||||
await handleUserRestrictionCommand(socket, socketState, msg as ChatModerationCommand, {
|
||||
logModerationEvent,
|
||||
broadcastRestrictionStateToUser,
|
||||
broadcastToChannel,
|
||||
});
|
||||
if (!targetUserRecord) {
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: 'moderationError',
|
||||
code: 'INVALID_TARGET',
|
||||
message: 'Target user no longer exists.',
|
||||
})
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const actingUserRecord = await prisma.user.findUnique({
|
||||
where: { id: actingModeratorUserId },
|
||||
select: { isAdmin: true },
|
||||
});
|
||||
if (
|
||||
process.env.NODE_ENV === 'production' &&
|
||||
targetUserRecord.isAdmin &&
|
||||
!actingUserRecord?.isAdmin
|
||||
) {
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: 'moderationError',
|
||||
code: 'FORBIDDEN',
|
||||
message: 'Platform admins cannot be moderated via chat commands.',
|
||||
})
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const resolvedTargetUsername = targetUserRecord.personalChannel?.name ?? 'that user';
|
||||
|
||||
if (msg.type === 'mod:unbanUser' || msg.type === 'mod:liftTimeout') {
|
||||
await prisma.chatUserBan.deleteMany({
|
||||
where: {
|
||||
channelId: socketState.channelId,
|
||||
userId: targetUserId,
|
||||
},
|
||||
});
|
||||
|
||||
await logModerationEvent({
|
||||
action: ChatModerationAction.USER_UNBANNED,
|
||||
channelId: socketState.channelId,
|
||||
moderatorId: actingModeratorUserId,
|
||||
targetUserId,
|
||||
reason: 'User unbanned in chat',
|
||||
});
|
||||
|
||||
await broadcastRestrictionStateToUser(
|
||||
socketState.targetUsername,
|
||||
targetUserId,
|
||||
socketState.channelId,
|
||||
socket
|
||||
);
|
||||
|
||||
broadcastToChannel(socketState.targetUsername, socket, {
|
||||
type: 'systemMsg',
|
||||
message: `${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: socketState.channelId,
|
||||
userId: targetUserId,
|
||||
},
|
||||
},
|
||||
create: {
|
||||
channelId: socketState.channelId,
|
||||
userId: targetUserId,
|
||||
bannedById: actingModeratorUserId,
|
||||
reason,
|
||||
expiresAt,
|
||||
},
|
||||
update: {
|
||||
bannedById: actingModeratorUserId,
|
||||
reason,
|
||||
expiresAt,
|
||||
},
|
||||
});
|
||||
|
||||
await logModerationEvent({
|
||||
action:
|
||||
msg.type === 'mod:timeoutUser'
|
||||
? ChatModerationAction.USER_TIMEOUT
|
||||
: ChatModerationAction.USER_BANNED,
|
||||
channelId: socketState.channelId,
|
||||
moderatorId: actingModeratorUserId,
|
||||
targetUserId,
|
||||
reason,
|
||||
details: durationSeconds ? { durationSeconds } : undefined,
|
||||
});
|
||||
|
||||
await broadcastRestrictionStateToUser(
|
||||
socketState.targetUsername,
|
||||
targetUserId,
|
||||
socketState.channelId,
|
||||
socket
|
||||
);
|
||||
|
||||
broadcastToChannel(socketState.targetUsername, socket, {
|
||||
type: 'systemMsg',
|
||||
message:
|
||||
msg.type === 'mod:timeoutUser'
|
||||
? `${resolvedTargetUsername} was timed out for ${durationSeconds}s.`
|
||||
: `${resolvedTargetUsername} was banned.`,
|
||||
});
|
||||
|
||||
outcome = 'moderation';
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -726,19 +678,17 @@ app.get(
|
||||
|
||||
const restriction = await getActiveRestriction(channelId, chatUser.id);
|
||||
if (restriction) {
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: 'moderationError',
|
||||
code: restriction.type === 'timeout' ? 'TIMED_OUT' : 'BANNED',
|
||||
message:
|
||||
restriction.type === 'timeout'
|
||||
? 'You are currently timed out in this chat.'
|
||||
: 'You are currently banned from this chat.',
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -751,13 +701,9 @@ app.get(
|
||||
moderationSettings.rateLimitWindowSeconds
|
||||
))
|
||||
) {
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: 'moderationError',
|
||||
code: 'RATE_LIMIT',
|
||||
message: 'You are sending messages too fast.',
|
||||
})
|
||||
);
|
||||
sendModerationError(socket, 'RATE_LIMIT', 'You are sending messages too fast.');
|
||||
recordChatModerationBlock('rate_limit');
|
||||
outcome = 'rate_limited';
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -765,13 +711,9 @@ app.get(
|
||||
const slowModeKey = `chat:slowmode:${channelId}:${chatUser.id}`;
|
||||
const timeRemaining = await redis.ttl(slowModeKey);
|
||||
if (timeRemaining > 0) {
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: 'moderationError',
|
||||
code: 'SLOW_MODE',
|
||||
message: `Slow mode is on. Wait ${timeRemaining}s.`,
|
||||
})
|
||||
);
|
||||
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');
|
||||
@@ -782,13 +724,13 @@ app.get(
|
||||
return;
|
||||
}
|
||||
if (message.length > moderationSettings.maxMessageLength) {
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: 'moderationError',
|
||||
code: 'MESSAGE_TOO_LONG',
|
||||
message: `Message exceeds ${moderationSettings.maxMessageLength} characters.`,
|
||||
})
|
||||
sendModerationError(
|
||||
socket,
|
||||
'MESSAGE_TOO_LONG',
|
||||
`Message exceeds ${moderationSettings.maxMessageLength} characters.`
|
||||
);
|
||||
recordChatModerationBlock('message_too_long');
|
||||
outcome = 'message_too_long';
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -804,13 +746,9 @@ app.get(
|
||||
details: { blockedTerm },
|
||||
});
|
||||
}
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: 'moderationError',
|
||||
code: 'BLOCKED_TERM',
|
||||
message: 'Message blocked by channel moderation.',
|
||||
})
|
||||
);
|
||||
recordChatModerationBlock('blocked_term');
|
||||
sendModerationError(socket, 'BLOCKED_TERM', 'Message blocked by channel moderation.');
|
||||
outcome = 'blocked_term';
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -831,16 +769,30 @@ app.get(
|
||||
};
|
||||
|
||||
const redisStr = JSON.stringify(msgObj);
|
||||
const msgStr = JSON.stringify(msgObj);
|
||||
|
||||
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);
|
||||
|
||||
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> = {};
|
||||
|
||||
@@ -865,11 +817,15 @@ app.get(
|
||||
emojis: emojiMap,
|
||||
})
|
||||
);
|
||||
outcome = 'emoji_lookup';
|
||||
}
|
||||
if (msg.type === 'emojiSearch') {
|
||||
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;
|
||||
@@ -899,6 +855,8 @@ app.get(
|
||||
results: results,
|
||||
})
|
||||
);
|
||||
recordEmojiSearchResults('matched', results.length);
|
||||
outcome = 'emoji_search';
|
||||
} else {
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
@@ -906,10 +864,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 });
|
||||
}
|
||||
},
|
||||
}))
|
||||
@@ -925,53 +889,3 @@ const server = serve(
|
||||
}
|
||||
);
|
||||
injectWebSocket(server);
|
||||
|
||||
interface ChatUser {
|
||||
id: string;
|
||||
username: string;
|
||||
pfpUrl: string;
|
||||
displayName?: string;
|
||||
isBot: boolean;
|
||||
moderatorUserId: string;
|
||||
isPlatformAdmin: boolean;
|
||||
channelRole: 'owner' | 'manager' | 'chatModerator' | 'botModerator' | null;
|
||||
}
|
||||
|
||||
interface ChatModerationSettingsShape {
|
||||
blockedTerms: string[];
|
||||
slowModeSeconds: number;
|
||||
maxMessageLength: number;
|
||||
rateLimitCount: number;
|
||||
rateLimitWindowSeconds: number;
|
||||
}
|
||||
|
||||
interface ChatRestrictionState {
|
||||
type: 'timeout' | 'ban';
|
||||
reason: string;
|
||||
expiresAt: Date | null;
|
||||
}
|
||||
|
||||
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;
|
||||
raw?:
|
||||
| (ModifiedWebSocket & {
|
||||
targetUsername?: string;
|
||||
channelId?: string;
|
||||
chatUser?: ChatUser | null;
|
||||
personalChannel?: any;
|
||||
isModerator?: boolean;
|
||||
})
|
||||
| null;
|
||||
}
|
||||
|
||||
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
@@ -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;
|
||||
};
|
||||
417
apps/chat/src/utils/moderation.ts
Normal file
@@ -0,0 +1,417 @@
|
||||
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<{ deleted: boolean; messageContent?: string }>;
|
||||
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 deletedMessage = await deps.deleteMessageFromHistory(context.targetUsername, msgId);
|
||||
if (!deletedMessage.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,
|
||||
messageContent: deletedMessage.messageContent,
|
||||
},
|
||||
});
|
||||
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.`,
|
||||
});
|
||||
}
|
||||
@@ -10,14 +10,14 @@
|
||||
"astro": "astro"
|
||||
},
|
||||
"dependencies": {
|
||||
"@astrojs/starlight": "^0.35.2",
|
||||
"@catppuccin/starlight": "^1.0.2",
|
||||
"astro": "^5.6.1",
|
||||
"astro-mermaid": "^1.0.4",
|
||||
"mermaid": "^11.10.1",
|
||||
"sharp": "^0.34.2",
|
||||
"@astrojs/starlight": "^0.38.4",
|
||||
"@catppuccin/starlight": "^2.0.1",
|
||||
"astro": "^6.3.3",
|
||||
"astro-mermaid": "^2.0.1",
|
||||
"mermaid": "^11.14.0",
|
||||
"sharp": "^0.34.5",
|
||||
"starlight-typedoc": "^0.21.5",
|
||||
"typedoc": "^0.28.16",
|
||||
"typedoc-plugin-markdown": "^4.9.0"
|
||||
"typedoc": "^0.28.19",
|
||||
"typedoc-plugin-markdown": "^4.11.0"
|
||||
}
|
||||
}
|
||||
|
||||
BIN
apps/docs/public/guides/obs-changing-settings-op.gif
Normal file
|
After Width: | Height: | Size: 8.4 MiB |
BIN
apps/docs/public/guides/obs-open-settings-op.gif
Normal file
|
After Width: | Height: | Size: 6.8 MiB |
BIN
apps/docs/src/assets/hctv-settings.png
Normal file
|
After Width: | Height: | Size: 42 KiB |
BIN
apps/docs/src/assets/lock.png
Normal file
|
After Width: | Height: | Size: 1.3 KiB |
BIN
apps/docs/src/assets/obs-changing-settings-op.gif
Normal file
|
After Width: | Height: | Size: 8.4 MiB |
BIN
apps/docs/src/assets/obs-custom.png
Normal file
|
After Width: | Height: | Size: 14 KiB |
BIN
apps/docs/src/assets/obs-open-settings-op.gif
Normal file
|
After Width: | Height: | Size: 6.8 MiB |
BIN
apps/docs/src/assets/obs.png
Normal file
|
After Width: | Height: | Size: 27 KiB |
@@ -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",
|
||||
|
||||
@@ -3,20 +3,42 @@ title: Development Setup
|
||||
description: Instructions to set up a local development environment for hackclub.tv
|
||||
---
|
||||
|
||||
1. clone repo
|
||||
2. `pnpm install`
|
||||
3. `cp apps/web/.env.example apps/web/.env && cp packages/db/.env.example packages/db/.env`
|
||||
4. `pnpm dev`
|
||||
5. `pnpm db:migrate` (RUN THIS AFTER POPULATING ENV)
|
||||
Follow these steps to run hackclub.tv locally:
|
||||
|
||||
- slack notifier app manifest is as follows:
|
||||
1. Clone the repository.
|
||||
2. Install dependencies:
|
||||
|
||||
```
|
||||
pnpm install
|
||||
```
|
||||
|
||||
3. Create environment files:
|
||||
|
||||
```
|
||||
cp apps/web/.env.example apps/web/.env && cp packages/db/.env.example packages/db/.env
|
||||
```
|
||||
|
||||
4. Fill in the required values in both .env files.
|
||||
5. Start the development servers:
|
||||
|
||||
```
|
||||
pnpm dev
|
||||
```
|
||||
|
||||
6. Run database migrations (after environment variables are set):
|
||||
|
||||
```
|
||||
pnpm db:migrate
|
||||
```
|
||||
|
||||
- Slack notifier app manifest:
|
||||
```
|
||||
display_information:
|
||||
# please change the name to something that can be linked to you if possible
|
||||
# Please change the name to something linked to you.
|
||||
name: hctv notifier dev
|
||||
features:
|
||||
bot_user:
|
||||
# same with this :pray:
|
||||
# Same here.
|
||||
display_name: hctv notifier dev
|
||||
always_online: false
|
||||
oauth_config:
|
||||
|
||||
333
apps/docs/src/content/docs/guides/python-wrapper.mdx
Normal file
@@ -0,0 +1,333 @@
|
||||
---
|
||||
title: Python wrapper
|
||||
description: How to use hctv's unofficial Python wrapper.
|
||||
---
|
||||
|
||||
A Pycord-style Python wrapper for [hackclub.tv](https://hackclub.tv), made by [Christian](https://github.com/christianwell). Build chat bots with decorators and minimal boilerplate.
|
||||
|
||||
Check it out on PyPI: https://pypi.org/project/hctvwrapper/
|
||||
You can take a look at the code [here](https://github.com/christianwell/hctvwrapper)
|
||||
|
||||
```
|
||||
pip install hctvwrapper
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
```python
|
||||
import os
|
||||
from hctvwrapper import Bot
|
||||
|
||||
bot = Bot(command_prefix="!")
|
||||
|
||||
@bot.event
|
||||
async def on_ready(session):
|
||||
print(f"Logged in as {session.viewer.username}")
|
||||
|
||||
@bot.event
|
||||
async def on_message(message):
|
||||
print(f"{message.author.username}: {message.content}")
|
||||
|
||||
@bot.command()
|
||||
async def ping(ctx):
|
||||
await ctx.reply("pong!")
|
||||
|
||||
bot.run(os.environ['BOT_TOKEN'], channel="bot-playground")
|
||||
```
|
||||
|
||||
### Getting a Bot Token
|
||||
|
||||
1. Go to [hackclub.tv](https://hackclub.tv)
|
||||
2. Create a bot account and get your API key (starts with `hctvb_`)
|
||||
3. Set it as an environment variable: `export BOT_TOKEN=hctvb_xxx`
|
||||
|
||||
## Guide
|
||||
|
||||
### Events
|
||||
|
||||
Register event handlers with `@bot.event`. The function name determines which event it handles.
|
||||
|
||||
```python
|
||||
@bot.event
|
||||
async def on_ready(session):
|
||||
"""Fired when the bot connects and receives session info."""
|
||||
print(f"Logged in as {session.viewer.username}")
|
||||
print(f"Can moderate: {session.permissions.can_moderate}")
|
||||
print(f"Max message length: {session.moderation.max_message_length}")
|
||||
|
||||
@bot.event
|
||||
async def on_message(message):
|
||||
"""Fired on every chat message."""
|
||||
print(f"[{message.channel}] {message.author.username}: {message.content}")
|
||||
# message.author.id, .pfp_url, .display_name, .is_bot,
|
||||
# .is_platform_admin, .channel_role
|
||||
# message.msg_id, .timestamp, .type
|
||||
|
||||
@bot.event
|
||||
async def on_history(messages):
|
||||
"""Fired once on connect with up to 100 recent messages."""
|
||||
print(f"Got {len(messages)} historical messages")
|
||||
|
||||
@bot.event
|
||||
async def on_system_message(message):
|
||||
"""Fired on system notifications (bans, unbans, etc.)."""
|
||||
print(f"System: {message.content}")
|
||||
|
||||
@bot.event
|
||||
async def on_message_deleted(event):
|
||||
"""Fired when a message is deleted by a moderator."""
|
||||
print(f"Message {event.msg_id} deleted in {event.channel}")
|
||||
|
||||
@bot.event
|
||||
async def on_chat_access(access, channel):
|
||||
"""Fired when chat permissions change (timeouts, bans)."""
|
||||
print(f"Can send in {channel}: {access.can_send}")
|
||||
if access.restriction:
|
||||
print(f" Restriction: {access.restriction.type}")
|
||||
|
||||
@bot.event
|
||||
async def on_moderation_error(error, channel):
|
||||
"""Fired when a moderation action or message is rejected."""
|
||||
print(f"Error in {channel}: {error.code} — {error.message}")
|
||||
# error.code is one of: FORBIDDEN, RATE_LIMIT, SLOW_MODE,
|
||||
# TIMED_OUT, BANNED, MESSAGE_TOO_LONG, BLOCKED_TERM,
|
||||
# INVALID_TARGET, INVALID_REQUEST, NOT_FOUND
|
||||
```
|
||||
|
||||
### Commands
|
||||
|
||||
Register commands with `@bot.command()`. The bot automatically parses messages starting with the prefix.
|
||||
|
||||
```python
|
||||
bot = Bot(command_prefix="!")
|
||||
|
||||
# Simple command, no arguments
|
||||
@bot.command()
|
||||
async def ping(ctx):
|
||||
await ctx.reply("pong!")
|
||||
|
||||
# Named command with aliases
|
||||
@bot.command(name="say", aliases=["echo", "repeat"])
|
||||
async def say_cmd(ctx, *, text):
|
||||
await ctx.send(text)
|
||||
|
||||
# Positional arguments (split by whitespace)
|
||||
@bot.command()
|
||||
async def greet(ctx, name, greeting="hello"):
|
||||
await ctx.reply(f"{greeting}, {name}!")
|
||||
|
||||
# Keyword-only (rest of message)
|
||||
# Use *, text to capture everything after the command as a single string:
|
||||
@bot.command()
|
||||
async def echo(ctx, *, text):
|
||||
await ctx.reply(text)
|
||||
# !echo hello world foo → text = "hello world foo"
|
||||
```
|
||||
|
||||
> The bot automatically ignores its own messages to prevent loops.
|
||||
|
||||
### Context
|
||||
|
||||
The `ctx` object passed to commands gives you everything you need:
|
||||
|
||||
```python
|
||||
@bot.command()
|
||||
async def info(ctx):
|
||||
ctx.message # the full Message object
|
||||
ctx.author # shortcut to ctx.message.author (Author)
|
||||
ctx.channel # channel name (str)
|
||||
ctx.bot # reference to the Bot
|
||||
|
||||
await ctx.reply("text") # sends "@username text"
|
||||
await ctx.send("text") # sends "text" without mention
|
||||
await ctx.delete() # deletes the triggering message (needs mod perms)
|
||||
```
|
||||
|
||||
### Sending Messages
|
||||
|
||||
```python
|
||||
# Inside a command
|
||||
await ctx.reply("mentioned reply")
|
||||
await ctx.send("plain message")
|
||||
|
||||
# Anywhere (if you have a reference to the bot)
|
||||
await bot.send("hello!", channel="bot-playground")
|
||||
```
|
||||
|
||||
### Multi-Channel
|
||||
|
||||
Connect to multiple channels at once:
|
||||
|
||||
```python
|
||||
bot.run("hctvb_xxx", channels=["channel1", "channel2", "bot-playground"])
|
||||
```
|
||||
|
||||
Messages and commands work across all channels. Use `ctx.channel` or `message.channel` to know which channel a message came from.
|
||||
|
||||
```python
|
||||
@bot.event
|
||||
async def on_message(message):
|
||||
print(f"[{message.channel}] {message.author.username}: {message.content}")
|
||||
|
||||
@bot.command()
|
||||
async def where(ctx):
|
||||
await ctx.reply(f"you're in {ctx.channel}")
|
||||
```
|
||||
|
||||
### Moderation
|
||||
|
||||
Bots with moderation permissions can manage users:
|
||||
|
||||
```python
|
||||
# Timeout a user for 5 minutes (default)
|
||||
await bot.timeout_user("channel", user_id="user123", duration=300, reason="spam")
|
||||
|
||||
# Ban a user
|
||||
await bot.ban_user("channel", user_id="user123", reason="repeated violations")
|
||||
|
||||
# Remove a timeout
|
||||
await bot.lift_timeout("channel", user_id="user123")
|
||||
|
||||
# Unban a user
|
||||
await bot.unban_user("channel", user_id="user123")
|
||||
|
||||
# Delete a specific message
|
||||
await bot.delete_message("channel", msg_id="msg-uuid")
|
||||
```
|
||||
|
||||
### Emojis
|
||||
|
||||
Look up or search emojis from the Slack. Results come back via events.
|
||||
|
||||
```python
|
||||
# Look up emoji URLs
|
||||
await bot.lookup_emojis(["yay", "aga"])
|
||||
|
||||
# Search emojis
|
||||
await bot.search_emojis("yay")
|
||||
|
||||
# Handle results
|
||||
@bot.event
|
||||
async def on_emoji_response(emojis):
|
||||
# emojis = {"yay": "https://...", "aga": "https://..."}
|
||||
print(emojis)
|
||||
|
||||
@bot.event
|
||||
async def on_emoji_search(results):
|
||||
# results = ["yay", "yay-bounce", "yay-spin", ...]
|
||||
print(results)
|
||||
```
|
||||
|
||||
### Async Entry Point
|
||||
|
||||
If you manage your own event loop:
|
||||
|
||||
```python
|
||||
import asyncio
|
||||
|
||||
async def main():
|
||||
bot = Bot(command_prefix="!")
|
||||
|
||||
@bot.event
|
||||
async def on_ready(session):
|
||||
print("Connected!")
|
||||
|
||||
await bot.start("hctvb_xxx", channel="bot-playground")
|
||||
|
||||
asyncio.run(main())
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
### Echo Bot
|
||||
|
||||
```python
|
||||
from hctvwrapper import Bot
|
||||
import os
|
||||
|
||||
bot = Bot(command_prefix="!")
|
||||
|
||||
@bot.event
|
||||
async def on_ready(session):
|
||||
print(f"✅ Logged in as {session.viewer}")
|
||||
|
||||
@bot.command()
|
||||
async def ping(ctx):
|
||||
await ctx.reply("pong! 🏓")
|
||||
|
||||
@bot.command(name="echo", aliases=["say"])
|
||||
async def echo_cmd(ctx, *, text):
|
||||
await ctx.send(text)
|
||||
|
||||
bot.run(os.environ["BOT_TOKEN"], channel="bot-playground")
|
||||
```
|
||||
|
||||
### AI Bot
|
||||
|
||||
```python
|
||||
from hctvwrapper import Bot
|
||||
import aiohttp, os
|
||||
|
||||
bot = Bot(command_prefix="/")
|
||||
|
||||
@bot.command(name="ai")
|
||||
async def ai_cmd(ctx, *, prompt):
|
||||
async with aiohttp.ClientSession() as http:
|
||||
resp = await http.post(
|
||||
"https://ai.hackclub.com/proxy/v1/chat/completions",
|
||||
headers={"Authorization": f"Bearer {os.environ['AI_TOKEN']}"},
|
||||
json={
|
||||
"model": "google/gemini-3-flash-preview",
|
||||
"messages": [{"role": "user", "content": prompt}],
|
||||
},
|
||||
)
|
||||
data = await resp.json()
|
||||
answer = data["choices"][0]["message"]["content"]
|
||||
await ctx.reply(answer)
|
||||
|
||||
bot.run(os.environ["BOT_TOKEN"], channel="bot-playground")
|
||||
```
|
||||
|
||||
### Moderation Bot
|
||||
|
||||
```python
|
||||
from hctvwrapper import Bot
|
||||
import os
|
||||
|
||||
bot = Bot(command_prefix="!")
|
||||
|
||||
@bot.command()
|
||||
async def timeout(ctx, user_id, seconds="300"):
|
||||
await bot.timeout_user(ctx.channel, user_id, duration=int(seconds))
|
||||
await ctx.send(f"⏰ Timed out for {seconds}s")
|
||||
|
||||
@bot.event
|
||||
async def on_moderation_error(error, channel):
|
||||
print(f"⚠️ {error.code}: {error.message}")
|
||||
|
||||
bot.run(os.environ["BOT_TOKEN"], channel="my-channel")
|
||||
```
|
||||
|
||||
## Models Reference
|
||||
|
||||
| Model | Fields |
|
||||
|---|---|
|
||||
| `Message` | `content`, `author`, `channel`, `msg_id`, `timestamp`, `type`, `is_bot` |
|
||||
| `Author` | `id`, `username`, `pfp_url`, `display_name`, `is_bot`, `is_platform_admin`, `channel_role` |
|
||||
| `Session` | `viewer` (Author), `permissions`, `moderation` |
|
||||
| `Permissions` | `can_moderate` |
|
||||
| `ModerationSettings` | `has_blocked_terms`, `slow_mode_seconds`, `max_message_length` |
|
||||
| `SystemMessage` | `type`, `channel`, `content`, `timestamp` |
|
||||
| `ChatAccess` | `can_send`, `restriction` |
|
||||
| `Restriction` | `type` (timeout/ban), `reason`, `expires_at` |
|
||||
| `ModerationError` | `code`, `message`, `restriction` |
|
||||
| `ModerationEvent` | `type`, `msg_id`, `channel` |
|
||||
|
||||
## Requirements
|
||||
|
||||
- Python 3.10+
|
||||
- `websockets` (only dependency)
|
||||
|
||||
## License
|
||||
|
||||
Copyright (c) 2026 Christian Well - [MIT License](https://github.com/christianwell/hctvwrapper/blob/main/LICENSE)
|
||||
@@ -2,14 +2,50 @@
|
||||
title: How to stream
|
||||
description: Get started with OBS and streaming on hackclub.tv
|
||||
---
|
||||
import { Steps } from '@astrojs/starlight/components';
|
||||
import { Aside } from '@astrojs/starlight/components';
|
||||
|
||||
- open obs
|
||||
- open settings
|
||||
- open "Stream"
|
||||
- set service to custom
|
||||
- set url to `srt://localhost:8890?streamid=publish:CHANNEL_NAME:thisusernameislongonpurposesoyoudontaccidentallyleakyourstreamkey:STREAM_KEY&pkt_size=1316`
|
||||
- on the website, click "Regenerate key"
|
||||
- paste the key into your obs "Stream Key"
|
||||
- start streaming!
|
||||
_This guide demonstrates how to stream with hackclub.tv via OBS Studio. For other streaming software, you will need to adapt these steps for your chosen software._
|
||||
|
||||
(screenshots to be added soon)
|
||||
<Steps>
|
||||
1. Open OBS Studio.
|
||||
(_If it is not installed, head to [this webpage](https://obsproject.com/) to download the installer._)
|
||||
|
||||

|
||||
|
||||
2. In OBS, click `File > Settings` in the top navigation bar.
|
||||
|
||||
<img alt="Animated GIF of opening the settings page" src="/guides/obs-open-settings-op.gif" />
|
||||
|
||||
3. In the Settings popup, open `Stream` from the sidebar.
|
||||
|
||||
4. Set `Service` to `Custom...`.
|
||||
|
||||
<img
|
||||
alt="Animated GIF of opening 'Stream' settings and changing to 'Custom'"
|
||||
src="/guides/obs-changing-settings-op.gif"
|
||||
/>
|
||||
|
||||
5. Go to https://hackclub.tv/settings/channel/ in your web browser.
|
||||
|
||||
(_If you are not logged in, you may have to log in again and then try again._)
|
||||
|
||||
6. Under `Stream Settings`, you will find your `Stream Key` and `Stream URL`. Copy the `Stream URL` and paste it into OBS.
|
||||
|
||||

|
||||
|
||||
7. Go back to the website and copy the streaming key and paste it into the `Stream Key` box in OBS.
|
||||
<Aside type="caution">You must keep your stream key secret and never share it with anyone.</Aside>
|
||||
|
||||
<Aside type="tip">
|
||||
You can regenerate your stream key at any time if compromised! Just click the key icon and copy the new key. Remember to update your streaming software with the new key if you do this.
|
||||
</Aside>
|
||||
|
||||

|
||||
|
||||
(_Your OBS settings should now look like this_)
|
||||
|
||||
8. You can now safely apply the changes in OBS and start streaming.
|
||||
</Steps>
|
||||
|
||||
Thanks for using this guide and happy streaming!
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
{
|
||||
"extends": "astro/tsconfigs/strict",
|
||||
"compilerOptions": {
|
||||
"ignoreDeprecations": "6.0"
|
||||
},
|
||||
"include": [".astro/types.d.ts", "**/*"],
|
||||
"exclude": ["dist"]
|
||||
}
|
||||
|
||||
@@ -21,11 +21,14 @@ HCID_REDIRECT_URI=http://localhost:3000/auth/hackclub/callback
|
||||
NEXT_PUBLIC_MEDIAMTX_URL_HQ=http://localhost:8891
|
||||
MEDIAMTX_API_HQ=http://localhost:9997
|
||||
NEXT_PUBLIC_MEDIAMTX_INGEST_ROUTE_HQ=localhost:8890
|
||||
NEXT_PUBLIC_MEDIAMTX_WHIP_ROUTE_HQ=http://localhost:8889
|
||||
|
||||
# commented because we don't have another ingest server as of right now
|
||||
# NEXT_PUBLIC_MEDIAMTX_URL_ASIA=http://localhost:8991
|
||||
# MEDIAMTX_API_ASIA=http://localhost:9999
|
||||
# NEXT_PUBLIC_MEDIAMTX_INGEST_ROUTE_ASIA=localhost:8990
|
||||
# optional EU mirror
|
||||
# NEXT_PUBLIC_MEDIAMTX_URL_ETHANDE=https://hls-eu.example.com
|
||||
# MEDIAMTX_API_ETHANDE=https://mediamtx-api-eu.example.com
|
||||
# NEXT_PUBLIC_MEDIAMTX_INGEST_ROUTE_ETHANDE=ingest-eu.example.com:8890
|
||||
# NEXT_PUBLIC_MEDIAMTX_WHIP_ROUTE_ETHANDE=https://webrtc-eu.example.com
|
||||
|
||||
# idt you should change this
|
||||
MEDIAMTX_PUBLISH_KEY=rjq1xdpCPA4qyt3jge
|
||||
# generate with `openssl rand -base64 20`
|
||||
MEDIAMTX_PUBLISH_KEY=
|
||||
MEDIAMTX_API_KEY=
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
FROM node:22-slim AS base
|
||||
ENV PNPM_HOME="/pnpm"
|
||||
ENV PATH="$PNPM_HOME:$PATH"
|
||||
ENV PATH="$PNPM_HOME/bin:$PATH"
|
||||
RUN corepack enable
|
||||
|
||||
FROM base AS builder
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
"rsc": true,
|
||||
"tsx": true,
|
||||
"tailwind": {
|
||||
"config": "tailwind.config.ts",
|
||||
"config": "tailwind.config.mts",
|
||||
"css": "src/app/globals.css",
|
||||
"baseColor": "slate",
|
||||
"cssVariables": true,
|
||||
@@ -14,4 +14,4 @@
|
||||
"components": "@/components",
|
||||
"utils": "@/lib/utils"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,6 +36,9 @@ const nextConfig = {
|
||||
{
|
||||
hostname: 'eoceqrx2r7.ufs.sh'
|
||||
},
|
||||
{
|
||||
hostname: 'thesvg.org',
|
||||
}
|
||||
],
|
||||
minimumCacheTTL: 120,
|
||||
},
|
||||
|
||||
@@ -17,81 +17,83 @@
|
||||
"dependencies": {
|
||||
"@hctv/auth": "workspace:*",
|
||||
"@hctv/db": "workspace:*",
|
||||
"@hookform/resolvers": "^3.9.1",
|
||||
"@hookform/resolvers": "^5.2.2",
|
||||
"@lucia-auth/adapter-prisma": "^4.0.1",
|
||||
"@node-rs/argon2": "^2.0.2",
|
||||
"@omit/react-confirm-dialog": "^1.2.0",
|
||||
"@omit/react-confirm-dialog": "^2.0.0",
|
||||
"@radix-ui/react-alert-dialog": "^1.1.15",
|
||||
"@radix-ui/react-avatar": "^1.0.4",
|
||||
"@radix-ui/react-checkbox": "^1.1.4",
|
||||
"@radix-ui/react-dialog": "^1.1.5",
|
||||
"@radix-ui/react-dropdown-menu": "^2.1.2",
|
||||
"@radix-ui/react-hover-card": "^1.1.14",
|
||||
"@radix-ui/react-label": "^2.1.1",
|
||||
"@radix-ui/react-popover": "^1.1.5",
|
||||
"@radix-ui/react-select": "^2.1.5",
|
||||
"@radix-ui/react-separator": "^1.1.1",
|
||||
"@radix-ui/react-avatar": "^1.1.11",
|
||||
"@radix-ui/react-checkbox": "^1.3.3",
|
||||
"@radix-ui/react-dialog": "^1.1.15",
|
||||
"@radix-ui/react-dropdown-menu": "^2.1.16",
|
||||
"@radix-ui/react-hover-card": "^1.1.15",
|
||||
"@radix-ui/react-label": "^2.1.8",
|
||||
"@radix-ui/react-popover": "^1.1.15",
|
||||
"@radix-ui/react-select": "^2.2.6",
|
||||
"@radix-ui/react-separator": "^1.1.8",
|
||||
"@radix-ui/react-slot": "^1.2.4",
|
||||
"@radix-ui/react-switch": "^1.1.3",
|
||||
"@radix-ui/react-tabs": "^1.1.12",
|
||||
"@radix-ui/react-tooltip": "^1.2.7",
|
||||
"@scalar/api-reference-react": "^0.7.42",
|
||||
"@sentry/nextjs": "^10",
|
||||
"@slack/web-api": "^7.9.1",
|
||||
"@radix-ui/react-switch": "^1.2.6",
|
||||
"@radix-ui/react-tabs": "^1.1.13",
|
||||
"@radix-ui/react-tooltip": "^1.2.8",
|
||||
"@scalar/api-reference-react": "^0.9.32",
|
||||
"@sentry/nextjs": "^10.51.0",
|
||||
"@slack/web-api": "^7.15.1",
|
||||
"@uidotdev/usehooks": "^2.4.1",
|
||||
"@uploadthing/react": "^7.3.1",
|
||||
"ajv": "^8.17.1",
|
||||
"@uploadthing/react": "^7.3.3",
|
||||
"ajv": "^8.20.0",
|
||||
"arctic": "^3.7.0",
|
||||
"bullmq": "^5.45.2",
|
||||
"cheerio": "^1.0.0",
|
||||
"bullmq": "^5.76.4",
|
||||
"cheerio": "^1.2.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.0",
|
||||
"cmdk": "1.0.0",
|
||||
"clsx": "^2.1.1",
|
||||
"cmdk": "1.1.1",
|
||||
"date-fns": "^4.1.0",
|
||||
"embla-carousel-react": "^8.6.0",
|
||||
"hls-video-element": "^1.5.0",
|
||||
"hls.js": "^1.6.15",
|
||||
"hls-video-element": "^1.5.11",
|
||||
"hls.js": "^1.6.16",
|
||||
"lucia": "^3.2.2",
|
||||
"lucide-react": "^0.473.0",
|
||||
"media-chrome": "^4.8.0",
|
||||
"next": "^16.1.0",
|
||||
"next-themes": "^0.4.4",
|
||||
"node-cron": "^3.0.3",
|
||||
"nuqs": "^2.4.3",
|
||||
"pg": "^8.14.1",
|
||||
"pg-boss": "^10.1.6",
|
||||
"react": "^19.2.3",
|
||||
"react-day-picker": "^9.13.0",
|
||||
"react-dom": "^19.2.3",
|
||||
"react-hook-form": "^7.54.2",
|
||||
"lucide-react": "^1.14.0",
|
||||
"media-chrome": "^4.19.0",
|
||||
"next": "^16.2.6",
|
||||
"next-themes": "^0.4.6",
|
||||
"node-cron": "^4.2.1",
|
||||
"nuqs": "^2.8.9",
|
||||
"pg": "^8.20.0",
|
||||
"pg-boss": "^12.18.1",
|
||||
"prom-client": "^15.1.3",
|
||||
"react": "^19.2.5",
|
||||
"react-day-picker": "^9.14.0",
|
||||
"react-dom": "^19.2.5",
|
||||
"react-hook-form": "^7.74.0",
|
||||
"rehype-raw": "^7.0.0",
|
||||
"rehype-react": "^8.0.0",
|
||||
"rehype-sanitize": "^6.0.0",
|
||||
"remark-parse": "^11.0.0",
|
||||
"remark-rehype": "^11.1.2",
|
||||
"sharp": "^0.34.3",
|
||||
"sonner": "^1.4.41",
|
||||
"swr": "^2.3.0",
|
||||
"tailwind-merge": "^2.2.2",
|
||||
"tailwindcss-animate": "^1.0.7",
|
||||
"sharp": "^0.34.5",
|
||||
"sonner": "^2.0.7",
|
||||
"swr": "^2.4.1",
|
||||
"tailwind-merge": "^3.5.0",
|
||||
"unified": "^11.0.5",
|
||||
"uploadthing": "^7.7.2",
|
||||
"uploadthing": "^7.7.4",
|
||||
"util-utils": "^1.0.3",
|
||||
"valtio": "^2.1.2",
|
||||
"ws": "^8.18.1",
|
||||
"zod": "^3.24.1"
|
||||
"valtio": "^2.3.2",
|
||||
"ws": "^8.20.0",
|
||||
"zod": "^4.4.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20",
|
||||
"@types/node": "^25.6.0",
|
||||
"@types/node-cron": "^3.0.11",
|
||||
"@types/react": "^18",
|
||||
"@types/react-dom": "^18",
|
||||
"@types/ws": "^8.18.0",
|
||||
"eslint": "^8",
|
||||
"eslint-config-next": "15.1.3",
|
||||
"postcss": "^8",
|
||||
"shadcn": "^2.7.0",
|
||||
"tailwindcss": "^3.4.1",
|
||||
"typescript": "^5"
|
||||
"@types/react": "^19.2.14",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@types/ws": "^8.18.1",
|
||||
"@tailwindcss/postcss": "^4.2.4",
|
||||
"eslint": "^10.3.0",
|
||||
"eslint-config-next": "16.2.4",
|
||||
"postcss": "^8.5.13",
|
||||
"shadcn": "^4.6.0",
|
||||
"tailwindcss": "^4.2.4",
|
||||
"tw-animate-css": "^1.4.0",
|
||||
"typescript": "^6.0.3"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/** @type {import('postcss-load-config').Config} */
|
||||
const config = {
|
||||
plugins: {
|
||||
tailwindcss: {},
|
||||
'@tailwindcss/postcss': {},
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>
|
||||
|
Before Width: | Height: | Size: 1.3 KiB |
@@ -1 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 283 64"><path fill="black" d="M141 16c-11 0-19 7-19 18s9 18 20 18c7 0 13-3 16-7l-7-5c-2 3-6 4-9 4-5 0-9-3-10-7h28v-3c0-11-8-18-19-18zm-9 15c1-4 4-7 9-7s8 3 9 7h-18zm117-15c-11 0-19 7-19 18s9 18 20 18c6 0 12-3 16-7l-8-5c-2 3-5 4-8 4-5 0-9-3-11-7h28l1-3c0-11-8-18-19-18zm-10 15c2-4 5-7 10-7s8 3 9 7h-19zm-39 3c0 6 4 10 10 10 4 0 7-2 9-5l8 5c-3 5-9 8-17 8-11 0-19-7-19-18s8-18 19-18c8 0 14 3 17 8l-8 5c-2-3-5-5-9-5-6 0-10 4-10 10zm83-29v46h-9V5h9zM37 0l37 64H0L37 0zm92 5-27 48L74 5h10l18 30 17-30h10zm59 12v10l-3-1c-6 0-10 4-10 10v15h-9V17h9v9c0-5 6-9 13-9z"/></svg>
|
||||
|
Before Width: | Height: | Size: 629 B |
BIN
apps/web/public/web-app-manifest-192x192.png
Normal file
|
After Width: | Height: | Size: 10 KiB |
BIN
apps/web/public/web-app-manifest-512x512.png
Normal file
|
After Width: | Height: | Size: 36 KiB |
@@ -1,8 +1,10 @@
|
||||
import LiveStream from "@/components/app/Livestream/Livestream";
|
||||
import LiveStream from '@/components/app/Livestream/Livestream';
|
||||
import { validateRequest } from '@/lib/auth/validate';
|
||||
import { prisma } from '@hctv/db';
|
||||
|
||||
export default async function Page({ params }: { params: Promise<{ username: string }> }) {
|
||||
const { username } = await params;
|
||||
const { user } = await validateRequest();
|
||||
const streamInfo = await prisma.streamInfo.findUnique({
|
||||
where: { username },
|
||||
include: {
|
||||
@@ -17,23 +19,31 @@ export default async function Page({ params }: { params: Promise<{ username: str
|
||||
return <div>Stream not found</div>;
|
||||
}
|
||||
|
||||
if (streamInfo.channel.restriction) {
|
||||
const isExpired = streamInfo.channel.restriction.expiresAt &&
|
||||
new Date(streamInfo.channel.restriction.expiresAt) < new Date();
|
||||
|
||||
if (!isExpired) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center h-[calc(100vh-64px)] p-4">
|
||||
<h1 className="text-2xl font-bold text-destructive mb-2">Channel Restricted</h1>
|
||||
<p className="text-muted-foreground text-center max-w-md">
|
||||
This channel has been restricted by a moderator and is not currently available for viewing.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const hasActiveRestriction = streamInfo.channel.restriction
|
||||
? !streamInfo.channel.restriction.expiresAt ||
|
||||
new Date(streamInfo.channel.restriction.expiresAt) >= new Date()
|
||||
: false;
|
||||
const canBypassRestriction = Boolean(user?.isAdmin);
|
||||
|
||||
if (hasActiveRestriction && !canBypassRestriction) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center h-[calc(100vh-64px)] p-4">
|
||||
<h1 className="text-2xl font-bold text-destructive mb-2">Channel Restricted</h1>
|
||||
<p className="text-muted-foreground text-center max-w-md">
|
||||
This channel has been restricted by a moderator and is not currently available for
|
||||
viewing.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<LiveStream username={username} streamInfo={streamInfo} />
|
||||
<LiveStream
|
||||
username={username}
|
||||
streamInfo={streamInfo}
|
||||
canViewRestrictedStream={canBypassRestriction}
|
||||
initialRestrictionActive={hasActiveRestriction}
|
||||
initialRestrictionExpiresAt={streamInfo.channel.restriction?.expiresAt?.toISOString() ?? null}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -8,11 +8,11 @@ import { Input } from '@/components/ui/input';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Calendar } from '@/components/ui/calendar';
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import {
|
||||
Users,
|
||||
Tv,
|
||||
Ban,
|
||||
LogOut,
|
||||
ShieldOff,
|
||||
Search,
|
||||
CalendarIcon,
|
||||
@@ -33,6 +33,7 @@ import {
|
||||
Activity,
|
||||
Hash,
|
||||
ShieldAlert,
|
||||
Settings,
|
||||
} from 'lucide-react';
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
|
||||
import {
|
||||
@@ -43,15 +44,14 @@ import {
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { useConfirm } from '@omit/react-confirm-dialog';
|
||||
import { toast } from 'sonner';
|
||||
import type { User } from '@hctv/db';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { parseAsString, useQueryState } from 'nuqs';
|
||||
import { useRouter } from 'next/navigation';
|
||||
|
||||
// ─── Constants ───────────────────────────────────────────────────────────────
|
||||
|
||||
const ADMIN_TABS = ['users', 'channels', 'audit', 'reports'] as const;
|
||||
const ADMIN_TABS = ['users', 'channels', 'audit', 'reports', 'settings'] as const;
|
||||
type AdminTab = (typeof ADMIN_TABS)[number];
|
||||
|
||||
const NAV_ITEMS: Array<{ id: AdminTab; label: string; icon: React.ReactNode }> = [
|
||||
@@ -59,9 +59,9 @@ const NAV_ITEMS: Array<{ id: AdminTab; label: string; icon: React.ReactNode }> =
|
||||
{ id: 'channels', label: 'Channels', icon: <Tv className="h-4 w-4" /> },
|
||||
{ id: 'audit', label: 'Audit Log', icon: <ClipboardList className="h-4 w-4" /> },
|
||||
{ id: 'reports', label: 'Reports', icon: <Flag className="h-4 w-4" /> },
|
||||
{ id: 'settings', label: 'Settings', icon: <Settings className="h-4 w-4" /> },
|
||||
];
|
||||
|
||||
// Audit action colour coding
|
||||
const AUDIT_SOURCE_DOT: Record<string, string> = {
|
||||
platform: 'bg-primary',
|
||||
chat: 'bg-amber-500',
|
||||
@@ -81,6 +81,8 @@ const AUDIT_ACTION_COLOR: Record<string, string> = {
|
||||
TIMEOUT_USER: 'text-amber-500',
|
||||
BAN_FROM_CHAT: 'text-destructive',
|
||||
LIFT_CHAT_BAN: 'text-green-600 dark:text-green-400',
|
||||
BYPASS_VERIFICATION_ENABLED: 'text-green-600 dark:text-green-400',
|
||||
BYPASS_VERIFICATION_DISABLED: 'text-amber-500',
|
||||
};
|
||||
|
||||
const REPORT_STATUS_CONFIG = {
|
||||
@@ -116,8 +118,6 @@ const LAST_ACTION_LABELS: Record<string, string> = {
|
||||
UNBAN_PLATFORM: 'Platform unbanned',
|
||||
};
|
||||
|
||||
// ─── Small helpers ───────────────────────────────────────────────────────────
|
||||
|
||||
function SectionHeader({
|
||||
icon,
|
||||
title,
|
||||
@@ -166,8 +166,6 @@ function LoadingRows({ cols }: { cols: number }) {
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Date/time picker shared component ──────────────────────────────────────
|
||||
|
||||
function DateTimePicker({
|
||||
value,
|
||||
onChange,
|
||||
@@ -232,9 +230,8 @@ function DateTimePicker({
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Main component ──────────────────────────────────────────────────────────
|
||||
|
||||
export default function AdminPanelClient({ currentUser }: AdminPanelClientProps) {
|
||||
const confirm = useConfirm();
|
||||
const router = useRouter();
|
||||
const [tabParam, setTabParam] = useQueryState('tab', parseAsString.withDefault('users'));
|
||||
const [reportIdParam, setReportIdParam] = useQueryState('reportId');
|
||||
@@ -247,6 +244,7 @@ export default function AdminPanelClient({ currentUser }: AdminPanelClientProps)
|
||||
const [channelsLoading, setChannelsLoading] = useState(false);
|
||||
const [auditLoading, setAuditLoading] = useState(false);
|
||||
const [reportsLoading, setReportsLoading] = useState(false);
|
||||
const [loggingOutOthers, setLoggingOutOthers] = useState(false);
|
||||
const [auditLogs, setAuditLogs] = useState<AuditLog[]>([]);
|
||||
const [reports, setReports] = useState<ChatReport[]>([]);
|
||||
const [highlightReportId, setHighlightReportId] = useState<string | null>(null);
|
||||
@@ -258,8 +256,6 @@ export default function AdminPanelClient({ currentUser }: AdminPanelClientProps)
|
||||
const [reason, setReason] = useState('');
|
||||
const [expiresAt, setExpiresAt] = useState<Date | undefined>(undefined);
|
||||
|
||||
// ── Data fetchers ──────────────────────────────────────────────────────────
|
||||
|
||||
const fetchUsers = useCallback(async (search: string) => {
|
||||
setUsersLoading(true);
|
||||
try {
|
||||
@@ -313,8 +309,6 @@ export default function AdminPanelClient({ currentUser }: AdminPanelClientProps)
|
||||
}
|
||||
}, []);
|
||||
|
||||
// ── Effects ────────────────────────────────────────────────────────────────
|
||||
|
||||
useEffect(() => {
|
||||
if (tabParam && ADMIN_TABS.includes(tabParam as AdminTab)) {
|
||||
setActiveTab(tabParam as AdminTab);
|
||||
@@ -353,8 +347,6 @@ export default function AdminPanelClient({ currentUser }: AdminPanelClientProps)
|
||||
return () => clearTimeout(timer);
|
||||
}, [channelSearch, fetchChannels]);
|
||||
|
||||
// ── Actions ────────────────────────────────────────────────────────────────
|
||||
|
||||
const resetDialogState = () => {
|
||||
setReason('');
|
||||
setExpiresAt(undefined);
|
||||
@@ -498,12 +490,66 @@ export default function AdminPanelClient({ currentUser }: AdminPanelClientProps)
|
||||
}
|
||||
};
|
||||
|
||||
// ── Derived stats ─────────────────────────────────────────────────────────
|
||||
const handleToggleBypassVerification = async (userId: string) => {
|
||||
try {
|
||||
const res = await fetch('/api/admin/users', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ userId, action: 'toggle_bypass_verification' }),
|
||||
});
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
toast.success(data.message);
|
||||
fetchUsers(userSearch);
|
||||
fetchAuditLogs();
|
||||
} else {
|
||||
toast.error((await res.text()) || 'Failed to toggle bypass verification');
|
||||
}
|
||||
} catch {
|
||||
toast.error('Failed to toggle bypass verification');
|
||||
}
|
||||
};
|
||||
|
||||
const handleLogoutOthers = async () => {
|
||||
const confirmed = await confirm({
|
||||
title: 'Log Out Everyone Else',
|
||||
description:
|
||||
'This will immediately sign out every other active session on hackclub.tv and keep only your current session active.',
|
||||
confirmText: 'Log Out Others',
|
||||
cancelText: 'Cancel',
|
||||
});
|
||||
|
||||
if (!confirmed) return;
|
||||
|
||||
setLoggingOutOthers(true);
|
||||
try {
|
||||
const res = await fetch('/api/admin/users', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ action: 'logout_others' }),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
toast.error((await res.text()) || 'Failed to log out other sessions');
|
||||
return;
|
||||
}
|
||||
|
||||
const data = (await res.json()) as { invalidatedSessions: number };
|
||||
toast.success(
|
||||
data.invalidatedSessions > 0
|
||||
? `Logged out ${data.invalidatedSessions} other session${data.invalidatedSessions === 1 ? '' : 's'}`
|
||||
: 'No other active sessions were found'
|
||||
);
|
||||
router.refresh();
|
||||
} catch {
|
||||
toast.error('Failed to log out other sessions');
|
||||
} finally {
|
||||
setLoggingOutOthers(false);
|
||||
}
|
||||
};
|
||||
|
||||
const openReports = reports.filter((r) => r.status === 'OPEN').length;
|
||||
|
||||
// ── Tab switch helper ─────────────────────────────────────────────────────
|
||||
|
||||
const switchTab = async (tab: AdminTab) => {
|
||||
setActiveTab(tab);
|
||||
await setTabParam(tab);
|
||||
@@ -513,8 +559,6 @@ export default function AdminPanelClient({ currentUser }: AdminPanelClientProps)
|
||||
}
|
||||
};
|
||||
|
||||
// ── Render ────────────────────────────────────────────────────────────────
|
||||
|
||||
return (
|
||||
<div className="min-h-screen">
|
||||
{/* ── Page header ─────────────────────────────────────────────────── */}
|
||||
@@ -534,24 +578,25 @@ export default function AdminPanelClient({ currentUser }: AdminPanelClientProps)
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Quick stats */}
|
||||
<div className="hidden sm:flex items-center gap-1 rounded-full border border-border bg-background px-3 py-1.5">
|
||||
<StatPill icon={<Users className="h-3 w-3" />} label={`${users.length} users`} />
|
||||
<span className="text-border mx-1">|</span>
|
||||
<StatPill
|
||||
icon={<Activity className="h-3 w-3" />}
|
||||
label={`${auditLogs.length} events`}
|
||||
/>
|
||||
{openReports > 0 && (
|
||||
<>
|
||||
<span className="text-border mx-1">|</span>
|
||||
<StatPill
|
||||
icon={<Flag className="h-3 w-3" />}
|
||||
label={`${openReports} open`}
|
||||
className="text-destructive"
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
<div className="flex flex-col items-end gap-3">
|
||||
<div className="hidden sm:flex items-center gap-1 rounded-full border border-border bg-background px-3 py-1.5">
|
||||
<StatPill icon={<Users className="h-3 w-3" />} label={`${users.length} users`} />
|
||||
<span className="text-border mx-1">|</span>
|
||||
<StatPill
|
||||
icon={<Activity className="h-3 w-3" />}
|
||||
label={`${auditLogs.length} events`}
|
||||
/>
|
||||
{openReports > 0 && (
|
||||
<>
|
||||
<span className="text-border mx-1">|</span>
|
||||
<StatPill
|
||||
icon={<Flag className="h-3 w-3" />}
|
||||
label={`${openReports} open`}
|
||||
className="text-destructive"
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -974,6 +1019,20 @@ export default function AdminPanelClient({ currentUser }: AdminPanelClientProps)
|
||||
{log.reason}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{log.deletedMessageContent && (
|
||||
<div className="mt-2 flex items-start gap-2 rounded-md border border-border bg-muted/40 px-3 py-2">
|
||||
<MessageSquare className="mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground" />
|
||||
<div className="min-w-0">
|
||||
<p className="text-[10px] font-medium uppercase tracking-wide text-muted-foreground">
|
||||
Deleted message
|
||||
</p>
|
||||
<p className="mt-1 break-words text-xs leading-relaxed text-foreground/90">
|
||||
{log.deletedMessageContent}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
@@ -1140,6 +1199,177 @@ export default function AdminPanelClient({ currentUser }: AdminPanelClientProps)
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{activeTab === 'settings' && (
|
||||
<div>
|
||||
<SectionHeader
|
||||
icon={<Settings className="h-4 w-4" />}
|
||||
title="Platform Settings"
|
||||
description="Manage verification bypass and platform configuration."
|
||||
/>
|
||||
|
||||
<div className="space-y-5">
|
||||
<div className="rounded-xl border-2 border-primary/20 bg-gradient-to-br from-primary/5 via-background to-background p-5 shadow-lg">
|
||||
<div className="mb-5 flex items-start gap-3">
|
||||
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-primary/10 ring-2 ring-primary/20">
|
||||
<ShieldAlert className="h-5 w-5 text-primary" />
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<h3 className="text-base font-bold tracking-tight">
|
||||
ID Verification Bypass
|
||||
</h3>
|
||||
<p className="mt-0.5 text-xs text-muted-foreground leading-relaxed">
|
||||
Allow existing users to bypass HCA verification and let them access the
|
||||
platform.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="relative mb-4">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search by email or username to manage bypass…"
|
||||
value={userSearch}
|
||||
onChange={(e) => setUserSearch(e.target.value)}
|
||||
className="pl-10 h-9 bg-background/50 border-2 focus:border-primary/50 transition-colors"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{usersLoading ? (
|
||||
<LoadingRows cols={1} />
|
||||
) : !userSearch ? (
|
||||
<div className="rounded-lg border-2 border-dashed border-primary/20 bg-primary/5 p-6 text-center">
|
||||
<div className="mx-auto w-fit rounded-full bg-primary/10 p-3 mb-2">
|
||||
<Search className="h-5 w-5 text-primary" />
|
||||
</div>
|
||||
<p className="text-sm font-medium text-foreground mb-1">
|
||||
Start searching to manage users
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Type an email or username above to find users and toggle their
|
||||
verification bypass
|
||||
</p>
|
||||
</div>
|
||||
) : users.length === 0 ? (
|
||||
<div className="rounded-lg border-2 border-dashed border-border bg-muted/30 p-6 text-center">
|
||||
<XCircle className="mx-auto h-8 w-8 text-muted-foreground/50 mb-2" />
|
||||
<p className="text-sm font-medium text-foreground mb-1">No users found</p>
|
||||
<p className="text-xs text-muted-foreground">Try a different search term</p>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="space-y-2 mb-3">
|
||||
{users.map((user) => (
|
||||
<div
|
||||
key={user.id}
|
||||
className={cn(
|
||||
'group relative overflow-hidden rounded-lg border-2 bg-card transition-all duration-200',
|
||||
user.bypassVerification
|
||||
? 'border-primary/40 bg-primary/5 hover:border-primary/50 hover:shadow-md hover:shadow-primary/5'
|
||||
: 'border-border hover:border-primary/30 hover:shadow-sm'
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-3 px-3 py-2.5">
|
||||
<Avatar className="h-9 w-9 shrink-0 ring-2 ring-background">
|
||||
<AvatarImage src={user.pfpUrl} />
|
||||
<AvatarFallback className="text-xs font-semibold">
|
||||
{user.personalChannel?.name?.[0]?.toUpperCase() ?? 'U'}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-1.5 flex-wrap mb-0.5">
|
||||
<span className="font-semibold text-sm">
|
||||
{user.personalChannel?.name ?? user.slack_id}
|
||||
</span>
|
||||
{user.isAdmin && (
|
||||
<span className="inline-flex items-center gap-0.5 text-[10px] font-bold px-1.5 py-0.5 rounded-full bg-primary/10 text-primary border border-primary/30">
|
||||
<Shield className="h-2.5 w-2.5" />
|
||||
Admin
|
||||
</span>
|
||||
)}
|
||||
{user.bypassVerification && (
|
||||
<span className="inline-flex items-center gap-0.5 text-[10px] font-bold px-1.5 py-0.5 rounded-full bg-primary/10 text-primary border border-primary/30 animate-in fade-in zoom-in duration-200">
|
||||
<CheckCircle2 className="h-2.5 w-2.5" />
|
||||
Bypass Active
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground truncate">
|
||||
{user.email ?? 'No email'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
variant={user.bypassVerification ? 'outline' : 'default'}
|
||||
size="sm"
|
||||
onClick={() => handleToggleBypassVerification(user.id)}
|
||||
className={cn(
|
||||
'h-7 text-xs gap-1 shrink-0 font-semibold transition-all duration-200',
|
||||
user.bypassVerification &&
|
||||
'border-primary/30 hover:bg-primary/10 hover:border-primary/50'
|
||||
)}
|
||||
>
|
||||
{user.bypassVerification ? (
|
||||
<>
|
||||
<XCircle className="h-3 w-3" />
|
||||
Disable
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<CheckCircle2 className="h-3 w-3" />
|
||||
Enable
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{user.bypassVerification && (
|
||||
<div className="absolute inset-x-0 bottom-0 h-0.5 bg-gradient-to-r from-primary/0 via-primary/50 to-primary/0" />
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="rounded-xl border-2 border-border bg-card p-4 shadow-lg">
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-muted ring-2 ring-border">
|
||||
<LogOut className="h-5 w-5 text-foreground" />
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<h3 className="text-base font-bold tracking-tight">Session Management</h3>
|
||||
<p className="mt-0.5 text-xs text-muted-foreground mb-3 leading-relaxed">
|
||||
Force logout all other sessions except your current one. Useful for
|
||||
security maintenance.
|
||||
</p>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleLogoutOthers}
|
||||
disabled={loggingOutOthers}
|
||||
className="h-7 gap-1.5 font-semibold text-xs"
|
||||
>
|
||||
{loggingOutOthers ? (
|
||||
<>
|
||||
<RefreshCw className="h-3.5 w-3.5 animate-spin" />
|
||||
Logging out...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<LogOut className="h-3.5 w-3.5" />
|
||||
Logout All Other Sessions
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1277,6 +1507,7 @@ interface UserWithBan {
|
||||
email: string | null;
|
||||
pfpUrl: string;
|
||||
isAdmin: boolean;
|
||||
bypassVerification: boolean;
|
||||
ban: {
|
||||
id: string;
|
||||
reason: string;
|
||||
@@ -1321,6 +1552,7 @@ interface AuditLog {
|
||||
reason: string | null;
|
||||
details?: unknown;
|
||||
channelName?: string;
|
||||
deletedMessageContent?: string | null;
|
||||
}
|
||||
|
||||
interface ChatReport {
|
||||
|
||||
@@ -2,6 +2,15 @@ import { validateRequest } from '@/lib/auth/validate';
|
||||
import { prisma } from '@hctv/db';
|
||||
import { NextRequest } from 'next/server';
|
||||
|
||||
function getDeletedMessageContent(details: unknown): string | null {
|
||||
if (!details || typeof details !== 'object' || Array.isArray(details)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const messageContent = (details as { messageContent?: unknown }).messageContent;
|
||||
return typeof messageContent === 'string' && messageContent.length > 0 ? messageContent : null;
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const { user } = await validateRequest();
|
||||
if (!user?.isAdmin) {
|
||||
@@ -136,6 +145,7 @@ export async function GET(request: NextRequest) {
|
||||
(log.targetUserId ? (targetUserMap.get(log.targetUserId) ?? log.targetUserId) : null),
|
||||
reason: log.reason,
|
||||
details: log.details,
|
||||
deletedMessageContent: getDeletedMessageContent(log.details),
|
||||
actorMeta: {
|
||||
isPlatformAdmin: log.actor.isAdmin,
|
||||
isChannelModerator: channelModSet.has(log.actorId),
|
||||
@@ -157,6 +167,7 @@ export async function GET(request: NextRequest) {
|
||||
target: log.targetUser?.personalChannel?.name ?? log.channel.name,
|
||||
reason: log.reason,
|
||||
details: log.details,
|
||||
deletedMessageContent: getDeletedMessageContent(log.details),
|
||||
channelName: log.channel.name,
|
||||
actorMeta: {
|
||||
isPlatformAdmin: log.moderator.isAdmin,
|
||||
|
||||
@@ -292,6 +292,7 @@ export async function POST(request: NextRequest) {
|
||||
details: {
|
||||
reportId,
|
||||
msgId: report.reportedMessageId,
|
||||
messageContent: report.reportedMessage,
|
||||
} as any,
|
||||
},
|
||||
});
|
||||
@@ -307,6 +308,7 @@ export async function POST(request: NextRequest) {
|
||||
reportId,
|
||||
enforcement: 'DELETE_REPORTED_MESSAGE',
|
||||
msgId: report.reportedMessageId,
|
||||
messageContent: report.reportedMessage,
|
||||
} as any,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { validateRequest } from '@/lib/auth/validate';
|
||||
import { AdminAuditAction, prisma } from '@hctv/db';
|
||||
import { AdminAuditAction, getRedisConnection, prisma } from '@hctv/db';
|
||||
import { NextRequest } from 'next/server';
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
@@ -22,7 +22,13 @@ export async function GET(request: NextRequest) {
|
||||
hasOnboarded: true,
|
||||
}
|
||||
: undefined,
|
||||
include: {
|
||||
select: {
|
||||
id: true,
|
||||
slack_id: true,
|
||||
email: true,
|
||||
pfpUrl: true,
|
||||
isAdmin: true,
|
||||
bypassVerification: true,
|
||||
ban: true,
|
||||
personalChannel: { select: { name: true } },
|
||||
},
|
||||
@@ -32,14 +38,14 @@ export async function GET(request: NextRequest) {
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const { user } = await validateRequest();
|
||||
const { user, session } = await validateRequest();
|
||||
if (!user?.isAdmin) {
|
||||
return new Response('Forbidden', { status: 403 });
|
||||
}
|
||||
|
||||
let body: {
|
||||
userId: string;
|
||||
action: 'ban' | 'unban' | 'promote' | 'demote';
|
||||
userId?: string;
|
||||
action: 'ban' | 'unban' | 'promote' | 'demote' | 'logout_others' | 'toggle_bypass_verification';
|
||||
reason?: string;
|
||||
expiresAt?: string;
|
||||
};
|
||||
@@ -52,6 +58,42 @@ export async function POST(request: NextRequest) {
|
||||
|
||||
const { userId, action, reason, expiresAt } = body;
|
||||
|
||||
if (action === 'logout_others') {
|
||||
if (!session) {
|
||||
return new Response('No active session found', { status: 400 });
|
||||
}
|
||||
|
||||
const sessionsToDelete = await prisma.session.findMany({
|
||||
where: {
|
||||
id: {
|
||||
not: session.id,
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (sessionsToDelete.length > 0) {
|
||||
const redis = getRedisConnection();
|
||||
await prisma.session.deleteMany({
|
||||
where: {
|
||||
id: {
|
||||
in: sessionsToDelete.map((existingSession) => existingSession.id),
|
||||
},
|
||||
},
|
||||
});
|
||||
await redis.unlink(
|
||||
...sessionsToDelete.map((existingSession) => `sessions:${existingSession.id}`)
|
||||
);
|
||||
}
|
||||
|
||||
return Response.json({
|
||||
success: true,
|
||||
invalidatedSessions: sessionsToDelete.length,
|
||||
});
|
||||
}
|
||||
|
||||
if (!userId || !action) {
|
||||
return new Response('Missing required fields', { status: 400 });
|
||||
}
|
||||
@@ -174,5 +216,32 @@ export async function POST(request: NextRequest) {
|
||||
return Response.json({ success: true, message: 'User demoted from admin' });
|
||||
}
|
||||
|
||||
if (action === 'toggle_bypass_verification') {
|
||||
const newBypassStatus = !targetUser.bypassVerification;
|
||||
|
||||
await prisma.user.update({
|
||||
where: { id: userId },
|
||||
data: { bypassVerification: newBypassStatus },
|
||||
});
|
||||
|
||||
await prisma.adminAuditLog.create({
|
||||
data: {
|
||||
action: newBypassStatus
|
||||
? AdminAuditAction.BYPASS_VERIFICATION_ENABLED
|
||||
: AdminAuditAction.BYPASS_VERIFICATION_DISABLED,
|
||||
actorId: user.id,
|
||||
targetUserId: userId,
|
||||
},
|
||||
});
|
||||
|
||||
return Response.json({
|
||||
success: true,
|
||||
message: newBypassStatus
|
||||
? 'Email verification bypass enabled'
|
||||
: 'Email verification bypass disabled',
|
||||
bypassVerification: newBypassStatus,
|
||||
});
|
||||
}
|
||||
|
||||
return new Response('Invalid action', { status: 400 });
|
||||
}
|
||||
|
||||
@@ -1,29 +1,43 @@
|
||||
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 });
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
console.error('Invalid MediaMTX auth request:', parsed.error.flatten());
|
||||
}
|
||||
|
||||
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, token } = parsed.data;
|
||||
action = parsedAction;
|
||||
protocol = parsedProtocol || 'none';
|
||||
|
||||
if (parsedAction === 'publish' && (parsedProtocol === 'srt' || parsedProtocol === 'webrtc')) {
|
||||
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,49 +52,65 @@ 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') {
|
||||
}
|
||||
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');
|
||||
}
|
||||
if (parsedAction === 'api') {
|
||||
if (password === process.env.MEDIAMTX_API_KEY || token === process.env.MEDIAMTX_API_KEY) {
|
||||
return finish('authorized api', 200, 'authorized_api');
|
||||
}
|
||||
|
||||
return finish('unauthorized api', 401, 'unauthorized_api');
|
||||
}
|
||||
|
||||
return new Response('uhh', { status: 401 });
|
||||
return finish('uhh', 401, 'unauthorized');
|
||||
}
|
||||
|
||||
const emptyableString = z
|
||||
.string()
|
||||
.nullish()
|
||||
.transform((value) => value ?? '');
|
||||
|
||||
const schema = z.object({
|
||||
user: z.string(),
|
||||
password: z.string(),
|
||||
token: z.string(),
|
||||
ip: z.string(),
|
||||
user: emptyableString,
|
||||
password: emptyableString,
|
||||
token: emptyableString,
|
||||
ip: emptyableString,
|
||||
action: z.enum(['publish', 'read', 'playback', 'api', 'metrics', 'pprof']),
|
||||
path: z.string(),
|
||||
protocol: z.enum(['rtsp', 'rtmp', 'hls', 'webrtc', 'srt']),
|
||||
id: z.string().nullable(),
|
||||
query: z.string(),
|
||||
path: emptyableString,
|
||||
protocol: z
|
||||
.union([z.enum(['rtsp', 'rtmp', 'hls', 'webrtc', 'srt']), z.literal('')])
|
||||
.nullish()
|
||||
.transform((value) => value ?? ''),
|
||||
id: z.string().nullable().default(null),
|
||||
query: emptyableString,
|
||||
});
|
||||
|
||||
@@ -1,46 +1,106 @@
|
||||
import { NextRequest } from 'next/server';
|
||||
import { validateRequest } from '@/lib/auth/validate';
|
||||
import { prisma } from '@hctv/db';
|
||||
import { NextRequest } from "next/server";
|
||||
import { regenerateStreamKey } from '@/lib/db/streamKey';
|
||||
import { prisma } from '@hctv/db';
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const channelName = await readChannelNameFromBody(request);
|
||||
|
||||
if (!channelName) {
|
||||
return badRequestResponse();
|
||||
}
|
||||
|
||||
const result = await getAuthorizedChannel(channelName);
|
||||
if ('response' in result) {
|
||||
return result.response;
|
||||
}
|
||||
|
||||
const streamKey = await regenerateStreamKey(result.channel.id, channelName);
|
||||
return Response.json({ key: streamKey.key });
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const channelName = request.nextUrl.searchParams.get('channel');
|
||||
|
||||
if (!isValidChannelName(channelName)) {
|
||||
return badRequestResponse();
|
||||
}
|
||||
|
||||
const result = await getAuthorizedChannel(channelName);
|
||||
if ('response' in result) {
|
||||
return result.response;
|
||||
}
|
||||
|
||||
const streamKey = await prisma.streamKey.findUnique({
|
||||
where: { channelId: result.channel.id },
|
||||
select: { key: true },
|
||||
});
|
||||
|
||||
if (!streamKey) {
|
||||
return new Response('Stream key not found', { status: 404 });
|
||||
}
|
||||
|
||||
return Response.json({ key: streamKey.key });
|
||||
}
|
||||
|
||||
async function getAuthorizedChannel(channelName: string): Promise<AuthorizedChannelResult> {
|
||||
const { user } = await validateRequest();
|
||||
const body = await request.json();
|
||||
const { channel } = body;
|
||||
|
||||
if (!user) {
|
||||
return new Response('Unauthorized', { status: 401 });
|
||||
return { response: unauthorizedResponse() };
|
||||
}
|
||||
|
||||
if (!channel || typeof channel !== 'string') {
|
||||
return new Response('Bad Request', { status: 400 });
|
||||
}
|
||||
|
||||
const channelInfo = await prisma.channel.findUnique({
|
||||
where: { name: channel },
|
||||
include: {
|
||||
owner: true,
|
||||
managers: true
|
||||
}
|
||||
const channel = await prisma.channel.findUnique({
|
||||
where: { name: channelName },
|
||||
select: {
|
||||
id: true,
|
||||
ownerId: true,
|
||||
managers: {
|
||||
where: { id: user.id },
|
||||
select: { id: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!channelInfo) {
|
||||
return new Response('Channel not found', { status: 404 });
|
||||
if (!channel) {
|
||||
return { response: new Response('Channel not found', { status: 404 }) };
|
||||
}
|
||||
|
||||
const isBroadcaster =
|
||||
channelInfo.ownerId === user.id ||
|
||||
channelInfo.managers.some(m => m.id === user.id);
|
||||
const isBroadcaster = channel.ownerId === user.id || channel.managers.length > 0;
|
||||
if (!isBroadcaster) {
|
||||
return new Response('Unauthorized', { status: 401 });
|
||||
return { response: unauthorizedResponse() };
|
||||
}
|
||||
|
||||
const streamKey = await regenerateStreamKey(channelInfo.id, channel);
|
||||
return { channel: { id: channel.id } };
|
||||
}
|
||||
|
||||
return new Response(JSON.stringify({ key: streamKey.key }), {
|
||||
status: 200,
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
async function readChannelNameFromBody(request: NextRequest) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
return isValidChannelName(body?.channel) ? body.channel : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function isValidChannelName(channelName: unknown): channelName is string {
|
||||
return typeof channelName === 'string' && channelName.length > 0;
|
||||
}
|
||||
|
||||
function badRequestResponse() {
|
||||
return new Response('Bad Request', { status: 400 });
|
||||
}
|
||||
|
||||
function unauthorizedResponse() {
|
||||
return new Response('Unauthorized', { status: 401 });
|
||||
}
|
||||
|
||||
type AuthorizedChannelResult =
|
||||
| {
|
||||
channel: {
|
||||
id: string;
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
| {
|
||||
response: Response;
|
||||
};
|
||||
|
||||
@@ -19,7 +19,13 @@ export async function POST(request: NextRequest, segmentData: { params: Params }
|
||||
const body = await request.json();
|
||||
const parsedBody = bodySchema.safeParse(body);
|
||||
if (!parsedBody.success) {
|
||||
return new Response(JSON.stringify({ success: false, error: parsedBody.error.errors.map(e => e.message).join(', ') }), { status: 400 });
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: false,
|
||||
error: parsedBody.error.issues.map((issue) => issue.message).join(', '),
|
||||
}),
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const { action, name } = parsedBody.data;
|
||||
@@ -121,4 +127,4 @@ export async function GET(request: NextRequest, segmentData: { params: Params })
|
||||
function generateApiKey() {
|
||||
const uuid = crypto.randomUUID().replace(/-/g, '');
|
||||
return `hctvb_${uuid}`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,18 +1,21 @@
|
||||
'use client';
|
||||
import { UniversalForm } from '@/components/app/UniversalForm/UniversalForm';
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from '@/components/ui/card';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { editBot } from '@/lib/form/actions';
|
||||
import { BotAccount } from '@hctv/db';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { UploadButton } from '@/lib/uploadthing';
|
||||
import { toast } from 'sonner';
|
||||
import React from 'react';
|
||||
|
||||
export function GeneralSettings(props: BotAccount) {
|
||||
const router = useRouter();
|
||||
const [isUploading, setIsUploading] = React.useState(false);
|
||||
const [uploadError, setUploadError] = React.useState<string | null>(null);
|
||||
const formRef = React.useRef<HTMLFormElement>(null);
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
@@ -21,6 +24,7 @@ export function GeneralSettings(props: BotAccount) {
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<UniversalForm
|
||||
formRef={formRef}
|
||||
fields={[
|
||||
{
|
||||
name: 'from',
|
||||
@@ -42,7 +46,7 @@ export function GeneralSettings(props: BotAccount) {
|
||||
label: 'Bot Slug',
|
||||
placeholder: 'Enter bot slug',
|
||||
required: true,
|
||||
value: props.slug
|
||||
value: props.slug,
|
||||
},
|
||||
{
|
||||
name: 'description',
|
||||
@@ -52,11 +56,96 @@ export function GeneralSettings(props: BotAccount) {
|
||||
value: props.description,
|
||||
textArea: true,
|
||||
},
|
||||
{
|
||||
name: 'pfpUrl',
|
||||
label: 'Profile Picture',
|
||||
type: 'url',
|
||||
value: props.pfpUrl,
|
||||
component: ({ field }) => {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<input type="hidden" {...field} />
|
||||
|
||||
{field.value && (
|
||||
<div className="flex items-center space-x-4">
|
||||
<Avatar className="h-16 w-16">
|
||||
<AvatarImage src={field.value} alt="Current profile picture" />
|
||||
<AvatarFallback>{props.displayName[0]?.toUpperCase()}</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="flex-1">
|
||||
<p className="text-sm font-medium">Current profile picture</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Click "Upload new image" to replace
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
field.onChange('');
|
||||
setUploadError(null);
|
||||
}}
|
||||
>
|
||||
Remove
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<UploadButton
|
||||
endpoint="pfpUpload"
|
||||
className="mt-2 ut-button:bg-mantle ut-button:text-mantle-foreground ut-allowed-content:text-muted-foreground/70"
|
||||
content={{
|
||||
button: field.value ? 'Upload new image' : 'Upload profile picture',
|
||||
allowedContent: 'Image (1MB max)',
|
||||
}}
|
||||
onUploadBegin={() => {
|
||||
setIsUploading(true);
|
||||
setUploadError(null);
|
||||
}}
|
||||
onClientUploadComplete={(res) => {
|
||||
setIsUploading(false);
|
||||
if (res && res[0]) {
|
||||
field.onChange(res[0].ufsUrl);
|
||||
toast.success('Profile picture uploaded successfully!');
|
||||
setTimeout(() => {
|
||||
formRef.current?.requestSubmit();
|
||||
}, 0);
|
||||
}
|
||||
}}
|
||||
onUploadError={(error) => {
|
||||
setIsUploading(false);
|
||||
setUploadError(error.message);
|
||||
toast.error(`Upload failed: ${error.message}`);
|
||||
}}
|
||||
disabled={isUploading}
|
||||
/>
|
||||
|
||||
{isUploading && <p className="mt-2 text-sm text-primary">Uploading...</p>}
|
||||
|
||||
{uploadError && <p className="mt-2 text-sm text-red-600">{uploadError}</p>}
|
||||
|
||||
{!field.value && !isUploading && !uploadError && (
|
||||
<p className="mt-2 text-sm text-muted-foreground">
|
||||
Upload a profile picture for your channel.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
]}
|
||||
schemaName={'editBot'}
|
||||
action={editBot}
|
||||
onActionComplete={(result) => {
|
||||
if (result?.success) {
|
||||
router.refresh();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useCallback } from 'react';
|
||||
import { useState, useCallback, useRef } from 'react';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
@@ -39,6 +39,7 @@ import {
|
||||
editStreamInfo,
|
||||
changeUsername,
|
||||
updateChatModeration,
|
||||
updateNotificationChannels,
|
||||
} from '@/lib/form/actions';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { toast } from 'sonner';
|
||||
@@ -61,10 +62,12 @@ 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';
|
||||
import { UploadButton } from '@/lib/uploadthing';
|
||||
import { useChannelStreamKey } from '@/lib/hooks/useChannelStreamKey';
|
||||
import { useOwnedChannels } from '@/lib/hooks/useUserList';
|
||||
import { ChannelSelect } from '@/components/app/ChannelSelect/ChannelSelect';
|
||||
import { useRouter } from 'next/navigation';
|
||||
@@ -77,8 +80,12 @@ import {
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { getMediamtxClientEnvs } from '@/lib/utils/mediamtx/client';
|
||||
import {
|
||||
getMediamtxClientEnvs,
|
||||
getMediamtxClientRegionOptions,
|
||||
} from '@/lib/utils/mediamtx/client';
|
||||
import type { MediaMTXRegion } from '@/lib/utils/mediamtx/regions';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
|
||||
interface ChannelSettingsClientProps {
|
||||
channel: Channel & {
|
||||
@@ -89,7 +96,7 @@ interface ChannelSettingsClientProps {
|
||||
chatModerators: User[];
|
||||
chatModeratorPersonalChannels: (Channel | null)[];
|
||||
chatModeratorBots: BotAccount[];
|
||||
teamBotAccounts: BotAccount[];
|
||||
allBotAccounts: Pick<BotAccount, 'id' | 'displayName' | 'slug' | 'pfpUrl'>[];
|
||||
streamInfo: StreamInfo[];
|
||||
streamKey: StreamKey | null;
|
||||
chatSettings: ChatModerationSettings | null;
|
||||
@@ -106,11 +113,9 @@ interface ChannelSettingsClientProps {
|
||||
export default function ChannelSettingsClient({
|
||||
channel,
|
||||
isOwner,
|
||||
currentUser,
|
||||
isPersonal,
|
||||
}: ChannelSettingsClientProps) {
|
||||
const confirm = useConfirm();
|
||||
const [streamKey, setStreamKey] = useState(channel.streamKey?.key || '');
|
||||
const [keyVisible, setKeyVisible] = useState(false);
|
||||
const [copied, setCopied] = useState({
|
||||
streamKey: false,
|
||||
@@ -119,9 +124,16 @@ export default function ChannelSettingsClient({
|
||||
const [selTab, setSelTab] = useQueryState('tab', parseAsString.withDefault('general'));
|
||||
const [isUploading, setIsUploading] = useState(false);
|
||||
const [uploadError, setUploadError] = useState<string | null>(null);
|
||||
const serverOptions = getMediamtxClientRegionOptions();
|
||||
const [region, setRegion] = useState<MediaMTXRegion>('hq');
|
||||
const channelList = useOwnedChannels();
|
||||
const {
|
||||
streamKey,
|
||||
isRegenerating: isRegeneratingStreamKey,
|
||||
regenerateStreamKey,
|
||||
} = useChannelStreamKey(channel.name, channel.streamKey?.key);
|
||||
const router = useRouter();
|
||||
const channelSettingsFormRef = useRef<HTMLFormElement>(null);
|
||||
|
||||
const handleStreamInfoActionComplete = useCallback((result: any) => {
|
||||
if (result?.success) {
|
||||
@@ -141,6 +153,12 @@ export default function ChannelSettingsClient({
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleNotifChannelsActionComplete = useCallback((result: any) => {
|
||||
if (result?.success) {
|
||||
toast.success('Notification channels updated');
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleUsernameChangeComplete = useCallback(
|
||||
(result: any) => {
|
||||
if (result?.success && result?.newUsername) {
|
||||
@@ -176,22 +194,11 @@ export default function ChannelSettingsClient({
|
||||
}
|
||||
};
|
||||
|
||||
const regenerateStreamKey = async () => {
|
||||
const handleRegenerateStreamKey = async () => {
|
||||
try {
|
||||
const response = await fetch('/api/rtmp/streamKey', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ channel: channel.name }),
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
setStreamKey(data.key);
|
||||
toast.success('Stream key regenerated successfully');
|
||||
} else {
|
||||
toast.error('Failed to regenerate stream key');
|
||||
}
|
||||
} catch (error) {
|
||||
await regenerateStreamKey();
|
||||
toast.success('Stream key regenerated successfully');
|
||||
} catch {
|
||||
toast.error('Failed to regenerate stream key');
|
||||
}
|
||||
};
|
||||
@@ -238,6 +245,7 @@ export default function ChannelSettingsClient({
|
||||
<div>
|
||||
<ChannelSelect
|
||||
channelList={channelList.channels.map((c) => c.channel)}
|
||||
includeCreate
|
||||
value={channel.name}
|
||||
onSelect={(value) => {
|
||||
if (value === 'create') {
|
||||
@@ -274,9 +282,9 @@ export default function ChannelSettingsClient({
|
||||
<MessageSquareWarning className="h-4 w-4" />
|
||||
Moderation
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="utilities" className="flex items-center gap-2">
|
||||
<TabsTrigger value="integrations" className="flex items-center gap-2">
|
||||
<Wrench className="size-4" />
|
||||
Utilities
|
||||
Integrations
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
@@ -290,6 +298,7 @@ export default function ChannelSettingsClient({
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
<UniversalForm
|
||||
formRef={channelSettingsFormRef}
|
||||
fields={[
|
||||
{ name: 'channelId', type: 'hidden', value: channel.id, label: 'Channel ID' },
|
||||
{
|
||||
@@ -345,6 +354,9 @@ export default function ChannelSettingsClient({
|
||||
if (res && res[0]) {
|
||||
field.onChange(res[0].ufsUrl);
|
||||
toast.success('Profile picture uploaded successfully!');
|
||||
setTimeout(() => {
|
||||
channelSettingsFormRef.current?.requestSubmit();
|
||||
}, 0);
|
||||
}
|
||||
}}
|
||||
onUploadError={(error) => {
|
||||
@@ -548,7 +560,12 @@ export default function ChannelSettingsClient({
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
<Button onClick={regenerateStreamKey} variant="outline" size="smicon">
|
||||
<Button
|
||||
onClick={handleRegenerateStreamKey}
|
||||
variant="outline"
|
||||
size="smicon"
|
||||
loading={isRegeneratingStreamKey}
|
||||
>
|
||||
<Key className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
@@ -574,7 +591,11 @@ export default function ChannelSettingsClient({
|
||||
<SelectValue placeholder="Select region" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="hq">HQ Server A 🇺🇸</SelectItem>
|
||||
{serverOptions.map((server) => (
|
||||
<SelectItem key={server.value} value={server.value}>
|
||||
{server.label} {server.emoji}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
@@ -857,7 +878,7 @@ export default function ChannelSettingsClient({
|
||||
/>
|
||||
<AddChatBotModeratorDialog
|
||||
channelId={channel.id}
|
||||
teamBots={channel.teamBotAccounts}
|
||||
botAccounts={channel.allBotAccounts}
|
||||
existingBotModerators={channel.chatModeratorBots.map((bot) => bot.id)}
|
||||
/>
|
||||
</div>
|
||||
@@ -1047,11 +1068,13 @@ export default function ChannelSettingsClient({
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
<TabsContent value="utilities">
|
||||
<TabsContent value="integrations">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Utilities</CardTitle>
|
||||
<CardDescription>OBS overlays, APIs... everything in one neat place!</CardDescription>
|
||||
<CardTitle>Integrations</CardTitle>
|
||||
<CardDescription>
|
||||
OBS overlays, Slack... everything in one neat place!
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
<div className="space-y-4">
|
||||
@@ -1069,11 +1092,58 @@ export default function ChannelSettingsClient({
|
||||
className="w-full px-3 py-2 border rounded-md bg-mantle font-mono text-sm"
|
||||
/>
|
||||
</div>
|
||||
<Button variant="outline" size="sm" onClick={() => setKeyVisible(!keyVisible)}>
|
||||
{keyVisible ? 'Hide' : 'Show'}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="smicon"
|
||||
onClick={() => setKeyVisible(!keyVisible)}
|
||||
>
|
||||
{keyVisible ? <EyeOff className='size-4' /> : <Eye className='size-4' />}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<UniversalForm
|
||||
fields={[
|
||||
{ name: 'channelId', type: 'hidden', value: channel.id, label: 'Channel ID' },
|
||||
{
|
||||
name: 'channels',
|
||||
label: 'Notification channels',
|
||||
value: channel.notifChannels.join('\n'),
|
||||
textArea: true,
|
||||
textAreaRows: 4,
|
||||
component: ({ field }) => (
|
||||
<div>
|
||||
<Textarea
|
||||
name={field.name}
|
||||
ref={field.ref}
|
||||
value={
|
||||
typeof field.value === 'string'
|
||||
? field.value
|
||||
: ''
|
||||
}
|
||||
disabled={channel.is247}
|
||||
rows={4}
|
||||
placeholder={
|
||||
channel.is247
|
||||
? 'Notifications are disabled for 24/7 channels'
|
||||
: 'Enter channel IDs, one per line'
|
||||
}
|
||||
onBlur={field.onBlur}
|
||||
onChange={field.onChange}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
{channel.is247
|
||||
? '24/7 channels do not send go-live notifications, so notification channels cannot be edited.'
|
||||
: 'Enter one channel ID per line. You can find channel IDs in their URLs.'}
|
||||
</p>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
]}
|
||||
schemaName="updateNotificationChannels"
|
||||
action={updateNotificationChannels}
|
||||
submitText="Save notification channels"
|
||||
onActionComplete={handleNotifChannelsActionComplete}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
@@ -1260,20 +1330,16 @@ function AddChatModeratorDialog({
|
||||
|
||||
function AddChatBotModeratorDialog({
|
||||
channelId,
|
||||
teamBots,
|
||||
botAccounts,
|
||||
existingBotModerators,
|
||||
}: {
|
||||
channelId: string;
|
||||
teamBots: BotAccount[];
|
||||
botAccounts: Pick<BotAccount, 'id' | 'displayName' | 'slug' | 'pfpUrl'>[];
|
||||
existingBotModerators: string[];
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [selectedBotId, setSelectedBotId] = useState('');
|
||||
|
||||
const availableBots = teamBots.filter(
|
||||
(botAccount) => !existingBotModerators.includes(botAccount.id)
|
||||
);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
@@ -1286,21 +1352,16 @@ function AddChatBotModeratorDialog({
|
||||
<DialogHeader>
|
||||
<DialogTitle>Add bot moderator</DialogTitle>
|
||||
<DialogDescription>
|
||||
Bots can delete messages, timeout users, and ban users in chat.
|
||||
Look up any bot account by name or slug to grant moderation powers.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<Select value={selectedBotId} onValueChange={setSelectedBotId}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select bot" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{availableBots.map((botAccount) => (
|
||||
<SelectItem key={botAccount.id} value={botAccount.id}>
|
||||
{botAccount.displayName} (@{botAccount.slug})
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<BotCombobox
|
||||
bots={botAccounts}
|
||||
filter={existingBotModerators}
|
||||
value={selectedBotId}
|
||||
onValueChange={setSelectedBotId}
|
||||
modal
|
||||
/>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
disabled={!selectedBotId}
|
||||
|
||||
@@ -65,12 +65,12 @@ export default async function ChannelSettingsPage({
|
||||
const followerPersonalChannels = await Promise.all(
|
||||
channel.followers.map((follower) => resolvePersonalChannel(follower.user.id))
|
||||
);
|
||||
const teamMemberIds = [channel.ownerId, ...channel.managers.map((manager) => manager.id)];
|
||||
const teamBotAccounts = await prisma.botAccount.findMany({
|
||||
where: {
|
||||
ownerId: {
|
||||
in: teamMemberIds,
|
||||
},
|
||||
const allBotAccounts = await prisma.botAccount.findMany({
|
||||
select: {
|
||||
id: true,
|
||||
displayName: true,
|
||||
slug: true,
|
||||
pfpUrl: true,
|
||||
},
|
||||
orderBy: {
|
||||
slug: 'asc',
|
||||
@@ -86,7 +86,7 @@ export default async function ChannelSettingsPage({
|
||||
managerPersonalChannels,
|
||||
chatModeratorPersonalChannels,
|
||||
followerPersonalChannels,
|
||||
teamBotAccounts,
|
||||
allBotAccounts,
|
||||
}}
|
||||
isOwner={isOwner}
|
||||
currentUser={user}
|
||||
|
||||
411
apps/web/src/app/(ui)/(protected)/stream/page.tsx
Normal file
@@ -0,0 +1,411 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import type { ReactNode } from 'react';
|
||||
import type { LucideIcon } from 'lucide-react';
|
||||
import {
|
||||
AlertTriangle,
|
||||
CircleAlert,
|
||||
Globe,
|
||||
LoaderCircle,
|
||||
Monitor,
|
||||
Radio,
|
||||
RefreshCw,
|
||||
Square,
|
||||
Video,
|
||||
} from 'lucide-react';
|
||||
import { ChannelSelect } from '@/components/app/ChannelSelect/ChannelSelect';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { useChannelStreamKey } from '@/lib/hooks/useChannelStreamKey';
|
||||
import { useOwnedChannels } from '@/lib/hooks/useUserList';
|
||||
import { useScreensharePublisher } from '@/lib/hooks/useScreensharePublisher';
|
||||
import { getMediamtxClientRegionOptions } from '@/lib/utils/mediamtx/client';
|
||||
import type { MediaMTXRegion } from '@/lib/utils/mediamtx/regions';
|
||||
|
||||
export default function Page() {
|
||||
const serverOptions = getMediamtxClientRegionOptions();
|
||||
const whipEnabledServerOptions = serverOptions.filter((server) => server.whipEnabled);
|
||||
const defaultRegion = whipEnabledServerOptions[0]?.value ?? 'hq';
|
||||
const [selectedChannel, setSelectedChannel] = useState('');
|
||||
const [selectedRegion, setSelectedRegion] = useState<MediaMTXRegion>(defaultRegion);
|
||||
const { channels, isLoading: isLoadingChannels } = useOwnedChannels();
|
||||
const ownedChannels = channels.map(({ channel }) => channel);
|
||||
const {
|
||||
streamKey,
|
||||
error: streamKeyError,
|
||||
isLoading: isLoadingStreamKey,
|
||||
} = useChannelStreamKey(selectedChannel || undefined);
|
||||
const {
|
||||
browserWarning,
|
||||
changeSource,
|
||||
hasPreview,
|
||||
issue,
|
||||
isLive,
|
||||
isPreviewReady,
|
||||
isPreviewingSource,
|
||||
isSessionActive,
|
||||
isStarting,
|
||||
isSwitchingSource,
|
||||
previewRef,
|
||||
previewSource,
|
||||
startPublishing,
|
||||
stopPublishing,
|
||||
} = useScreensharePublisher({
|
||||
channelName: selectedChannel,
|
||||
region: selectedRegion,
|
||||
streamKey,
|
||||
});
|
||||
|
||||
const hasChannels = ownedChannels.length > 0;
|
||||
const selectedServer = whipEnabledServerOptions.find((server) => server.value === selectedRegion);
|
||||
const hasWhipEnabledServerOptions = whipEnabledServerOptions.length > 0;
|
||||
const canStartPublishing =
|
||||
!isSessionActive &&
|
||||
!isPreviewingSource &&
|
||||
Boolean(selectedChannel) &&
|
||||
Boolean(streamKey) &&
|
||||
Boolean(selectedServer?.whipEnabled) &&
|
||||
!isLoadingStreamKey;
|
||||
const channelPlaceholder = isLoadingChannels ? 'Loading channels...' : 'Select a channel';
|
||||
const primaryIssue = issue ?? browserWarning;
|
||||
|
||||
useEffect(() => {
|
||||
if (isSessionActive) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!ownedChannels.some((channel) => channel.name === selectedChannel)) {
|
||||
setSelectedChannel(ownedChannels[0]?.name ?? '');
|
||||
}
|
||||
}, [isSessionActive, ownedChannels, selectedChannel]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isLive) {
|
||||
return;
|
||||
}
|
||||
|
||||
const handleBeforeUnload = (event: BeforeUnloadEvent) => {
|
||||
event.preventDefault();
|
||||
event.returnValue = '';
|
||||
};
|
||||
|
||||
window.addEventListener('beforeunload', handleBeforeUnload);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('beforeunload', handleBeforeUnload);
|
||||
};
|
||||
}, [isLive]);
|
||||
|
||||
const statusLabel = isLive
|
||||
? 'LIVE'
|
||||
: isSwitchingSource
|
||||
? 'Switching'
|
||||
: isStarting
|
||||
? 'Connecting'
|
||||
: isPreviewingSource
|
||||
? hasPreview
|
||||
? 'Updating Preview'
|
||||
: 'Preparing Preview'
|
||||
: isPreviewReady
|
||||
? 'Preview'
|
||||
: 'Ready';
|
||||
|
||||
return (
|
||||
<div className="relative flex min-h-[calc(100vh-4rem)] flex-col">
|
||||
{/* Video Stage */}
|
||||
<div className="flex flex-1 items-center justify-center px-4 py-4 md:px-6">
|
||||
<div className="w-full max-w-6xl">
|
||||
<div className="relative overflow-hidden rounded-3xl border border-border/60 bg-black shadow-2xl">
|
||||
<div className="relative aspect-video w-full bg-black">
|
||||
<video
|
||||
ref={previewRef}
|
||||
autoPlay
|
||||
muted
|
||||
playsInline
|
||||
className="h-full w-full object-contain"
|
||||
/>
|
||||
|
||||
{!hasPreview && (
|
||||
<div className="absolute inset-0 flex flex-col items-center justify-center gap-5 px-6 text-muted-foreground">
|
||||
<div className="flex h-24 w-24 items-center justify-center rounded-full border border-secondary bg-secondary/80">
|
||||
<Monitor className="h-10 w-10 text-primary/80" />
|
||||
</div>
|
||||
<div className="max-w-md text-center space-y-1.5">
|
||||
<p className="text-lg font-medium text-zinc-200">
|
||||
Ready to livestream
|
||||
</p>
|
||||
<p className="text-sm text-zinc-400">
|
||||
Select a tab, window, or display to preview.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{(isPreviewingSource || isStarting || isSwitchingSource) && (
|
||||
<div className="absolute inset-0 flex flex-col items-center justify-center gap-3 bg-black/60 text-white backdrop-blur-sm">
|
||||
<LoaderCircle className="h-8 w-8 animate-spin" />
|
||||
<p className="text-sm font-medium">
|
||||
{isPreviewingSource
|
||||
? hasPreview
|
||||
? 'Updating preview...'
|
||||
: 'Preparing preview...'
|
||||
: isStarting
|
||||
? 'Starting broadcast...'
|
||||
: 'Switching source...'}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="absolute left-6 top-6">
|
||||
<Badge
|
||||
variant={isLive ? 'default' : hasPreview ? 'secondary' : 'outline'}
|
||||
className={cn(
|
||||
'gap-2 px-3 py-1 text-xs font-semibold shadow-lg backdrop-blur-md transition-all',
|
||||
isLive && 'bg-red-500 text-white hover:bg-red-600',
|
||||
!isLive && !hasPreview && 'border-zinc-800 bg-black/50 text-zinc-400'
|
||||
)}
|
||||
>
|
||||
{isLive && <span className="h-2 w-2 animate-pulse rounded-full bg-white shadow-[0_0_8px_rgba(255,255,255,0.8)]" />}
|
||||
{statusLabel}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{(streamKeyError || primaryIssue) && (
|
||||
<div className="absolute inset-x-0 top-4 z-10 mx-auto max-w-xl px-4 md:top-6">
|
||||
{streamKeyError ? (
|
||||
<AlertCard
|
||||
actions={
|
||||
<Button onClick={() => window.location.reload()} size="sm" variant="outline">
|
||||
<RefreshCw className="mr-2 h-4 w-4" />
|
||||
Reload page
|
||||
</Button>
|
||||
}
|
||||
description={getStreamKeyErrorDescription(streamKeyError.message)}
|
||||
icon={CircleAlert}
|
||||
title="Could not load the stream key"
|
||||
tone="destructive"
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{primaryIssue ? (
|
||||
<AlertCard
|
||||
actions={
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{!isSessionActive && primaryIssue.context === 'preview' ? (
|
||||
<Button
|
||||
onClick={previewSource}
|
||||
disabled={isPreviewingSource}
|
||||
loading={isPreviewingSource}
|
||||
size="sm"
|
||||
>
|
||||
Preview again
|
||||
</Button>
|
||||
) : null}
|
||||
|
||||
{!isSessionActive &&
|
||||
primaryIssue.context !== 'warning' &&
|
||||
primaryIssue.context !== 'preview' ? (
|
||||
<Button onClick={startPublishing} disabled={!canStartPublishing} size="sm">
|
||||
Try again
|
||||
</Button>
|
||||
) : null}
|
||||
|
||||
{primaryIssue.context === 'switch' && isLive ? (
|
||||
<Button
|
||||
onClick={changeSource}
|
||||
disabled={isSwitchingSource}
|
||||
loading={isSwitchingSource}
|
||||
size="sm"
|
||||
>
|
||||
Try switching again
|
||||
</Button>
|
||||
) : null}
|
||||
|
||||
{isSessionActive && primaryIssue.context !== 'warning' ? (
|
||||
<Button onClick={stopPublishing} size="sm" variant="outline">
|
||||
Stop stream
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
}
|
||||
description={primaryIssue.description}
|
||||
icon={primaryIssue.tone === 'warning' ? AlertTriangle : CircleAlert}
|
||||
title={primaryIssue.title}
|
||||
tone={primaryIssue.tone}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="shrink-0 border-t border-border/50 bg-background/95 px-4 py-4 backdrop-blur supports-[backdrop-filter]:bg-background/60">
|
||||
<div className="mx-auto flex max-w-6xl flex-col items-stretch gap-4 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="flex flex-wrap items-center gap-5">
|
||||
<div className="flex items-center gap-3">
|
||||
<Video className="h-4 w-4 text-muted-foreground" />
|
||||
<ChannelSelect
|
||||
channelList={ownedChannels}
|
||||
disabled={isSessionActive || isLoadingChannels || !hasChannels}
|
||||
placeholder={channelPlaceholder}
|
||||
value={selectedChannel || undefined}
|
||||
onSelect={setSelectedChannel}
|
||||
triggerClassName="w-48"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<Globe className="h-4 w-4 text-muted-foreground" />
|
||||
<Select
|
||||
value={selectedRegion}
|
||||
onValueChange={(value) => setSelectedRegion(value as MediaMTXRegion)}
|
||||
disabled={isSessionActive || !hasWhipEnabledServerOptions}
|
||||
>
|
||||
<SelectTrigger className="w-44">
|
||||
<SelectValue placeholder="Select server" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{whipEnabledServerOptions.map((server) => (
|
||||
<SelectItem key={server.value} value={server.value}>
|
||||
{server.label} {server.emoji}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{!hasChannels && !isLoadingChannels ? (
|
||||
<p className="text-xs text-muted-foreground">Create a channel to stream.</p>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{/* Right: Actions */}
|
||||
<div className="flex flex-wrap items-center justify-end gap-2">
|
||||
{!isSessionActive ? (
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={previewSource}
|
||||
disabled={isPreviewingSource}
|
||||
loading={isPreviewingSource}
|
||||
size="default"
|
||||
>
|
||||
<Monitor className="mr-2 h-4 w-4" />
|
||||
{hasPreview ? 'Change Preview' : 'Preview'}
|
||||
</Button>
|
||||
|
||||
{hasPreview ? (
|
||||
<Button
|
||||
onClick={stopPublishing}
|
||||
disabled={isPreviewingSource}
|
||||
variant="outline"
|
||||
size="default"
|
||||
>
|
||||
<Square className="mr-2 h-4 w-4" />
|
||||
Clear Preview
|
||||
</Button>
|
||||
) : null}
|
||||
|
||||
<Button
|
||||
onClick={startPublishing}
|
||||
disabled={!canStartPublishing || isSwitchingSource}
|
||||
loading={isStarting}
|
||||
size="default"
|
||||
>
|
||||
<Radio className="mr-2 h-4 w-4" />
|
||||
Start
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={changeSource}
|
||||
disabled={!isLive}
|
||||
loading={isSwitchingSource}
|
||||
size="default"
|
||||
>
|
||||
<RefreshCw className="mr-2 h-4 w-4" />
|
||||
Switch
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
onClick={stopPublishing}
|
||||
disabled={isPreviewingSource || isSwitchingSource}
|
||||
variant="outline"
|
||||
size="default"
|
||||
>
|
||||
<Square className="mr-2 h-4 w-4" />
|
||||
Stop
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AlertCard({ actions, description, icon: Icon, title, tone }: AlertCardProps) {
|
||||
const isWarning = tone === 'warning';
|
||||
|
||||
return (
|
||||
<Card
|
||||
className={cn(
|
||||
'overflow-hidden border-l-4 shadow-xl backdrop-blur-md',
|
||||
isWarning
|
||||
? 'border-l-amber-500 bg-amber-500/[0.03]'
|
||||
: 'border-l-destructive bg-destructive/[0.03]'
|
||||
)}
|
||||
>
|
||||
<CardContent className="flex flex-col gap-4 p-4 md:flex-row md:items-start md:justify-between">
|
||||
<div className="flex items-start gap-3">
|
||||
<Icon
|
||||
className={cn(
|
||||
'mt-0.5 h-5 w-5 shrink-0',
|
||||
isWarning ? 'text-amber-500' : 'text-destructive'
|
||||
)}
|
||||
/>
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-semibold">{title}</p>
|
||||
<p className="text-sm text-muted-foreground">{description}</p>
|
||||
</div>
|
||||
</div>
|
||||
{actions ? <div className="flex flex-wrap gap-2 md:shrink-0">{actions}</div> : null}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function getStreamKeyErrorDescription(message: string) {
|
||||
if (message.toLowerCase().includes('unauthorized')) {
|
||||
return 'You no longer have permission to stream to this channel. Try another channel or sign in again.';
|
||||
}
|
||||
|
||||
if (message.toLowerCase().includes('not found')) {
|
||||
return 'This channel does not have a valid stream key yet. Regenerate it in channel settings, then retry.';
|
||||
}
|
||||
|
||||
return 'Refresh the page and try again. If it keeps failing, check channel settings and server config.';
|
||||
}
|
||||
|
||||
type AlertCardProps = {
|
||||
actions?: ReactNode;
|
||||
description: string;
|
||||
icon: LucideIcon;
|
||||
title: string;
|
||||
tone: 'warning' | 'destructive';
|
||||
};
|
||||
@@ -1,3 +1,4 @@
|
||||
import slackNotifier from '@/lib/services/slackNotifier';
|
||||
import { hackClub, lucia, HCID_TOKEN_URL, HCID_USER_INFO_URL } from '@hctv/auth';
|
||||
import { cookies as nextCookies } from 'next/headers';
|
||||
import { OAuth2RequestError } from 'arctic';
|
||||
@@ -8,34 +9,59 @@ import { getRedisConnection } from '@hctv/db';
|
||||
export async function GET(request: Request): Promise<Response> {
|
||||
const cookies = await nextCookies();
|
||||
const url = new URL(request.url);
|
||||
const code = url.searchParams.get("code");
|
||||
const state = url.searchParams.get("state");
|
||||
const storedState = cookies.get("hackclub_oauth_state")?.value ?? null;
|
||||
if (!code || !state || !storedState || state !== storedState) {
|
||||
const code = url.searchParams.get('code');
|
||||
const state = url.searchParams.get('state');
|
||||
const storedState = cookies.get('hackclub_oauth_state')?.value ?? null;
|
||||
if (!code || !state || !storedState || state !== storedState) {
|
||||
console.log('invalid state stuff');
|
||||
return new Response(null, {
|
||||
status: 400
|
||||
});
|
||||
}
|
||||
return new Response(null, {
|
||||
status: 400,
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
const tokens = await hackClub.validateAuthorizationCode(HCID_TOKEN_URL, code, null);
|
||||
const accessToken = tokens.accessToken();
|
||||
const userResponse = await fetch(HCID_USER_INFO_URL, {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${accessToken}`,
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (!userResponse.ok) {
|
||||
return new Response('Unable to verify your Hack Club identity right now. Please try again.', {
|
||||
status: 502,
|
||||
});
|
||||
}
|
||||
|
||||
const userResult: HackClubUserResponse = await userResponse.json();
|
||||
const identity = userResult.identity;
|
||||
const bypass = await checkIfBypass(identity.primary_email);
|
||||
|
||||
if (identity.verification_status !== 'verified') {
|
||||
if (!bypass) {
|
||||
return new Response(getVerificationErrorMessage(identity.verification_status), {
|
||||
status: 403,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const slackId = identity.slack_id;
|
||||
if (!slackId) {
|
||||
return new Response("Please make sure to have a Slack account before continuing.", {
|
||||
return new Response('Please make sure to have a Slack account before continuing.', {
|
||||
status: 400,
|
||||
});
|
||||
}
|
||||
|
||||
const slackValidation = await validateSlackUser(slackId);
|
||||
if (!slackValidation.success) {
|
||||
if (!bypass) {
|
||||
return new Response(slackValidation.message, {
|
||||
status: slackValidation.status,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const existingUser = await prisma.user.findFirst({
|
||||
where: {
|
||||
slack_id: slackId,
|
||||
@@ -70,7 +96,9 @@ export async function GET(request: Request): Promise<Response> {
|
||||
id: userId,
|
||||
slack_id: slackId,
|
||||
email: identity.primary_email,
|
||||
pfpUrl: identity.slack_id ? `https://cachet.dunkirk.sh/users/${identity.slack_id}/r` : 'https://github.com/hackclub.png',
|
||||
pfpUrl: identity.slack_id
|
||||
? `https://cachet.dunkirk.sh/users/${identity.slack_id}/r`
|
||||
: 'https://github.com/hackclub.png',
|
||||
hasOnboarded: false,
|
||||
},
|
||||
});
|
||||
@@ -106,9 +134,85 @@ interface HackClubIdentity {
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
primary_email: string;
|
||||
verification_status: VerificationStatus;
|
||||
}
|
||||
|
||||
interface HackClubUserResponse {
|
||||
identity: HackClubIdentity;
|
||||
}
|
||||
|
||||
type VerificationStatus = 'needs_submission' | 'pending' | 'verified' | 'ineligible';
|
||||
|
||||
type SlackValidationResult =
|
||||
| {
|
||||
success: true;
|
||||
}
|
||||
| {
|
||||
success: false;
|
||||
message: string;
|
||||
status: number;
|
||||
};
|
||||
|
||||
function getVerificationErrorMessage(status: VerificationStatus): string {
|
||||
switch (status) {
|
||||
case 'needs_submission':
|
||||
return 'Please complete Hack Club Identity verification before signing in to hackclub.tv.';
|
||||
case 'pending':
|
||||
return 'Your Hack Club Identity verification is still being reviewed. Please try again once it is approved.';
|
||||
case 'ineligible':
|
||||
return 'Your Hack Club Identity verification was rejected, so you cannot access hackclub.tv right now.';
|
||||
case 'verified':
|
||||
return 'Verified users can continue.';
|
||||
}
|
||||
}
|
||||
|
||||
async function validateSlackUser(slackId: string): Promise<SlackValidationResult> {
|
||||
if (!process.env.SLACK_NOTIFIER_TOKEN) {
|
||||
return {
|
||||
success: false,
|
||||
message: 'Slack verification is not configured right now. Please try again later.',
|
||||
status: 503,
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await slackNotifier.users.info({ user: slackId });
|
||||
if (!response.ok || !response.user) {
|
||||
return {
|
||||
success: false,
|
||||
message: 'Unable to verify your Slack account right now. Please try again later.',
|
||||
status: 502,
|
||||
};
|
||||
}
|
||||
|
||||
if (response.user.deleted) {
|
||||
return {
|
||||
success: false,
|
||||
message: 'Your Slack account is deactivated, so you cannot access hackclub.tv.',
|
||||
status: 403,
|
||||
};
|
||||
}
|
||||
|
||||
if (response.user.is_restricted || response.user.is_ultra_restricted) {
|
||||
return {
|
||||
success: false,
|
||||
message:
|
||||
'Guest Slack accounts cannot access hackclub.tv. Please sign in with a full Hack Club Slack account.',
|
||||
status: 403,
|
||||
};
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
} catch {
|
||||
return {
|
||||
success: false,
|
||||
message: 'Unable to verify your Slack account right now. Please try again later.',
|
||||
status: 502,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async function checkIfBypass(email: string): Promise<boolean> {
|
||||
const user = await prisma.user.findFirst({ where: { email } });
|
||||
return user?.bypassVerification ?? false;
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import { useSession } from '@/lib/providers/SessionProvider';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
import { User, Tv, Heart, MessageSquare } from 'lucide-react';
|
||||
import Image from 'next/image';
|
||||
import BlahajHeart from '@/lib/assets/blahaj-heart.webp';
|
||||
|
||||
export default function OnboardingClient() {
|
||||
const { user } = useSession();
|
||||
@@ -31,7 +32,7 @@ export default function OnboardingClient() {
|
||||
Welcome to hackclub.tv!
|
||||
</h1>
|
||||
<p className="text-lg text-muted-foreground flex gap-2 justify-center">
|
||||
Let's get you set up <Image src="https://emoji.slack-edge.com/T0266FRGM/blahaj-heart/db9adf8229e9a4fb.png" alt=":blahaj-heart:" width={24} height={24} />
|
||||
Let's get you set up <Image src={BlahajHeart} alt=":blahaj-heart:" height={28} />
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -73,7 +74,7 @@ export default function OnboardingClient() {
|
||||
<Heart className="w-4 h-4 text-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="font-semibold text-sm">Follow hackclubbers</h3>
|
||||
<h3 className="font-semibold text-sm">Follow Hack Clubbers</h3>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Stay updated with your favorite creators and streams
|
||||
</p>
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import type { Metadata } from 'next';
|
||||
import { Inter } from 'next/font/google';
|
||||
import { cookies } from 'next/headers';
|
||||
import '../globals.css';
|
||||
import Navbar from '@/components/app/NavBar/NavBar';
|
||||
@@ -9,7 +8,6 @@ import { Toaster } from '@/components/ui/sonner';
|
||||
import { ThemeProvider } from '@/lib/providers/ThemeProvider';
|
||||
import { SidebarProvider } from '@/components/ui/sidebar';
|
||||
import Sidebar from '@/components/app/Sidebar/Sidebar';
|
||||
import { cn } from '@/lib/utils';
|
||||
import EditLivestream from '@/components/app/EditLivestream/EditLivestream';
|
||||
import { StreamInfoProvider } from '@/lib/providers/StreamInfoProvider';
|
||||
import { NextSSRPlugin } from "@uploadthing/react/next-ssr-plugin";
|
||||
@@ -19,8 +17,6 @@ import { NuqsAdapter } from 'nuqs/adapters/next/app'
|
||||
import SonnerNewVersion from '@/components/app/SonnerNewVersion/SonnerNewVersion';
|
||||
import ConfirmDialogProvider from '@/lib/providers/ConfirmProvider';
|
||||
|
||||
const inter = Inter({ subsets: ['latin'] });
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'hackclub.tv',
|
||||
description: "Hack Club's livestreaming platform",
|
||||
@@ -37,7 +33,7 @@ export default async function RootLayout({
|
||||
|
||||
return (
|
||||
<html lang="en">
|
||||
<body className={cn('flex flex-col h-screen', inter.className)}>
|
||||
<body className="flex h-screen flex-col">
|
||||
<SessionProvider value={sessionData}>
|
||||
<ThemeProvider
|
||||
attribute="class"
|
||||
@@ -59,10 +55,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
@@ -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_PASSWORD;
|
||||
}
|
||||
BIN
apps/web/src/app/apple-icon.png
Normal file
|
After Width: | Height: | Size: 9.2 KiB |
|
Before Width: | Height: | Size: 25 KiB After Width: | Height: | Size: 15 KiB |
@@ -1,128 +1,163 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
@import "tailwindcss";
|
||||
@import "tw-animate-css";
|
||||
|
||||
@layer base {
|
||||
:root {
|
||||
/* Light theme - based on your color scheme */
|
||||
@config "../../tailwind.config.mts";
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
/* Main background and foreground */
|
||||
--background: 350 59% 98%; /* FDF7F8 - main background */
|
||||
--foreground: 351 34% 30%; /* 5D3A3F - main text */
|
||||
@font-face {
|
||||
font-family: 'Phantom Sans';
|
||||
src:
|
||||
url('https://assets.hackclub.com/fonts/Phantom_Sans_0.7/Regular.woff2') format('woff2'),
|
||||
url('https://assets.hackclub.com/fonts/Phantom_Sans_0.7/Regular.woff') format('woff');
|
||||
font-weight: normal;
|
||||
font-style: normal;
|
||||
font-display: swap;
|
||||
}
|
||||
|
||||
/* Muted elements */
|
||||
--muted: 350 40% 93%; /* F8E8EA - muted background */
|
||||
--muted-foreground: 350 30% 45%; /* Lighter version of main text */
|
||||
@font-face {
|
||||
font-family: 'Phantom Sans';
|
||||
src:
|
||||
url('https://assets.hackclub.com/fonts/Phantom_Sans_0.7/Italic.woff2') format('woff2'),
|
||||
url('https://assets.hackclub.com/fonts/Phantom_Sans_0.7/Italic.woff') format('woff');
|
||||
font-weight: normal;
|
||||
font-style: italic;
|
||||
font-display: swap;
|
||||
}
|
||||
|
||||
/* Popover and card */
|
||||
--popover: 0 0% 100%; /* FFFFFF - popover background */
|
||||
--popover-foreground: 351 34% 30%; /* 5D3A3F - popover text */
|
||||
--card: 0 0% 100%; /* FFFFFF - card background */
|
||||
--card-foreground: 351 34% 30%; /* 5D3A3F - card text */
|
||||
@font-face {
|
||||
font-family: 'Phantom Sans';
|
||||
src:
|
||||
url('https://assets.hackclub.com/fonts/Phantom_Sans_0.7/Bold.woff2') format('woff2'),
|
||||
url('https://assets.hackclub.com/fonts/Phantom_Sans_0.7/Bold.woff') format('woff');
|
||||
font-weight: bold;
|
||||
font-style: normal;
|
||||
font-display: swap;
|
||||
}
|
||||
|
||||
/* Border and input */
|
||||
--border: 350 30% 85%; /* Derived border color */
|
||||
--input: 350 30% 85%; /* Input background */
|
||||
:root {
|
||||
--background: hsl(350 59% 98%);
|
||||
--foreground: hsl(351 34% 30%);
|
||||
--muted: hsl(350 40% 93%);
|
||||
--muted-foreground: hsl(350 30% 45%);
|
||||
--popover: hsl(0 0% 100%);
|
||||
--popover-foreground: hsl(351 34% 30%);
|
||||
--card: hsl(0 0% 100%);
|
||||
--card-foreground: hsl(351 34% 30%);
|
||||
--border: hsl(350 30% 85%);
|
||||
--input: hsl(350 30% 85%);
|
||||
--primary: hsl(350 70% 50%);
|
||||
--primary-foreground: hsl(0 0% 100%);
|
||||
--secondary: hsl(350 40% 93%);
|
||||
--secondary-foreground: hsl(351 34% 30%);
|
||||
--accent: hsl(350 70% 40%);
|
||||
--accent-foreground: hsl(0 0% 100%);
|
||||
--destructive: hsl(350 70% 55%);
|
||||
--destructive-foreground: hsl(0 0% 100%);
|
||||
--ring: hsl(350 70% 50%);
|
||||
--surface-1: hsl(350 40% 93%);
|
||||
--surface-2: hsl(350 35% 88%);
|
||||
--mantle: hsl(350 59% 98%);
|
||||
--mantle-foreground: hsl(351 34% 30%);
|
||||
--radius: 0.5rem;
|
||||
--sidebar-background: hsl(350 59% 98%);
|
||||
--sidebar-foreground: hsl(351 34% 30%);
|
||||
--sidebar-primary: hsl(350 70% 50%);
|
||||
--sidebar-primary-foreground: hsl(0 0% 100%);
|
||||
--sidebar-accent: hsl(350 40% 93%);
|
||||
--sidebar-accent-foreground: hsl(351 34% 30%);
|
||||
--sidebar-border: hsl(350 30% 85%);
|
||||
--sidebar-ring: hsl(350 70% 50%);
|
||||
}
|
||||
|
||||
/* Primary actions */
|
||||
--primary: 350 70% 50%; /* C8394F - primary button */
|
||||
--primary-foreground: 0 0% 100%; /* FFFFFF - text on primary */
|
||||
.dark {
|
||||
--background: hsl(350 20% 15%);
|
||||
--foreground: hsl(350 30% 92%);
|
||||
--muted: hsl(350 20% 25%);
|
||||
--muted-foreground: hsl(350 30% 75%);
|
||||
--popover: hsl(350 20% 15%);
|
||||
--popover-foreground: hsl(350 30% 92%);
|
||||
--card: hsl(350 20% 15%);
|
||||
--card-foreground: hsl(350 30% 92%);
|
||||
--border: hsl(350 20% 35%);
|
||||
--input: hsl(350 20% 35%);
|
||||
--primary: hsl(350 100% 75%);
|
||||
--primary-foreground: hsl(350 20% 15%);
|
||||
--secondary: hsl(350 20% 25%);
|
||||
--secondary-foreground: hsl(350 30% 92%);
|
||||
--accent: hsl(350 100% 80%);
|
||||
--accent-foreground: hsl(350 20% 15%);
|
||||
--destructive: hsl(350 100% 70%);
|
||||
--destructive-foreground: hsl(350 20% 15%);
|
||||
--ring: hsl(350 100% 75%);
|
||||
--surface-1: hsl(350 20% 25%);
|
||||
--surface-2: hsl(350 20% 35%);
|
||||
--mantle: hsl(350 20% 12%);
|
||||
--mantle-foreground: hsl(350 30% 92%);
|
||||
--sidebar-background: hsl(350 20% 12%);
|
||||
--sidebar-foreground: hsl(350 30% 92%);
|
||||
--sidebar-primary: hsl(350 100% 75%);
|
||||
--sidebar-primary-foreground: hsl(350 20% 15%);
|
||||
--sidebar-accent: hsl(350 20% 25%);
|
||||
--sidebar-accent-foreground: hsl(350 30% 92%);
|
||||
--sidebar-border: hsl(350 20% 35%);
|
||||
--sidebar-ring: hsl(350 100% 75%);
|
||||
}
|
||||
|
||||
/* Secondary elements */
|
||||
--secondary: 350 40% 93%; /* F8E8EA - secondary background */
|
||||
--secondary-foreground: 351 34% 30%; /* 5D3A3F - text on secondary */
|
||||
@theme inline {
|
||||
--font-sans: 'Phantom Sans', ui-sans-serif, system-ui, sans-serif;
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--color-muted: var(--muted);
|
||||
--color-muted-foreground: var(--muted-foreground);
|
||||
--color-popover: var(--popover);
|
||||
--color-popover-foreground: var(--popover-foreground);
|
||||
--color-card: var(--card);
|
||||
--color-card-foreground: var(--card-foreground);
|
||||
--color-border: var(--border);
|
||||
--color-input: var(--input);
|
||||
--color-primary: var(--primary);
|
||||
--color-primary-foreground: var(--primary-foreground);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-secondary-foreground: var(--secondary-foreground);
|
||||
--color-accent: var(--accent);
|
||||
--color-accent-foreground: var(--accent-foreground);
|
||||
--color-destructive: var(--destructive);
|
||||
--color-destructive-foreground: var(--destructive-foreground);
|
||||
--color-ring: var(--ring);
|
||||
--color-surface1: var(--surface-1);
|
||||
--color-surface2: var(--surface-2);
|
||||
--color-mantle: var(--mantle);
|
||||
--color-mantle-foreground: var(--mantle-foreground);
|
||||
--color-sidebar: var(--sidebar-background);
|
||||
--color-sidebar-foreground: var(--sidebar-foreground);
|
||||
--color-sidebar-primary: var(--sidebar-primary);
|
||||
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
|
||||
--color-sidebar-accent: var(--sidebar-accent);
|
||||
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||
--color-sidebar-border: var(--sidebar-border);
|
||||
--color-sidebar-ring: var(--sidebar-ring);
|
||||
--radius-sm: calc(var(--radius) - 4px);
|
||||
--radius-md: calc(var(--radius) - 2px);
|
||||
--radius-lg: var(--radius);
|
||||
--animate-accordion-down: accordion-down 0.2s ease-out;
|
||||
--animate-accordion-up: accordion-up 0.2s ease-out;
|
||||
}
|
||||
|
||||
/* Accent elements */
|
||||
--accent: 350 70% 40%; /* A12D3E - accent color */
|
||||
--accent-foreground: 0 0% 100%; /* FFFFFF - text on accent */
|
||||
|
||||
/* Destructive actions */
|
||||
--destructive: 350 70% 55%; /* D63C56 - error/destroy */
|
||||
--destructive-foreground: 0 0% 100%; /* FFFFFF - text on destructive */
|
||||
|
||||
/* Focus ring */
|
||||
--ring: 350 70% 50%; /* C8394F - focus ring */
|
||||
|
||||
/* Surface colors */
|
||||
--surface-1: 350 40% 93%; /* F8E8EA - surface 1 */
|
||||
--surface-2: 350 35% 88%; /* Derived surface 2 */
|
||||
|
||||
/* Mantle */
|
||||
--mantle: 350 59% 98%; /* FDF7F8 - mantle */
|
||||
|
||||
/* Radius */
|
||||
--radius: 0.5rem;
|
||||
|
||||
/* Sidebar specific */
|
||||
--sidebar-background: 350 59% 98%; /* FDF7F8 - sidebar bg */
|
||||
--sidebar-foreground: 351 34% 30%; /* 5D3A3F - sidebar text */
|
||||
--sidebar-primary: 350 70% 50%; /* C8394F - sidebar primary */
|
||||
--sidebar-primary-foreground: 0 0% 100%; /* FFFFFF - text on sidebar primary */
|
||||
--sidebar-accent: 350 40% 93%; /* F8E8EA - sidebar accent */
|
||||
--sidebar-accent-foreground: 351 34% 30%; /* 5D3A3F - text on sidebar accent */
|
||||
--sidebar-border: 350 30% 85%; /* Derived border */
|
||||
--sidebar-ring: 350 70% 50%; /* C8394F - sidebar focus ring */
|
||||
@keyframes accordion-down {
|
||||
from {
|
||||
height: 0;
|
||||
}
|
||||
to {
|
||||
height: var(--radix-accordion-content-height);
|
||||
}
|
||||
}
|
||||
|
||||
.dark {
|
||||
/* Dark theme - based on your color scheme */
|
||||
|
||||
/* Main background and foreground */
|
||||
--background: 350 20% 15%; /* 2A1F21 - main background */
|
||||
--foreground: 350 30% 92%; /* F5E6E8 - main text */
|
||||
|
||||
/* Muted elements */
|
||||
--muted: 350 20% 25%; /* 4A2D31 - muted background */
|
||||
--muted-foreground: 350 30% 75%; /* Lighter version of main text */
|
||||
|
||||
/* Popover and card */
|
||||
--popover: 350 20% 15%; /* 2A1F21 - popover background */
|
||||
--popover-foreground: 350 30% 92%; /* F5E6E8 - popover text */
|
||||
--card: 350 20% 15%; /* 2A1F21 - card background */
|
||||
--card-foreground: 350 30% 92%; /* F5E6E8 - card text */
|
||||
|
||||
/* Border and input */
|
||||
--border: 350 20% 35%; /* Derived border color */
|
||||
--input: 350 20% 35%; /* Input background */
|
||||
|
||||
/* Primary actions */
|
||||
--primary: 350 100% 75%; /* FF7A8A - primary button */
|
||||
--primary-foreground: 350 20% 15%; /* 2A1F21 - text on primary */
|
||||
|
||||
/* Secondary elements */
|
||||
--secondary: 350 20% 25%; /* 4A2D31 - secondary background */
|
||||
--secondary-foreground: 350 30% 92%; /* F5E6E8 - text on secondary */
|
||||
|
||||
/* Accent elements */
|
||||
--accent: 350 100% 80%; /* FF9AAA - accent color */
|
||||
--accent-foreground: 350 20% 15%; /* 2A1F21 - text on accent */
|
||||
|
||||
/* Destructive actions */
|
||||
--destructive: 350 100% 70%; /* FF6B7D - error/destroy */
|
||||
--destructive-foreground: 350 20% 15%; /* 2A1F21 - text on destructive */
|
||||
|
||||
/* Focus ring */
|
||||
--ring: 350 100% 75%; /* FF7A8A - focus ring */
|
||||
|
||||
/* Surface colors */
|
||||
--surface-1: 350 20% 25%; /* 4A2D31 - surface 1 */
|
||||
--surface-2: 350 20% 35%; /* Derived surface 2 */
|
||||
|
||||
/* Mantle */
|
||||
--mantle: 350 20% 12%; /* 1F1617 - mantle */
|
||||
|
||||
/* Radius */
|
||||
--radius: 0.5rem;
|
||||
|
||||
/* Sidebar specific */
|
||||
--sidebar-background: 350 20% 12%; /* 1F1617 - sidebar bg */
|
||||
--sidebar-foreground: 350 30% 92%; /* F5E6E8 - sidebar text */
|
||||
--sidebar-primary: 350 100% 75%; /* FF7A8A - sidebar primary */
|
||||
--sidebar-primary-foreground: 350 20% 15%; /* 2A1F21 - text on sidebar primary */
|
||||
--sidebar-accent: 350 20% 25%; /* 4A2D31 - sidebar accent */
|
||||
--sidebar-accent-foreground: 350 30% 92%; /* F5E6E8 - text on sidebar accent */
|
||||
--sidebar-border: 350 20% 35%; /* Derived border */
|
||||
--sidebar-ring: 350 100% 75%; /* FF7A8A - sidebar focus ring */
|
||||
@keyframes accordion-up {
|
||||
from {
|
||||
height: var(--radix-accordion-content-height);
|
||||
}
|
||||
to {
|
||||
height: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -131,76 +166,113 @@
|
||||
@apply border-border;
|
||||
}
|
||||
body {
|
||||
font-family: 'Phantom Sans', ui-sans-serif, system-ui, sans-serif;
|
||||
@apply bg-background text-foreground;
|
||||
}
|
||||
|
||||
.scrollbar-hide::-webkit-scrollbar { display: none; }
|
||||
.scrollbar-hide { -ms-overflow-style: none; scrollbar-width: none; }
|
||||
|
||||
.scrollbar-hide::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.scrollbar-hide {
|
||||
-ms-overflow-style: none;
|
||||
scrollbar-width: none;
|
||||
}
|
||||
}
|
||||
|
||||
h1 {
|
||||
@apply scroll-m-20 text-4xl font-extrabold tracking-tight lg:text-5xl;
|
||||
}
|
||||
|
||||
h2 {
|
||||
@apply scroll-m-20 pb-2 text-3xl font-semibold tracking-tight first:mt-0;
|
||||
}
|
||||
|
||||
/* Media controller styles remain unchanged */
|
||||
media-controller {
|
||||
--media-primary-color: #ffffff;
|
||||
--media-secondary-color: hsla(var(--background), 0.85);
|
||||
--media-control-hover-background: hsla(var(--accent), 0.85);
|
||||
--media-control-background: hsla(var(--secondary), 0.85);
|
||||
--media-loading-icon-color: #ffffff;
|
||||
border-radius: var(--radius);
|
||||
--media-secondary-color: transparent;
|
||||
--media-control-background: transparent;
|
||||
--media-control-hover-background: color-mix(in oklab, var(--primary) 40%, transparent);
|
||||
|
||||
/* Range colors */
|
||||
--media-range-track-background: hsla(0, 0%, 100%, 0.3);
|
||||
--media-range-bar-color: var(--primary);
|
||||
--media-range-thumb-background: var(--primary);
|
||||
--media-range-thumb-border-radius: 50%;
|
||||
--media-range-thumb-height: 12px;
|
||||
--media-range-thumb-width: 12px;
|
||||
--media-range-track-height: 4px;
|
||||
|
||||
/* Layout & structure */
|
||||
border-radius: calc(var(--radius) * 1.5);
|
||||
overflow: hidden;
|
||||
border: 1px solid hsl(var(--border));
|
||||
border: 1px solid color-mix(in oklab, var(--border) 20%, transparent);
|
||||
background-color: #000;
|
||||
box-shadow: 0 10px 30px -10px rgba(0,0,0,0.3);
|
||||
}
|
||||
|
||||
media-control-bar {
|
||||
background-color: hsla(var(--background), 0.8);
|
||||
backdrop-filter: blur(8px);
|
||||
background: linear-gradient(to top, rgba(0,0,0,0.85) 0%, rgba(0,0,0,0) 100%);
|
||||
backdrop-filter: blur(4px);
|
||||
-webkit-mask-image: linear-gradient(to top, black 50%, transparent 100%);
|
||||
mask-image: linear-gradient(to top, black 50%, transparent 100%);
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
justify-content: space-between;
|
||||
padding: 2rem 0.75rem 0.75rem;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
media-time-range {
|
||||
--media-range-track-height: 6px;
|
||||
--media-range-thumb-height: 14px;
|
||||
--media-range-thumb-width: 14px;
|
||||
--media-range-thumb-border-radius: 50%;
|
||||
--media-range-bar-color: #ffffff;
|
||||
--media-range-thumb-background: #ffffff;
|
||||
--media-preview-background: hsla(var(--card), 0.9);
|
||||
--media-preview-background: color-mix(in oklab, var(--card) 95%, transparent);
|
||||
--media-preview-border-radius: var(--radius);
|
||||
--media-time-display-color: var(--foreground);
|
||||
}
|
||||
|
||||
media-time-display {
|
||||
--media-text-color: #ffffff;
|
||||
font-weight: 500;
|
||||
font-variant-numeric: tabular-nums;
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
|
||||
media-controller::part(centered-layer) {
|
||||
background-color: hsla(var(--background), 0.2);
|
||||
transition: opacity 0.3s ease;
|
||||
background-color: transparent;
|
||||
transition: opacity 0.4s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
}
|
||||
|
||||
media-controller:not([mediapaused])[userinactive]::part(centered-layer) {
|
||||
opacity: 0;
|
||||
transition: opacity 1s ease;
|
||||
transition: opacity 0.8s ease;
|
||||
}
|
||||
|
||||
media-loading-indicator {
|
||||
--media-loading-icon-width: 48px;
|
||||
--media-loading-icon-height: 48px;
|
||||
--media-loading-icon-color: #ffffff;
|
||||
--media-loading-icon-width: 56px;
|
||||
--media-loading-icon-height: 56px;
|
||||
--media-loading-icon-color: var(--primary);
|
||||
filter: drop-shadow(0 0 8px color-mix(in oklab, var(--primary) 40%, transparent));
|
||||
}
|
||||
|
||||
media-play-button,
|
||||
media-mute-button,
|
||||
media-fullscreen-button,
|
||||
media-chrome-button {
|
||||
transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
border-radius: var(--radius);
|
||||
margin: 0 2px;
|
||||
}
|
||||
|
||||
media-play-button:hover,
|
||||
media-mute-button:hover,
|
||||
media-fullscreen-button:hover,
|
||||
media-seek-backward-button:hover,
|
||||
media-seek-forward-button:hover {
|
||||
--media-control-hover-background: rgba(255, 255, 255, 0.2);
|
||||
}
|
||||
media-chrome-button:hover {
|
||||
transform: scale(1.1);
|
||||
--media-control-background: color-mix(in oklab, var(--primary) 85%, transparent);
|
||||
--media-button-icon-color: #ffffff;
|
||||
}
|
||||
|
||||
/* A pulse animation for the live/retry indicator if needed */
|
||||
@keyframes stream-pulse {
|
||||
0%, 100% { opacity: 1; }
|
||||
50% { opacity: 0.5; }
|
||||
}
|
||||
.stream-live-indicator {
|
||||
animation: stream-pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
|
||||
}
|
||||
|
||||
media-volume-range {
|
||||
width: 90px;
|
||||
height: 40px; /* Aligns with standard media button heights */
|
||||
}
|
||||
|
||||
1
apps/web/src/app/icon0.svg
Normal file
|
After Width: | Height: | Size: 362 KiB |
BIN
apps/web/src/app/icon1.png
Normal file
|
After Width: | Height: | Size: 4.8 KiB |
21
apps/web/src/app/manifest.json
Normal file
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"name": "MyWebSite",
|
||||
"short_name": "MySite",
|
||||
"icons": [
|
||||
{
|
||||
"src": "/web-app-manifest-192x192.png",
|
||||
"sizes": "192x192",
|
||||
"type": "image/png",
|
||||
"purpose": "maskable"
|
||||
},
|
||||
{
|
||||
"src": "/web-app-manifest-512x512.png",
|
||||
"sizes": "512x512",
|
||||
"type": "image/png",
|
||||
"purpose": "maskable"
|
||||
}
|
||||
],
|
||||
"theme_color": "#ffffff",
|
||||
"background_color": "#ffffff",
|
||||
"display": "standalone"
|
||||
}
|
||||
104
apps/web/src/components/app/BotCombobox/BotCombobox.tsx
Normal file
@@ -0,0 +1,104 @@
|
||||
'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}
|
||||
keywords={[bot.displayName, bot.slug]}
|
||||
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;
|
||||
};
|
||||
@@ -1,8 +1,7 @@
|
||||
'use client'
|
||||
'use client';
|
||||
|
||||
import type { Channel } from "@hctv/db";
|
||||
import * as React from 'react';
|
||||
import { Plus } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
@@ -11,13 +10,21 @@ import {
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar';
|
||||
import type { Channel } from '@hctv/db';
|
||||
|
||||
export function ChannelSelect(props: Props) {
|
||||
const { channelList } = props;
|
||||
const {
|
||||
channelList,
|
||||
disabled = false,
|
||||
includeCreate = false,
|
||||
placeholder = 'Channel',
|
||||
triggerClassName,
|
||||
} = props;
|
||||
|
||||
return (
|
||||
<Select onValueChange={props.onSelect} value={props.value}>
|
||||
<SelectTrigger className="w-[180px]">
|
||||
<SelectValue placeholder="Channel" />
|
||||
<Select disabled={disabled} onValueChange={props.onSelect} value={props.value}>
|
||||
<SelectTrigger className={cn('w-[180px]', triggerClassName)}>
|
||||
<SelectValue placeholder={placeholder} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{channelList.map((channel) => (
|
||||
@@ -25,15 +32,22 @@ export function ChannelSelect(props: Props) {
|
||||
<div className="flex items-center gap-3">
|
||||
<Avatar className="h-8 w-8">
|
||||
<AvatarImage src={channel.pfpUrl} alt={channel.name} />
|
||||
<AvatarFallback>{channel.name[0]}</AvatarFallback>
|
||||
<AvatarFallback>{channel.name[0]?.toUpperCase()}</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="font-medium">{channel.name}</div>
|
||||
</div>
|
||||
</SelectItem>
|
||||
))}
|
||||
<SelectItem key="create" value="create" icon={<Plus className="h-4 w-4" />} className='h-11'>
|
||||
Create Channel
|
||||
</SelectItem>
|
||||
{includeCreate ? (
|
||||
<SelectItem
|
||||
key="create"
|
||||
value="create"
|
||||
icon={<Plus className="h-4 w-4" />}
|
||||
className="h-11"
|
||||
>
|
||||
Create Channel
|
||||
</SelectItem>
|
||||
) : null}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
);
|
||||
@@ -42,5 +56,9 @@ export function ChannelSelect(props: Props) {
|
||||
interface Props {
|
||||
channelList: Channel[];
|
||||
value?: string;
|
||||
disabled?: boolean;
|
||||
includeCreate?: boolean;
|
||||
onSelect: (value: string) => void;
|
||||
}
|
||||
placeholder?: string;
|
||||
triggerClassName?: string;
|
||||
}
|
||||
|
||||
@@ -300,7 +300,7 @@ export default function ChatPanel(props: Props) {
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`${props.isObsPanel ? 'w-full text-white' : 'md:border-l border-border bg-mantle w-[350px] max-w-[350px]'} flex flex-col h-full`}
|
||||
className={`${props.isObsPanel ? 'w-full text-white' : 'w-full max-w-none md:w-[350px] md:max-w-[350px] md:border-l border-border bg-mantle'} flex flex-col h-full min-w-0`}
|
||||
>
|
||||
<div
|
||||
ref={scrollRef}
|
||||
|
||||
@@ -9,7 +9,7 @@ interface EmojiSearchProps {
|
||||
onSelect: (emoji: string) => void;
|
||||
socket: WebSocket | null;
|
||||
emojiMap: Map<string, string>;
|
||||
textareaRef: React.RefObject<HTMLTextAreaElement>;
|
||||
textareaRef: React.RefObject<HTMLTextAreaElement | null>;
|
||||
}
|
||||
|
||||
export function EmojiSearch({
|
||||
|
||||
@@ -59,7 +59,9 @@ function TooltipIcon({
|
||||
return (
|
||||
<Tooltip delayDuration={200}>
|
||||
<TooltipTrigger asChild>
|
||||
<Icon className={cn('size-3.5 shrink-0', className)} />
|
||||
<span className={cn('inline-flex align-[-0.15em]', className)}>
|
||||
<Icon className="size-[1.1em] shrink-0" />
|
||||
</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top">{label}</TooltipContent>
|
||||
</Tooltip>
|
||||
@@ -71,15 +73,25 @@ function UsernameRow({ user, displayName }: { user?: User; displayName?: string
|
||||
|
||||
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>
|
||||
{user?.isBot && (
|
||||
<TooltipIcon icon={Bot} label="Bot" className="text-muted-foreground mr-[0.3em]" />
|
||||
)}
|
||||
{role && (
|
||||
<TooltipIcon
|
||||
icon={role.icon}
|
||||
label={role.label}
|
||||
className={cn(role.className, 'mr-[0.3em]')}
|
||||
/>
|
||||
)}
|
||||
{user?.isPlatformAdmin && (
|
||||
<TooltipIcon
|
||||
icon={ShieldAlert}
|
||||
label="Platform Admin"
|
||||
className="text-destructive mr-[0.3em]"
|
||||
/>
|
||||
)}
|
||||
<span className="font-semibold text-primary">{displayName}</span>
|
||||
<span className="font-normal text-muted-foreground select-none">: </span>
|
||||
</TooltipProvider>
|
||||
);
|
||||
}
|
||||
@@ -116,7 +128,7 @@ function ReportDialog({
|
||||
<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>
|
||||
<p className="mt-2 whitespace-pre-wrap break-words">{message}</p>
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-sm font-medium">Reason</label>
|
||||
@@ -215,14 +227,16 @@ export function Message({
|
||||
<>
|
||||
<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
|
||||
<div
|
||||
lang="en"
|
||||
className="text-foreground min-w-0 flex-1"
|
||||
className="text-foreground min-w-0 flex-1 leading-normal"
|
||||
style={{ overflowWrap: 'anywhere', wordBreak: 'break-word' }}
|
||||
>
|
||||
<EmojiRenderer text={message} emojiMap={emojiMap} />
|
||||
</span>
|
||||
<UsernameRow user={user} displayName={displayName} />
|
||||
<span className="whitespace-pre-wrap break-words">
|
||||
<EmojiRenderer text={message} emojiMap={emojiMap} />
|
||||
</span>
|
||||
</div>
|
||||
{type === 'message' && user?.id && (
|
||||
<MessageActionsMenu
|
||||
user={user}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { format } from 'date-fns';
|
||||
import { AlertTriangle, RefreshCw } from 'lucide-react';
|
||||
import StreamPlayer from '../StreamPlayer/StreamPlayer';
|
||||
import UserInfoCard from '../UserInfoCard/UserInfoCard';
|
||||
import ChatPanel from '../ChatPanel/ChatPanel';
|
||||
@@ -9,13 +10,14 @@ import { Button } from '@/components/ui/button';
|
||||
import type { StreamInfo, Channel } from '@hctv/db';
|
||||
import { useIsMobile } from '@/lib/hooks/useMobile';
|
||||
import { useAllChannels } from '@/lib/hooks/useUserList';
|
||||
import { RefreshCw } from 'lucide-react';
|
||||
|
||||
export default function LiveStream(props: Props) {
|
||||
const isMobile = useIsMobile();
|
||||
const { channels, refresh } = useAllChannels(5000);
|
||||
const [isRestricted, setIsRestricted] = useState(false);
|
||||
const [restrictionExpiresAt, setRestrictionExpiresAt] = useState<string | null>(null);
|
||||
const [isRestricted, setIsRestricted] = useState(props.initialRestrictionActive);
|
||||
const [restrictionExpiresAt, setRestrictionExpiresAt] = useState<string | null>(
|
||||
props.initialRestrictionExpiresAt
|
||||
);
|
||||
const [isRefreshing, setIsRefreshing] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -38,7 +40,7 @@ export default function LiveStream(props: Props) {
|
||||
}
|
||||
};
|
||||
|
||||
if (isRestricted) {
|
||||
if (isRestricted && !props.canViewRestrictedStream) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center h-[calc(100vh-64px)] p-4">
|
||||
<h1 className="text-2xl font-bold text-destructive mb-2">Channel Restricted</h1>
|
||||
@@ -59,11 +61,30 @@ export default function LiveStream(props: Props) {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`${isMobile ? 'flex flex-col' : 'flex'} h-[calc(100vh-64px)] w-full`}>
|
||||
<div className={`${isMobile ? 'flex flex-col' : 'flex'} h-[calc(100vh-64px)] w-full min-w-0`}>
|
||||
<div className="flex-1 flex flex-col min-w-0 overflow-hidden">
|
||||
<StreamPlayer />
|
||||
{isRestricted && props.canViewRestrictedStream && (
|
||||
<div className="flex items-start gap-3 border-b border-amber-500/30 bg-amber-500/10 px-4 py-3 text-foreground">
|
||||
<AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />
|
||||
<div className="text-sm">
|
||||
<p className="font-medium">Restricted stream override</p>
|
||||
<p>
|
||||
This channel is restricted and unavailable to regular viewers. You are watching it
|
||||
because you are a platform admin.
|
||||
</p>
|
||||
{restrictionExpiresAt && (
|
||||
<p className="mt-1 text-muted-foreground">
|
||||
Restriction lifts: {format(new Date(restrictionExpiresAt), 'PPP p')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="min-h-0 flex-1 overflow-hidden bg-black">
|
||||
<StreamPlayer />
|
||||
</div>
|
||||
{isMobile && (
|
||||
<div className="flex-1 min-h-[250px] max-h-[400px] border-t border-border">
|
||||
<div className="w-full min-w-0 flex-1 min-h-[250px] max-h-[400px] border-t border-border">
|
||||
<ChatPanel />
|
||||
</div>
|
||||
)}
|
||||
@@ -82,4 +103,7 @@ export default function LiveStream(props: Props) {
|
||||
interface Props {
|
||||
username: string;
|
||||
streamInfo: StreamInfo & { channel: Channel };
|
||||
canViewRestrictedStream: boolean;
|
||||
initialRestrictionActive: boolean;
|
||||
initialRestrictionExpiresAt: string | null;
|
||||
}
|
||||
|
||||
@@ -15,96 +15,177 @@ import { logout } from '@/lib/auth/actions';
|
||||
import { useSession } from '@/lib/providers/SessionProvider';
|
||||
import Link from 'next/link';
|
||||
import { ThemeSwitcher } from '../ThemeSwitcher/ThemeSwitcher';
|
||||
import { IdCard, Shield } from 'lucide-react';
|
||||
import {
|
||||
IdCard,
|
||||
Shield,
|
||||
Settings,
|
||||
Users,
|
||||
PenSquare,
|
||||
LogOut,
|
||||
Code,
|
||||
Heart,
|
||||
Radio,
|
||||
} from 'lucide-react';
|
||||
import { SidebarTrigger } from '@/components/ui/sidebar';
|
||||
import Image from 'next/image';
|
||||
import Logo from '@/lib/assets/logo.webp';
|
||||
import { usePersonalChannels } from '@/lib/hooks/useUserList';
|
||||
import { JSX } from 'react';
|
||||
|
||||
export default function Navbar(props: Props) {
|
||||
const { user } = useSession();
|
||||
const { channels: personalChannels } = usePersonalChannels();
|
||||
const personalChannel = personalChannels.find((channel) => channel.channelId === user?.personalChannelId);
|
||||
const username = personalChannel?.username || 'not-onboarded';
|
||||
|
||||
const menuItemClass = "cursor-pointer rounded-lg px-3 py-2 text-sm font-medium hover:bg-primary/10 focus:bg-primary/10 hover:text-primary focus:text-primary";
|
||||
const iconClass = "w-4 h-4 mr-3 text-muted-foreground";
|
||||
|
||||
return (
|
||||
<>
|
||||
<nav className="flex items-center justify-between h-14 md:h-16 px-2 md:px-4 border-b gap-1 md:gap-3 w-full z-40 fixed top-0 left-0 shadow-md bg-mantle">
|
||||
<div className="flex items-center space-x-2 md:space-x-5 shrink-0">
|
||||
<Link href="/" className="flex items-center">
|
||||
<Button variant={'ghost'} className="px-2 md:px-3 text-sm md:text-base">
|
||||
hackclub.tv
|
||||
<Link href="/" className="flex items-center">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="rounded-sm hover:scale-105 transition-transform duration-200 "
|
||||
>
|
||||
<Image
|
||||
src={Logo}
|
||||
alt="HCTV Logo"
|
||||
className="h-6 w-6 md:h-8 md:w-8"
|
||||
/>
|
||||
</Button>
|
||||
</Link>
|
||||
</Link>
|
||||
<SidebarTrigger />
|
||||
</div>
|
||||
|
||||
{/* Right Side Items */}
|
||||
<div className="flex items-center gap-1 md:gap-3 shrink-0">
|
||||
{user && (
|
||||
<Link href="/stream">
|
||||
<Button variant="outline" size="sm" className="gap-1 md:gap-2 text-xs md:text-sm">
|
||||
<Radio className="w-3 h-3 md:w-4 md:h-4" />
|
||||
<span className="hidden sm:inline">Go live</span>
|
||||
<span className="sm:hidden">Live</span>
|
||||
</Button>
|
||||
</Link>
|
||||
)}
|
||||
|
||||
{props.editLivestream && <div className="hidden sm:block">{props.editLivestream}</div>}
|
||||
|
||||
{user ? (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild className="cursor-pointer">
|
||||
<Avatar className="h-8 w-8 md:h-10 md:w-10">
|
||||
<AvatarImage src={user.pfpUrl} alt={`@${user.id}`} />
|
||||
<AvatarImage src={user.pfpUrl} alt={`@${username || '(not onboarded)'}`} />
|
||||
<AvatarFallback>{user.pfpUrl}</AvatarFallback>
|
||||
</Avatar>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent className="w-56">
|
||||
<DropdownMenuLabel>My Account</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuGroup>
|
||||
<DropdownMenuContent className="w-64 mt-2 p-2 rounded-xl border-border/50 shadow-xl backdrop-blur-xl bg-mantle/95" align="end" sideOffset={5}>
|
||||
<div className="flex items-center gap-3 p-2 mb-2">
|
||||
<Avatar className="h-10 w-10 border border-border/50">
|
||||
<AvatarImage src={user.pfpUrl} alt={`@${username}`} />
|
||||
<AvatarFallback>{username[0]?.toUpperCase()}</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="flex flex-col space-y-0.5">
|
||||
<p className="text-sm font-semibold tracking-tight text-foreground">@{username}</p>
|
||||
<p className="text-xs text-muted-foreground truncate max-w-[140px]">Manage your account</p>
|
||||
</div>
|
||||
</div>
|
||||
<DropdownMenuSeparator className="bg-border/40 mb-2" />
|
||||
|
||||
<DropdownMenuGroup className="space-y-1">
|
||||
<Link href={`/settings/follows`}>
|
||||
<DropdownMenuItem className="cursor-pointer">Follows</DropdownMenuItem>
|
||||
<DropdownMenuItem className={menuItemClass}>
|
||||
<Users className={iconClass} />
|
||||
Follows
|
||||
</DropdownMenuItem>
|
||||
</Link>
|
||||
<Link href={`/settings/channel/create`}>
|
||||
<DropdownMenuItem className="cursor-pointer">Create channel</DropdownMenuItem>
|
||||
<DropdownMenuItem className={menuItemClass}>
|
||||
<PenSquare className={iconClass} />
|
||||
Create channel
|
||||
</DropdownMenuItem>
|
||||
</Link>
|
||||
<Link href={`/settings/bot`}>
|
||||
<DropdownMenuItem className="cursor-pointer">Bot accounts</DropdownMenuItem>
|
||||
<DropdownMenuItem className={menuItemClass}>
|
||||
<Settings className={iconClass} />
|
||||
Bot accounts
|
||||
</DropdownMenuItem>
|
||||
</Link>
|
||||
|
||||
{user.isAdmin && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<div>
|
||||
<DropdownMenuSeparator className="bg-border/40 my-2" />
|
||||
<Link href={`/admin`}>
|
||||
<DropdownMenuItem className="cursor-pointer text-primary">
|
||||
<Shield className="w-4 h-4 mr-2" />
|
||||
<DropdownMenuItem className={`${menuItemClass} text-primary hover:text-primary`}>
|
||||
<Shield className={`w-4 h-4 mr-3 text-primary`} />
|
||||
Admin Panel
|
||||
</DropdownMenuItem>
|
||||
</Link>
|
||||
</>
|
||||
</div>
|
||||
)}
|
||||
<DropdownMenuSeparator />
|
||||
</DropdownMenuGroup>
|
||||
|
||||
<DropdownMenuSeparator className="bg-border/40 my-2" />
|
||||
|
||||
<DropdownMenuGroup className="space-y-1">
|
||||
<Link href={'https://docs.hackclub.tv'} target="_blank" rel="noreferrer">
|
||||
<DropdownMenuItem className="cursor-pointer">API Docs</DropdownMenuItem>
|
||||
</Link>
|
||||
<Link href={'https://github.com/SrIzan10/hctv'} target="_blank" rel="noreferrer">
|
||||
<DropdownMenuItem className="cursor-pointer">Github</DropdownMenuItem>
|
||||
</Link>
|
||||
<Link href={'https://github.com/sponsors/SrIzan10'} target="_blank" rel="noreferrer">
|
||||
<DropdownMenuItem className="cursor-pointer">Sponsor</DropdownMenuItem>
|
||||
<DropdownMenuItem className={menuItemClass}>
|
||||
<Code className={iconClass} />
|
||||
API Docs
|
||||
</DropdownMenuItem>
|
||||
</Link>
|
||||
<div className="grid grid-cols-2 gap-1">
|
||||
<Link href={'https://github.com/SrIzan10/hctv'} target="_blank" rel="noreferrer">
|
||||
<DropdownMenuItem className={`${menuItemClass} justify-center text-xs gap-2`}>
|
||||
<Image
|
||||
src="https://thesvg.org/icons/github/dark.svg"
|
||||
alt="GitHub"
|
||||
width={14}
|
||||
height={14}
|
||||
/>
|
||||
Github
|
||||
</DropdownMenuItem>
|
||||
</Link>
|
||||
<Link href={'https://github.com/sponsors/SrIzan10'} target="_blank" rel="noreferrer">
|
||||
<DropdownMenuItem className={`${menuItemClass} justify-center text-xs text-pink-500 hover:text-pink-500 hover:bg-pink-500/10 focus:bg-pink-500/10`}>
|
||||
<Heart className="w-3.5 h-3.5 mr-1.5" />
|
||||
Sponsor
|
||||
</DropdownMenuItem>
|
||||
</Link>
|
||||
</div>
|
||||
</DropdownMenuGroup>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuGroup>
|
||||
<DropdownMenuItem
|
||||
className="cursor-pointer"
|
||||
onClick={() => {
|
||||
logout();
|
||||
}}
|
||||
>
|
||||
Sign out
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuGroup>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuGroup>
|
||||
|
||||
<DropdownMenuSeparator className="bg-border/40 my-2" />
|
||||
|
||||
<div className="flex items-center justify-between px-1">
|
||||
<ThemeSwitcher />
|
||||
</DropdownMenuGroup>
|
||||
<DropdownMenuGroup>
|
||||
<p className="text-gray-500 dark:text-gray-400 text-sm px-2">
|
||||
v{process.env.version}-{process.env.NODE_ENV === 'development' ? 'dev' : 'prod'}, commit{' '}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="rounded-lg text-red-500 hover:text-red-600 hover:bg-red-500/10"
|
||||
onClick={() => logout()}
|
||||
>
|
||||
<LogOut className="w-4 h-4 mr-2" />
|
||||
Sign out
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="mt-2 pt-3 border-t border-border/40 px-2">
|
||||
<p className="text-[10px] text-muted-foreground/60 text-center font-mono">
|
||||
v{process.env.version}-{process.env.NODE_ENV === 'development' ? 'dev' : 'prod'} • {' '}
|
||||
<Link
|
||||
href={`https://github.com/SrIzan10/hctv/commit/${process.env.commit}`}
|
||||
target="_blank"
|
||||
className="hover:text-primary underline decoration-border/50 underline-offset-2"
|
||||
>
|
||||
{process.env.commit}
|
||||
{process.env.commit?.substring(0, 7) || 'unknown'}
|
||||
</Link>
|
||||
</p>
|
||||
</DropdownMenuGroup>
|
||||
</div>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
) : (
|
||||
|
||||
@@ -25,7 +25,8 @@ export default function Sidebar({ ...props }: React.ComponentProps<typeof UISide
|
||||
|
||||
if (isLoading) return <SidebarSkeleton {...props} />;
|
||||
|
||||
const liveStreamers = stream?.filter((s) => s.isLive) || [];
|
||||
const alwaysOnStreamers = stream?.filter((s) => s.isLive && s.channel.is247) || [];
|
||||
const liveStreamers = stream?.filter((s) => s.isLive && !s.channel.is247) || [];
|
||||
const offlineStreamers = stream?.filter((s) => !s.isLive) || [];
|
||||
|
||||
return (
|
||||
@@ -55,6 +56,31 @@ export default function Sidebar({ ...props }: React.ComponentProps<typeof UISide
|
||||
</SidebarGroupContent>
|
||||
</SidebarGroup>
|
||||
|
||||
<Separator className="group-data-[collapsible=icon]:block hidden" />
|
||||
|
||||
<SidebarGroup>
|
||||
<SidebarGroupLabel className="flex items-center justify-between px-2 py-1.5">
|
||||
<span className="text-xs font-semibold uppercase text-muted-foreground group-data-[collapsible=icon]:opacity-0 transition-opacity duration-200">
|
||||
24/7 Channels
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground group-data-[collapsible=icon]:opacity-0 transition-opacity duration-200">
|
||||
{alwaysOnStreamers.length}
|
||||
</span>
|
||||
</SidebarGroupLabel>
|
||||
<SidebarGroupContent>
|
||||
<SidebarMenu>
|
||||
{alwaysOnStreamers.length === 0 && !isCollapsed && (
|
||||
<div className="px-4 py-2 text-sm text-muted-foreground">
|
||||
No 24/7 channels
|
||||
</div>
|
||||
)}
|
||||
{alwaysOnStreamers.map((streamer) => (
|
||||
<StreamerItem key={streamer.id} streamer={streamer} isCollapsed={isCollapsed} />
|
||||
))}
|
||||
</SidebarMenu>
|
||||
</SidebarGroupContent>
|
||||
</SidebarGroup>
|
||||
|
||||
<Separator className="group-data-[collapsible=icon]:block hidden" />
|
||||
|
||||
<SidebarGroup>
|
||||
@@ -182,4 +208,4 @@ function StreamerItemSkeleton({ isCollapsed }: { isCollapsed: boolean }) {
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,11 +21,29 @@ interface StreamGridProps {
|
||||
}
|
||||
|
||||
export default function StreamGrid({ liveStreams, offlineStreams }: StreamGridProps) {
|
||||
const sortedLiveStreams = [...liveStreams].sort((a, b) => b.viewers - a.viewers);
|
||||
const sortedLiveStreams = liveStreams
|
||||
.filter((stream) => !stream.channel.is247)
|
||||
.sort((a, b) => b.viewers - a.viewers);
|
||||
const alwaysOnStreams = [...liveStreams, ...offlineStreams]
|
||||
.filter((stream) => stream.isLive && stream.channel.is247)
|
||||
.sort((a, b) => {
|
||||
if (a.isLive !== b.isLive) {
|
||||
return Number(b.isLive) - Number(a.isLive);
|
||||
}
|
||||
|
||||
if (a.viewers !== b.viewers) {
|
||||
return b.viewers - a.viewers;
|
||||
}
|
||||
|
||||
return a.channel.name.localeCompare(b.channel.name);
|
||||
});
|
||||
const sortedOfflineStreams = offlineStreams
|
||||
.sort((a, b) => a.channel.name.localeCompare(b.channel.name));
|
||||
const hasVisibleLiveStreams = sortedLiveStreams.length > 0 || alwaysOnStreams.some((stream) => stream.isLive);
|
||||
|
||||
return (
|
||||
<div className="space-y-8 md:space-y-10">
|
||||
{sortedLiveStreams.length === 0 && (
|
||||
<div className="space-y-8 md:space-y-10 min-w-0">
|
||||
{!hasVisibleLiveStreams && (
|
||||
<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">
|
||||
@@ -52,17 +70,25 @@ export default function StreamGrid({ liveStreams, offlineStreams }: StreamGridPr
|
||||
</section>
|
||||
)}
|
||||
|
||||
{offlineStreams.length > 0 && (
|
||||
{alwaysOnStreams.length > 0 && (
|
||||
<section>
|
||||
<SectionHeading label="Offline channels" count={offlineStreams.length} />
|
||||
<div className="relative">
|
||||
<Carousel opts={{ align: 'start', dragFree: true }}>
|
||||
<CarouselContent>
|
||||
{offlineStreams.map((stream) => (
|
||||
<CarouselItem
|
||||
key={stream.id}
|
||||
className="flex basis-[74px] justify-center sm:basis-[82px] md:basis-[90px] lg:basis-[100px]"
|
||||
>
|
||||
<SectionHeading label="24/7 channels" count={alwaysOnStreams.length} />
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 md:gap-4 lg:grid-cols-3 xl:grid-cols-4">
|
||||
{alwaysOnStreams.map((stream) => (
|
||||
<StreamCard key={stream.id} stream={stream} />
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{sortedOfflineStreams.length > 0 && (
|
||||
<section className="w-full min-w-0">
|
||||
<SectionHeading label="Offline channels" count={sortedOfflineStreams.length} />
|
||||
<div className="px-10">
|
||||
<Carousel className="w-full max-w-full" opts={{ dragFree: true, containScroll: 'trimSnaps' }}>
|
||||
<CarouselContent className="-ml-2">
|
||||
{sortedOfflineStreams.map((stream) => (
|
||||
<CarouselItem key={stream.id} className="basis-auto pl-2 md:pl-3">
|
||||
<OfflineCard stream={stream} />
|
||||
</CarouselItem>
|
||||
))}
|
||||
@@ -86,18 +112,29 @@ function StreamCard({ stream }: { stream: StreamWithChannel }) {
|
||||
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>
|
||||
{stream.isLive && (
|
||||
<>
|
||||
<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} />
|
||||
<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>
|
||||
@@ -124,11 +161,16 @@ function StreamCard({ stream }: { stream: StreamWithChannel }) {
|
||||
|
||||
function OfflineCard({ stream }: { stream: StreamWithChannel }) {
|
||||
return (
|
||||
<Link href={`/${stream.username}`} className="group inline-flex">
|
||||
<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} />
|
||||
<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>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import { useParams } from 'next/navigation';
|
||||
import { useRef, useEffect } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import {
|
||||
MediaController,
|
||||
MediaLoadingIndicator,
|
||||
@@ -10,26 +10,92 @@ import {
|
||||
MediaMuteButton,
|
||||
MediaVolumeRange,
|
||||
MediaFullscreenButton,
|
||||
MediaChromeButton,
|
||||
} from 'media-chrome/react';
|
||||
import { RefreshCw, RotateCw } from 'lucide-react';
|
||||
import HlsVideo from 'hls-video-element/react';
|
||||
import type { HlsVideoElement } from 'hls-video-element';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { useSession } from '@/lib/providers/SessionProvider';
|
||||
import { useUserStreamInfo } from '@/lib/hooks/useUserList';
|
||||
import { getMediamtxClientEnvs } from '@/lib/utils/mediamtx/client';
|
||||
import type { MediaMTXRegion } from '@/lib/utils/mediamtx/regions';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const WAITING_RECOVERY_DELAY_MS = 8000;
|
||||
const RECOVERY_COOLDOWN_MS = 2000;
|
||||
|
||||
export default function StreamPlayer() {
|
||||
const { username } = useParams();
|
||||
const { session } = useSession();
|
||||
const { streamInfo: userInfo } = useUserStreamInfo(username!.toString());
|
||||
|
||||
const videoRef = useRef(null);
|
||||
const resolvedUsername = Array.isArray(username) ? username[0] : username;
|
||||
const { streamInfo: userInfo } = useUserStreamInfo(resolvedUsername, true, 5000);
|
||||
|
||||
const videoRef = useRef<HlsVideoElement | null>(null);
|
||||
const waitingTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const lastRecoveryAtRef = useRef(0);
|
||||
const [playerKey, setPlayerKey] = useState(0);
|
||||
const [isRecovering, setIsRecovering] = useState(false);
|
||||
|
||||
const streamSrc = useMemo(() => {
|
||||
if (!resolvedUsername || !userInfo?.isLive || !userInfo.streamRegion) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return `${getMediamtxClientEnvs(userInfo.streamRegion as MediaMTXRegion).publicUrl}/${resolvedUsername}/index.m3u8?reload=${playerKey}`;
|
||||
}, [playerKey, resolvedUsername, userInfo?.isLive, userInfo?.streamRegion]);
|
||||
|
||||
const clearWaitingTimeout = useCallback(() => {
|
||||
if (waitingTimeoutRef.current) {
|
||||
clearTimeout(waitingTimeoutRef.current);
|
||||
waitingTimeoutRef.current = null;
|
||||
}
|
||||
}, []);
|
||||
|
||||
const triggerRecovery = useCallback(
|
||||
(reason: string) => {
|
||||
if (!session || !resolvedUsername || !userInfo?.isLive) {
|
||||
return;
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
if (now - lastRecoveryAtRef.current < RECOVERY_COOLDOWN_MS) {
|
||||
return;
|
||||
}
|
||||
|
||||
lastRecoveryAtRef.current = now;
|
||||
clearWaitingTimeout();
|
||||
setIsRecovering(true);
|
||||
setPlayerKey((currentKey) => currentKey + 1);
|
||||
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
console.debug('[StreamPlayer] Recovering playback', {
|
||||
reason,
|
||||
username: resolvedUsername,
|
||||
});
|
||||
}
|
||||
},
|
||||
[clearWaitingTimeout, resolvedUsername, session, userInfo?.isLive]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isRecovering) {
|
||||
return;
|
||||
}
|
||||
|
||||
const timeout = setTimeout(() => {
|
||||
setIsRecovering(false);
|
||||
}, 1200);
|
||||
|
||||
return () => clearTimeout(timeout);
|
||||
}, [isRecovering]);
|
||||
|
||||
useEffect(() => {
|
||||
const video = videoRef.current;
|
||||
if (video && username && session) {
|
||||
if (video && streamSrc && session) {
|
||||
const user = 'skibiditoilet';
|
||||
const credentials = btoa(`${user}:${session.id}`);
|
||||
|
||||
// @ts-ignore
|
||||
video.config = {
|
||||
xhrSetup: (xhr: XMLHttpRequest) => {
|
||||
xhr.setRequestHeader('Authorization', `Basic ${credentials}`);
|
||||
@@ -38,42 +104,115 @@ export default function StreamPlayer() {
|
||||
debug: process.env.NODE_ENV === 'development',
|
||||
backBufferLength: 90,
|
||||
enableWorker: true,
|
||||
maxLiveSyncPlaybackRate: 1.5,
|
||||
maxLiveSyncPlaybackRate: 1,
|
||||
liveSyncDurationCount: 2,
|
||||
liveMaxLatencyDurationCount: 4,
|
||||
};
|
||||
|
||||
// @ts-ignore
|
||||
video.src = `${getMediamtxClientEnvs(userInfo?.streamRegion!).publicUrl}/${username}/index.m3u8`;
|
||||
video.src = streamSrc;
|
||||
video.load();
|
||||
|
||||
void video.play().catch(() => {
|
||||
// Ignore autoplay rejections; the controls remain available for manual playback.
|
||||
});
|
||||
} else if (video) {
|
||||
clearWaitingTimeout();
|
||||
video.removeAttribute('src');
|
||||
video.load();
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (video) {
|
||||
// @ts-ignore
|
||||
video.src = '';
|
||||
clearWaitingTimeout();
|
||||
video.removeAttribute('src');
|
||||
video.load();
|
||||
}
|
||||
};
|
||||
}, [username, session]);
|
||||
}, [clearWaitingTimeout, session, streamSrc]);
|
||||
|
||||
useEffect(() => {
|
||||
const video = videoRef.current;
|
||||
if (!video) {
|
||||
return;
|
||||
}
|
||||
|
||||
const handleWaiting = () => {
|
||||
clearWaitingTimeout();
|
||||
waitingTimeoutRef.current = setTimeout(() => {
|
||||
triggerRecovery('waiting_timeout');
|
||||
}, WAITING_RECOVERY_DELAY_MS);
|
||||
};
|
||||
|
||||
const clearRecoverySignals = () => {
|
||||
clearWaitingTimeout();
|
||||
setIsRecovering(false);
|
||||
};
|
||||
|
||||
const handlePlaybackFailure = () => {
|
||||
triggerRecovery('media_event');
|
||||
};
|
||||
|
||||
video.addEventListener('waiting', handleWaiting);
|
||||
video.addEventListener('stalled', handlePlaybackFailure);
|
||||
video.addEventListener('error', handlePlaybackFailure);
|
||||
video.addEventListener('abort', handlePlaybackFailure);
|
||||
video.addEventListener('emptied', handlePlaybackFailure);
|
||||
video.addEventListener('ended', handlePlaybackFailure);
|
||||
video.addEventListener('playing', clearRecoverySignals);
|
||||
video.addEventListener('canplay', clearRecoverySignals);
|
||||
video.addEventListener('loadeddata', clearRecoverySignals);
|
||||
|
||||
return () => {
|
||||
clearWaitingTimeout();
|
||||
video.removeEventListener('waiting', handleWaiting);
|
||||
video.removeEventListener('stalled', handlePlaybackFailure);
|
||||
video.removeEventListener('error', handlePlaybackFailure);
|
||||
video.removeEventListener('abort', handlePlaybackFailure);
|
||||
video.removeEventListener('emptied', handlePlaybackFailure);
|
||||
video.removeEventListener('ended', handlePlaybackFailure);
|
||||
video.removeEventListener('playing', clearRecoverySignals);
|
||||
video.removeEventListener('canplay', clearRecoverySignals);
|
||||
video.removeEventListener('loadeddata', clearRecoverySignals);
|
||||
};
|
||||
}, [clearWaitingTimeout, playerKey, triggerRecovery]);
|
||||
|
||||
return (
|
||||
<MediaController className="w-full aspect-video">
|
||||
<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">
|
||||
<MediaPlayButton />
|
||||
<MediaMuteButton />
|
||||
<MediaVolumeRange />
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<MediaFullscreenButton />
|
||||
</div>
|
||||
</MediaControlBar>
|
||||
</MediaController>
|
||||
<div className="relative flex h-full w-full min-w-0 items-center justify-center bg-black">
|
||||
<MediaController className="h-full w-full">
|
||||
<HlsVideo
|
||||
key={playerKey}
|
||||
ref={videoRef}
|
||||
slot="media"
|
||||
crossOrigin="anonymous"
|
||||
playsInline
|
||||
autoplay
|
||||
className="h-full w-full object-contain"
|
||||
/>
|
||||
<MediaLoadingIndicator slot="centered-chrome" noAutohide />
|
||||
<MediaControlBar className="w-full px-2 sm:px-4 pb-1">
|
||||
<div className="flex items-center gap-1 sm:gap-4">
|
||||
<div className="flex items-center">
|
||||
<MediaPlayButton />
|
||||
<MediaMuteButton />
|
||||
<MediaVolumeRange className="hidden sm:block opacity-80 hover:opacity-100 transition-opacity pl-4" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-1 sm:gap-2">
|
||||
{(process.env.NODE_ENV === 'development' || userInfo?.isLive) && (
|
||||
<MediaChromeButton onClick={() => triggerRecovery('manual_reload')}>
|
||||
<span className="flex h-4 w-4 items-center justify-center">
|
||||
<RefreshCw
|
||||
className={cn('h-5 w-5 shrink-0', isRecovering && 'animate-spin')}
|
||||
strokeWidth={2.5}
|
||||
/>
|
||||
</span>
|
||||
<span slot="tooltip-content">Retry stream</span>
|
||||
</MediaChromeButton>
|
||||
)}
|
||||
<MediaFullscreenButton />
|
||||
</div>
|
||||
</MediaControlBar>
|
||||
</MediaController>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -18,9 +18,9 @@ export function ThemeSwitcher() {
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="outline" size="icon">
|
||||
<Sun className="h-[1.2rem] w-[1.2rem] rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0" />
|
||||
<Moon className="absolute h-[1.2rem] w-[1.2rem] rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100" />
|
||||
<Button variant="ghost" size="smicon">
|
||||
<Sun className="h-4 w-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0" />
|
||||
<Moon className="absolute h-4 w-4 rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100" />
|
||||
<span className="sr-only">Toggle theme</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
'use client';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { Path, useForm } from 'react-hook-form';
|
||||
import { FieldValues, Path, useForm } from 'react-hook-form';
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
@@ -11,7 +11,6 @@ import {
|
||||
FormMessage,
|
||||
} from '@/components/ui/form';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { z } from 'zod';
|
||||
import type { UniversalFormProps } from './types';
|
||||
import SubmitButton from '../SubmitButton/SubmitButton';
|
||||
import { useActionState } from 'react';
|
||||
@@ -28,6 +27,7 @@ import {
|
||||
streamInfoEditSchema,
|
||||
updateChatModerationSchema,
|
||||
updateChannelSettingsSchema,
|
||||
updateNotificationChannelsSchema,
|
||||
} from '@/lib/form/zod';
|
||||
|
||||
export const schemaDb = [
|
||||
@@ -39,19 +39,21 @@ export const schemaDb = [
|
||||
{ name: 'editBot', zod: editBotSchema },
|
||||
{ name: 'changeUsername', zod: changeUsernameSchema },
|
||||
{ name: 'updateChatModeration', zod: updateChatModerationSchema },
|
||||
{ name: 'updateNotificationChannels', zod: updateNotificationChannelsSchema },
|
||||
] as const;
|
||||
|
||||
export function UniversalForm<T extends z.ZodType>({
|
||||
export function UniversalForm({
|
||||
fields,
|
||||
schemaName,
|
||||
action,
|
||||
onActionComplete,
|
||||
defaultValues,
|
||||
formRef,
|
||||
submitText = 'Submit',
|
||||
submitClassname,
|
||||
otherSubmitButton,
|
||||
submitButtonDivClassname,
|
||||
}: UniversalFormProps<T>) {
|
||||
}: UniversalFormProps) {
|
||||
// @ts-expect-error - idk
|
||||
const [state, formAction] = useActionState<{ success: boolean; error?: string }>(action, null);
|
||||
const schema = schemaDb.find((s) => s.name === schemaName)?.zod;
|
||||
@@ -69,11 +71,9 @@ export function UniversalForm<T extends z.ZodType>({
|
||||
return { ...values, ...defaultValues };
|
||||
}, [fields, defaultValues]);
|
||||
|
||||
type FormData = z.infer<T>;
|
||||
|
||||
const form = useForm<FormData>({
|
||||
const form = useForm<FieldValues>({
|
||||
resolver: zodResolver(schema as any),
|
||||
defaultValues: initialValues as FormData,
|
||||
defaultValues: initialValues,
|
||||
});
|
||||
|
||||
React.useEffect(() => {
|
||||
@@ -87,12 +87,12 @@ export function UniversalForm<T extends z.ZodType>({
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form action={formAction} className="space-y-2">
|
||||
<form ref={formRef} action={formAction} className="space-y-2">
|
||||
{fields.map((field) => (
|
||||
<FormField
|
||||
key={field.name}
|
||||
control={form.control}
|
||||
name={field.name as Path<FormData>}
|
||||
name={field.name as Path<FieldValues>}
|
||||
render={({ field: formField }) => (
|
||||
<FormItem className={field.type === 'hidden' ? 'hidden' : undefined}>
|
||||
{field.type !== 'hidden' && field.label && <FormLabel>{field.label}</FormLabel>}
|
||||
|
||||
@@ -1,32 +1,38 @@
|
||||
import { z } from 'zod';
|
||||
import { HTMLInputTypeAttribute } from 'react';
|
||||
import { ControllerRenderProps } from 'react-hook-form';
|
||||
import type { HTMLInputTypeAttribute, Ref } from 'react';
|
||||
import { ControllerRenderProps, FieldValues } from 'react-hook-form';
|
||||
import { schemaDb } from './UniversalForm';
|
||||
|
||||
type FormFieldValue = string | number | boolean | null | undefined;
|
||||
|
||||
export type FormFieldConfig = {
|
||||
name: string;
|
||||
label?: string;
|
||||
type?: HTMLInputTypeAttribute;
|
||||
placeholder?: string;
|
||||
description?: string;
|
||||
value?: any;
|
||||
value?: FormFieldValue;
|
||||
textArea?: boolean;
|
||||
textAreaRows?: number;
|
||||
maxChars?: number;
|
||||
inputFilter?: RegExp;
|
||||
component?: (props: { field: ControllerRenderProps<any, any> } & any) => React.ReactNode;
|
||||
component?: (
|
||||
props: {
|
||||
field: ControllerRenderProps<FieldValues>;
|
||||
} & Record<string, unknown>
|
||||
) => React.ReactNode;
|
||||
componentProps?: Record<string, any>;
|
||||
required?: boolean;
|
||||
};
|
||||
|
||||
export type UniversalFormProps<T extends z.ZodType> = {
|
||||
export type UniversalFormProps = {
|
||||
fields: FormFieldConfig[];
|
||||
schemaName: (typeof schemaDb)[number]['name'];
|
||||
action: (prev: any, formData: FormData) => void;
|
||||
onActionComplete?: (result: any) => void;
|
||||
defaultValues?: Partial<z.infer<T>>;
|
||||
defaultValues?: Partial<FieldValues>;
|
||||
formRef?: Ref<HTMLFormElement>;
|
||||
submitText?: string;
|
||||
submitClassname?: string;
|
||||
otherSubmitButton?: React.ReactNode;
|
||||
submitButtonDivClassname?: string;
|
||||
};
|
||||
};
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -8,7 +8,7 @@ import { Preview } from '@/components/ui/channel-desc-fancy-area/preview';
|
||||
|
||||
export default function UserInfoCard(props: Props) {
|
||||
return (
|
||||
<div className="bg-mantle p-4 border-b h-48 flex flex-col">
|
||||
<div className="bg-mantle p-4 border-b h-48 shrink-0 flex flex-col">
|
||||
<div className="flex items-start justify-between mb-4 flex-shrink-0">
|
||||
<div className="flex items-center space-x-4">
|
||||
<Avatar className="h-16 w-16">
|
||||
|
||||
@@ -26,7 +26,6 @@ export function useProcessor(md: string) {
|
||||
mention: ["handle"],
|
||||
},
|
||||
})
|
||||
// @ts-expect-error because mention is not valid html-tag
|
||||
.use(rehypeReact, {
|
||||
createElement,
|
||||
Fragment,
|
||||
@@ -37,7 +36,7 @@ export function useProcessor(md: string) {
|
||||
},
|
||||
})
|
||||
.process(text)
|
||||
.then((file) => {
|
||||
.then((file: { result: React.ReactNode }) => {
|
||||
setContent(file.result);
|
||||
});
|
||||
}, [text]);
|
||||
|
||||
@@ -141,7 +141,7 @@ const SidebarProvider = React.forwardRef<
|
||||
} as React.CSSProperties
|
||||
}
|
||||
className={cn(
|
||||
"group/sidebar-wrapper flex min-h-svh has-[[data-variant=inset]]:bg-sidebar",
|
||||
"group/sidebar-wrapper flex min-h-svh flex-col has-[[data-variant=inset]]:bg-sidebar",
|
||||
className
|
||||
)}
|
||||
ref={ref}
|
||||
@@ -181,7 +181,7 @@ const Sidebar = React.forwardRef<
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex h-full w-[--sidebar-width] flex-col bg-sidebar text-sidebar-foreground",
|
||||
"flex h-full w-[var(--sidebar-width)] flex-col bg-sidebar text-sidebar-foreground",
|
||||
className
|
||||
)}
|
||||
ref={ref}
|
||||
@@ -198,7 +198,7 @@ const Sidebar = React.forwardRef<
|
||||
<SheetContent
|
||||
data-sidebar="sidebar"
|
||||
data-mobile="true"
|
||||
className="w-[--sidebar-width] bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden"
|
||||
className="w-[var(--sidebar-width)] bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden"
|
||||
style={
|
||||
{
|
||||
"--sidebar-width": SIDEBAR_WIDTH_MOBILE,
|
||||
@@ -224,24 +224,24 @@ const Sidebar = React.forwardRef<
|
||||
{/* This is what handles the sidebar gap on desktop */}
|
||||
<div
|
||||
className={cn(
|
||||
"duration-200 relative h-[calc(100vh-4rem)] w-[--sidebar-width] transition-[left,right,width] ease-linear md:flex",
|
||||
"duration-200 relative h-[calc(100vh-4rem)] w-[var(--sidebar-width)] transition-[left,right,width] ease-linear md:flex",
|
||||
"group-data-[collapsible=offcanvas]:w-0",
|
||||
"group-data-[side=right]:rotate-180",
|
||||
variant === "floating" || variant === "inset"
|
||||
? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4))]"
|
||||
: "group-data-[collapsible=icon]:w-[--sidebar-width-icon]"
|
||||
? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+var(--spacing)*4)]"
|
||||
: "group-data-[collapsible=icon]:w-[var(--sidebar-width-icon)]"
|
||||
)}
|
||||
/>
|
||||
<div
|
||||
className={cn(
|
||||
"duration-200 fixed inset-y-0 z-10 hidden h-svh w-[--sidebar-width] transition-[left,right,width] ease-linear md:flex",
|
||||
"duration-200 fixed inset-y-0 z-10 hidden h-svh w-[var(--sidebar-width)] transition-[left,right,width] ease-linear md:flex",
|
||||
side === "left"
|
||||
? "left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]"
|
||||
: "right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",
|
||||
// Adjust the padding for floating and inset variants.
|
||||
variant === "floating" || variant === "inset"
|
||||
? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4)_+2px)]"
|
||||
: "group-data-[collapsible=icon]:w-[--sidebar-width-icon] group-data-[side=left]:border-r group-data-[side=right]:border-l",
|
||||
? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+var(--spacing)*4+2px)]"
|
||||
: "group-data-[collapsible=icon]:w-[var(--sidebar-width-icon)] group-data-[side=left]:border-r group-data-[side=right]:border-l",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
@@ -323,7 +323,7 @@ const SidebarInset = React.forwardRef<
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative flex min-h-svh flex-1 flex-col bg-background",
|
||||
"peer-data-[variant=inset]:min-h-[calc(100svh-theme(spacing.4))] md:peer-data-[variant=inset]:m-2 md:peer-data-[state=collapsed]:peer-data-[variant=inset]:ml-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow",
|
||||
"peer-data-[variant=inset]:min-h-[calc(100svh-var(--spacing)*4)] md:peer-data-[variant=inset]:m-2 md:peer-data-[state=collapsed]:peer-data-[variant=inset]:ml-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
@@ -518,7 +518,7 @@ const sidebarMenuButtonVariants = cva(
|
||||
variant: {
|
||||
default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
|
||||
outline:
|
||||
"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]",
|
||||
"bg-background shadow-[0_0_0_1px_var(--sidebar-border)] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_var(--sidebar-accent)]",
|
||||
},
|
||||
size: {
|
||||
default: "h-8 text-sm",
|
||||
@@ -669,7 +669,7 @@ const SidebarMenuSkeleton = React.forwardRef<
|
||||
/>
|
||||
)}
|
||||
<Skeleton
|
||||
className="h-4 flex-1 max-w-[--skeleton-width]"
|
||||
className="h-4 flex-1 max-w-[var(--skeleton-width)]"
|
||||
data-sidebar="menu-skeleton-text"
|
||||
style={
|
||||
{
|
||||
|
||||
BIN
apps/web/src/lib/assets/blahaj-heart.webp
Normal file
|
After Width: | Height: | Size: 3.7 KiB |
BIN
apps/web/src/lib/assets/logo.webp
Normal file
|
After Width: | Height: | Size: 26 KiB |
@@ -13,6 +13,7 @@ import {
|
||||
streamInfoEditSchema,
|
||||
updateChatModerationSchema,
|
||||
updateChannelSettingsSchema,
|
||||
updateNotificationChannelsSchema,
|
||||
} from './zod';
|
||||
import { initializeStreamInfo } from '../instrumentation/streamInfo';
|
||||
import {
|
||||
@@ -23,6 +24,7 @@ import {
|
||||
import { can } from '../auth/abac';
|
||||
import { genIdenticonUpload } from '../utils/genIdenticonUpload';
|
||||
import { generateStreamKey } from '../db/streamKey';
|
||||
import slackNotifierClient from '../services/slackNotifier';
|
||||
|
||||
export async function editStreamInfo(prev: any, formData: FormData) {
|
||||
const { user } = await validateRequest();
|
||||
@@ -373,7 +375,7 @@ export async function addChatBotModerator(channelId: string, botId: string) {
|
||||
|
||||
const bot = await prisma.botAccount.findUnique({
|
||||
where: { id: botId },
|
||||
select: { id: true, ownerId: true },
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
if (!bot) {
|
||||
@@ -384,14 +386,6 @@ export async function addChatBotModerator(channelId: string, botId: string) {
|
||||
return { success: false, error: 'Bot is already a chat moderator' };
|
||||
}
|
||||
|
||||
const canUseBot =
|
||||
bot.ownerId === channel.ownerId ||
|
||||
channel.managers.some((manager) => manager.id === bot.ownerId);
|
||||
|
||||
if (!canUseBot) {
|
||||
return { success: false, error: 'Bot owner must be a channel manager or owner' };
|
||||
}
|
||||
|
||||
await prisma.channel.update({
|
||||
where: { id: channelId },
|
||||
data: {
|
||||
@@ -622,7 +616,7 @@ export async function createBot(prev: any, formData: FormData) {
|
||||
slug: zod.data.slug,
|
||||
ownerId: user.id,
|
||||
description: zod.data.description,
|
||||
pfpUrl: await genIdenticonUpload(zod.data.slug, 'botpfp'),
|
||||
pfpUrl: await genIdenticonUpload(zod.data.slug, 'botpfp'),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -655,14 +649,21 @@ export async function editBot(prev: any, formData: FormData) {
|
||||
if (botExists) {
|
||||
return { success: false, error: 'Bot slug already exists' };
|
||||
}
|
||||
}
|
||||
|
||||
if (zod.data.pfpUrl === '') {
|
||||
const identicon = await genIdenticonUpload(zod.data.name, 'pfp');
|
||||
zod.data.pfpUrl = identicon;
|
||||
}
|
||||
|
||||
// i feel like you could just append the data instead of manually changing each field but oh well
|
||||
const updatedBot = await prisma.botAccount.update({
|
||||
where: { id: zod.data.from },
|
||||
data: {
|
||||
displayName: zod.data.name,
|
||||
slug: zod.data.slug,
|
||||
description: zod.data.description,
|
||||
pfpUrl: zod.data.pfpUrl,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -792,3 +793,56 @@ export async function changeUsername(prev: any, formData: FormData) {
|
||||
return { success: false, error: 'Failed to change username. Please try again.' };
|
||||
}
|
||||
}
|
||||
|
||||
export async function updateNotificationChannels(prev: any, formData: FormData) {
|
||||
const { user } = await validateRequest();
|
||||
if (!user) {
|
||||
return { success: false, error: 'Unauthorized' };
|
||||
}
|
||||
|
||||
const zod = await zodVerify(updateNotificationChannelsSchema, formData);
|
||||
if (!zod.success) {
|
||||
return zod;
|
||||
}
|
||||
|
||||
const channel = await prisma.channel.findUnique({
|
||||
where: { id: zod.data.channelId },
|
||||
include: {
|
||||
owner: true,
|
||||
managers: true,
|
||||
streamInfo: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!channel) {
|
||||
return { success: false, error: 'Channel not found' };
|
||||
}
|
||||
|
||||
if (!can(user, 'update', 'channel', { channel })) {
|
||||
return { success: false, error: 'Unauthorized' };
|
||||
}
|
||||
|
||||
const newDifference = zod.data.channels.filter((c: string) => !channel.notifChannels.includes(c));
|
||||
for (const channelId of newDifference) {
|
||||
try {
|
||||
await slackNotifierClient.chat.postMessage({
|
||||
channel: channelId,
|
||||
text: `:yay: I'll send livestream notifications for <https://hackclub.tv/${channel.name}|${channel.name}> here from now on!`,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Failed to validate Slack notification channel:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: `Failed to send a test notification to ${channelId}. Check that the channel ID is valid and that the bot has access, then try again.`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
await prisma.channel.updateMany({
|
||||
where: { id: channel.id },
|
||||
data: { notifChannels: zod.data.channels },
|
||||
});
|
||||
|
||||
revalidatePath(`/settings/channel/${channel.name}`);
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
@@ -57,6 +50,7 @@ export const createBotSchema = z.object({
|
||||
export const editBotSchema = createBotSchema.and(
|
||||
z.object({
|
||||
from: z.string().min(1),
|
||||
pfpUrl: z.string(),
|
||||
})
|
||||
);
|
||||
|
||||
@@ -64,3 +58,23 @@ export const changeUsernameSchema = z.object({
|
||||
channelId: z.string().min(1),
|
||||
newUsername: username,
|
||||
});
|
||||
|
||||
const notificationChannelsSchema = z
|
||||
.union([z.string(), z.array(z.string())])
|
||||
.transform((value) => {
|
||||
if (typeof value === 'string') {
|
||||
return value
|
||||
.replace(/\r\n/g, '\n')
|
||||
.split('\n')
|
||||
.map((channel) => channel.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
return value.map((channel) => channel.trim()).filter(Boolean);
|
||||
})
|
||||
.pipe(z.array(z.string()).max(10));
|
||||
|
||||
export const updateNotificationChannelsSchema = z.object({
|
||||
channelId: z.string().min(1),
|
||||
channels: notificationChannelsSchema,
|
||||
});
|
||||
|
||||
81
apps/web/src/lib/hooks/useChannelStreamKey.ts
Normal file
@@ -0,0 +1,81 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback } from 'react';
|
||||
import useSWR from 'swr';
|
||||
import useSWRMutation from 'swr/mutation';
|
||||
|
||||
interface StreamKeyResponse {
|
||||
key: string;
|
||||
}
|
||||
|
||||
async function parseStreamKeyResponse(response: Response): Promise<StreamKeyResponse> {
|
||||
if (!response.ok) {
|
||||
const message = await response.text();
|
||||
throw new Error(message || 'Failed to load stream key');
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
async function fetchStreamKey(
|
||||
[url, channelName]: readonly [string, string]
|
||||
): Promise<StreamKeyResponse> {
|
||||
const response = await fetch(`${url}?channel=${encodeURIComponent(channelName)}`);
|
||||
return parseStreamKeyResponse(response);
|
||||
}
|
||||
|
||||
async function regenerateStreamKey(
|
||||
url: string,
|
||||
{ arg: channelName }: { arg: string }
|
||||
): Promise<StreamKeyResponse> {
|
||||
const response = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ channel: channelName }),
|
||||
});
|
||||
|
||||
return parseStreamKeyResponse(response);
|
||||
}
|
||||
|
||||
export function useChannelStreamKey(channelName?: string, initialKey?: string | null) {
|
||||
const swrKey = channelName ? (['/api/rtmp/streamKey', channelName] as const) : null;
|
||||
const { data, error, isLoading, isValidating, mutate } = useSWR<StreamKeyResponse>(
|
||||
swrKey,
|
||||
fetchStreamKey,
|
||||
{
|
||||
fallbackData: initialKey ? { key: initialKey } : undefined,
|
||||
revalidateOnFocus: false,
|
||||
}
|
||||
);
|
||||
const { trigger, isMutating } = useSWRMutation('/api/rtmp/streamKey', regenerateStreamKey);
|
||||
|
||||
const refreshStreamKey = useCallback(async () => {
|
||||
if (!channelName) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return mutate();
|
||||
}, [channelName, mutate]);
|
||||
|
||||
const handleRegenerateStreamKey = useCallback(async () => {
|
||||
if (!channelName) {
|
||||
throw new Error('Select a channel before regenerating its stream key');
|
||||
}
|
||||
|
||||
const nextStreamKey = await trigger(channelName);
|
||||
await mutate(nextStreamKey, { revalidate: false });
|
||||
return nextStreamKey.key;
|
||||
}, [channelName, mutate, trigger]);
|
||||
|
||||
return {
|
||||
streamKey: data?.key ?? initialKey ?? '',
|
||||
error,
|
||||
isLoading,
|
||||
isRefreshing: isValidating && !isLoading,
|
||||
isRegenerating: isMutating,
|
||||
refreshStreamKey,
|
||||
regenerateStreamKey: handleRegenerateStreamKey,
|
||||
};
|
||||
}
|
||||
440
apps/web/src/lib/hooks/useScreensharePublisher.ts
Normal file
@@ -0,0 +1,440 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { getMediamtxClientEnvs } from '@/lib/utils/mediamtx/client';
|
||||
import type { MediaMTXRegion } from '@/lib/utils/mediamtx/regions';
|
||||
import MediaMTXWebRTCPublisher from '@/lib/utils/mediamtx/webrtc';
|
||||
|
||||
const HLS_COMPATIBLE_VIDEO_CODECS = [
|
||||
['h264', 'h264/90000'],
|
||||
['vp9', 'vp9/90000'],
|
||||
['av1', 'av1/90000'],
|
||||
['h265', 'h265/90000'],
|
||||
] as const;
|
||||
|
||||
const DISPLAY_MEDIA_OPTIONS: ScreenCaptureOptions = {
|
||||
video: true,
|
||||
audio: true,
|
||||
monitorTypeSurfaces: 'include',
|
||||
selfBrowserSurface: 'exclude',
|
||||
surfaceSwitching: 'include',
|
||||
systemAudio: 'include',
|
||||
};
|
||||
|
||||
export function useScreensharePublisher({
|
||||
channelName,
|
||||
region,
|
||||
streamKey,
|
||||
}: UseScreensharePublisherOptions) {
|
||||
const previewRef = useRef<HTMLVideoElement>(null);
|
||||
const captureStreamRef = useRef<MediaStream | null>(null);
|
||||
const captureCleanupRef = useRef<(() => void) | null>(null);
|
||||
const publisherRef = useRef<MediaMTXWebRTCPublisher | null>(null);
|
||||
const [publishState, setPublishState] = useState<PublishState>('idle');
|
||||
const [hasPreview, setHasPreview] = useState(false);
|
||||
const [issue, setIssue] = useState<PublisherIssue | null>(null);
|
||||
const browserWarning = useMemo(() => getBrowserWarning(), []);
|
||||
|
||||
const setPreviewStream = useCallback((stream: MediaStream | null) => {
|
||||
if (previewRef.current) {
|
||||
previewRef.current.srcObject = stream;
|
||||
}
|
||||
}, []);
|
||||
|
||||
const detachCaptureCleanup = useCallback(() => {
|
||||
captureCleanupRef.current?.();
|
||||
captureCleanupRef.current = null;
|
||||
}, []);
|
||||
|
||||
const clearCaptureStream = useCallback(() => {
|
||||
detachCaptureCleanup();
|
||||
stopTracks(captureStreamRef.current);
|
||||
captureStreamRef.current = null;
|
||||
setHasPreview(false);
|
||||
setPreviewStream(null);
|
||||
}, [detachCaptureCleanup, setPreviewStream]);
|
||||
|
||||
const closePublisher = useCallback(() => {
|
||||
const publisher = publisherRef.current;
|
||||
|
||||
publisherRef.current = null;
|
||||
publisher?.close();
|
||||
}, []);
|
||||
|
||||
const disposeCurrentSession = useCallback(() => {
|
||||
closePublisher();
|
||||
clearCaptureStream();
|
||||
}, [clearCaptureStream, closePublisher]);
|
||||
|
||||
const stopPublishing = useCallback(() => {
|
||||
disposeCurrentSession();
|
||||
setIssue(null);
|
||||
setPublishState('idle');
|
||||
}, [disposeCurrentSession]);
|
||||
|
||||
const attachCaptureStopListener = useCallback(
|
||||
(stream: MediaStream) => {
|
||||
const [videoTrack] = stream.getVideoTracks();
|
||||
|
||||
if (!videoTrack) {
|
||||
captureCleanupRef.current = null;
|
||||
return;
|
||||
}
|
||||
|
||||
const handleEnded = () => {
|
||||
stopPublishing();
|
||||
};
|
||||
|
||||
videoTrack.addEventListener('ended', handleEnded);
|
||||
captureCleanupRef.current = () => {
|
||||
videoTrack.removeEventListener('ended', handleEnded);
|
||||
};
|
||||
},
|
||||
[stopPublishing]
|
||||
);
|
||||
|
||||
const commitCaptureStream = useCallback(
|
||||
(nextStream: MediaStream) => {
|
||||
const previousStream = captureStreamRef.current;
|
||||
|
||||
detachCaptureCleanup();
|
||||
captureStreamRef.current = nextStream;
|
||||
setHasPreview(true);
|
||||
setPreviewStream(nextStream);
|
||||
attachCaptureStopListener(nextStream);
|
||||
stopTracks(previousStream);
|
||||
},
|
||||
[attachCaptureStopListener, detachCaptureCleanup, setPreviewStream]
|
||||
);
|
||||
|
||||
const previewSource = useCallback(async () => {
|
||||
try {
|
||||
setIssue(null);
|
||||
setPublishState('previewing');
|
||||
|
||||
const stream = await requestCaptureStream();
|
||||
|
||||
commitCaptureStream(stream);
|
||||
setPublishState('preview');
|
||||
} catch (err) {
|
||||
setPublishState(captureStreamRef.current ? 'preview' : 'idle');
|
||||
setIssue(classifyPublisherIssue(err, 'preview'));
|
||||
}
|
||||
}, [commitCaptureStream]);
|
||||
|
||||
const startPublishing = useCallback(async () => {
|
||||
if (!channelName) {
|
||||
setIssue({
|
||||
context: 'start',
|
||||
description: 'Pick a channel first so we know where to publish.',
|
||||
title: 'Choose a channel before starting',
|
||||
tone: 'warning',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (!streamKey) {
|
||||
setIssue({
|
||||
context: 'start',
|
||||
description: 'Wait for the stream key to load, then try starting again.',
|
||||
title: 'Stream key is still unavailable',
|
||||
tone: 'warning',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setIssue(null);
|
||||
setPublishState('connecting');
|
||||
|
||||
const videoCodec = await getPreferredVideoCodec();
|
||||
let stream = captureStreamRef.current;
|
||||
|
||||
if (!stream) {
|
||||
stream = await requestCaptureStream();
|
||||
commitCaptureStream(stream);
|
||||
}
|
||||
|
||||
const publisher = new MediaMTXWebRTCPublisher({
|
||||
url: getWhipUrl(channelName, region),
|
||||
stream,
|
||||
videoCodec,
|
||||
videoBitrate: 2000,
|
||||
audioCodec: 'opus',
|
||||
audioBitrate: 64,
|
||||
audioVoice: true,
|
||||
user: 'user',
|
||||
pass: streamKey,
|
||||
onConnected: () => {
|
||||
if (publisherRef.current !== publisher) {
|
||||
return;
|
||||
}
|
||||
|
||||
setPublishState('live');
|
||||
},
|
||||
onError: (message) => {
|
||||
if (publisherRef.current !== publisher) {
|
||||
return;
|
||||
}
|
||||
|
||||
setIssue(classifyPublisherIssue(message, 'publish'));
|
||||
setPublishState('connecting');
|
||||
},
|
||||
});
|
||||
|
||||
publisherRef.current = publisher;
|
||||
} catch (err) {
|
||||
closePublisher();
|
||||
setPublishState(captureStreamRef.current ? 'preview' : 'idle');
|
||||
setIssue(classifyPublisherIssue(err, 'start'));
|
||||
}
|
||||
}, [channelName, closePublisher, commitCaptureStream, region, streamKey]);
|
||||
|
||||
const changeSource = useCallback(async () => {
|
||||
const publisher = publisherRef.current;
|
||||
|
||||
if (!publisher) {
|
||||
return;
|
||||
}
|
||||
|
||||
let nextStream: MediaStream | null = null;
|
||||
|
||||
try {
|
||||
setIssue(null);
|
||||
setPublishState('switching');
|
||||
|
||||
nextStream = await requestCaptureStream();
|
||||
await publisher.replaceStream(nextStream);
|
||||
commitCaptureStream(nextStream);
|
||||
setPublishState('live');
|
||||
} catch (err) {
|
||||
stopTracks(nextStream);
|
||||
setPublishState(publisherRef.current ? 'live' : 'idle');
|
||||
setIssue(classifyPublisherIssue(err, 'switch'));
|
||||
}
|
||||
}, [commitCaptureStream]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
disposeCurrentSession();
|
||||
};
|
||||
}, [disposeCurrentSession]);
|
||||
|
||||
return {
|
||||
browserWarning,
|
||||
changeSource,
|
||||
hasPreview,
|
||||
issue,
|
||||
isLive: publishState === 'live',
|
||||
isPreviewReady: publishState === 'preview',
|
||||
isPreviewingSource: publishState === 'previewing',
|
||||
isSessionActive:
|
||||
publishState === 'connecting' || publishState === 'live' || publishState === 'switching',
|
||||
isStarting: publishState === 'connecting',
|
||||
isSwitchingSource: publishState === 'switching',
|
||||
publishState,
|
||||
previewRef,
|
||||
previewSource,
|
||||
startPublishing,
|
||||
stopPublishing,
|
||||
};
|
||||
}
|
||||
|
||||
async function requestCaptureStream() {
|
||||
return navigator.mediaDevices.getDisplayMedia(DISPLAY_MEDIA_OPTIONS as DisplayMediaStreamOptions);
|
||||
}
|
||||
|
||||
function getWhipUrl(channelName: string, region: MediaMTXRegion) {
|
||||
const { whip } = getMediamtxClientEnvs(region);
|
||||
|
||||
return `${whip.replace(/\/$/, '')}/${encodeURIComponent(channelName)}/whip`;
|
||||
}
|
||||
|
||||
function stopTracks(stream: MediaStream | null) {
|
||||
stream?.getTracks().forEach((track) => track.stop());
|
||||
}
|
||||
|
||||
function getErrorMessage(error: unknown, fallback: string) {
|
||||
return error instanceof Error ? error.message : fallback;
|
||||
}
|
||||
|
||||
function classifyPublisherIssue(error: unknown, context: PublisherIssueContext): PublisherIssue {
|
||||
const message = getErrorMessage(
|
||||
error,
|
||||
context === 'switch'
|
||||
? 'Failed to change screenshare source'
|
||||
: context === 'preview'
|
||||
? 'Failed to preview the selected source'
|
||||
: 'Failed to start publishing'
|
||||
);
|
||||
const normalizedMessage = message.toLowerCase();
|
||||
|
||||
if (normalizedMessage.includes('notallowederror') || normalizedMessage.includes('permission')) {
|
||||
return {
|
||||
context,
|
||||
description:
|
||||
context === 'switch'
|
||||
? 'Choose a new tab, window, or display in the browser picker to continue the broadcast.'
|
||||
: context === 'preview'
|
||||
? 'Approve the browser screen-share prompt so we can load your preview.'
|
||||
: 'Approve the browser screen-share prompt, then try again.',
|
||||
title:
|
||||
context === 'switch'
|
||||
? 'Source switch was cancelled or blocked'
|
||||
: context === 'preview'
|
||||
? 'Preview permission was denied'
|
||||
: 'Screen-share permission was denied',
|
||||
tone: 'warning',
|
||||
};
|
||||
}
|
||||
|
||||
if (normalizedMessage.includes('notfounderror')) {
|
||||
return {
|
||||
context,
|
||||
description:
|
||||
'Open the window or tab you want to capture, then retry the screen-share picker.',
|
||||
title: 'No capturable source was found',
|
||||
tone: 'warning',
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
normalizedMessage.includes('getdisplaymedia') ||
|
||||
normalizedMessage.includes('secure context') ||
|
||||
normalizedMessage.includes('browser environment')
|
||||
) {
|
||||
return {
|
||||
context,
|
||||
description:
|
||||
'Use the platform over HTTPS or localhost in a Chromium-based browser, then try again.',
|
||||
title: 'This browser or page cannot start screen sharing',
|
||||
tone: 'destructive',
|
||||
};
|
||||
}
|
||||
|
||||
if (normalizedMessage.includes('hls-compatible webrtc video codec')) {
|
||||
return {
|
||||
context,
|
||||
description:
|
||||
'Switch to a Chromium-based browser. Firefox and Safari can expose codecs that our ingest pipeline cannot use reliably yet.',
|
||||
title: 'This browser cannot publish a compatible stream codec',
|
||||
tone: 'destructive',
|
||||
};
|
||||
}
|
||||
|
||||
if (normalizedMessage.includes('invalid stream key') || normalizedMessage.includes('403')) {
|
||||
return {
|
||||
context,
|
||||
description:
|
||||
'Refresh the page or regenerate the stream key in channel settings if this keeps happening.',
|
||||
title: 'The ingest server rejected your stream key',
|
||||
tone: 'destructive',
|
||||
};
|
||||
}
|
||||
|
||||
if (normalizedMessage.includes('404')) {
|
||||
return {
|
||||
context,
|
||||
description:
|
||||
'The selected ingest server may be misconfigured or offline. Try another server or retry in a moment.',
|
||||
title: 'The selected ingest server could not be reached',
|
||||
tone: 'destructive',
|
||||
};
|
||||
}
|
||||
|
||||
if (normalizedMessage.includes('retrying in some seconds')) {
|
||||
return {
|
||||
context,
|
||||
description:
|
||||
'We are retrying automatically. Keep this page open, or stop and start again if it does not recover.',
|
||||
title: 'Connection to the ingest server dropped',
|
||||
tone: 'warning',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
context,
|
||||
description:
|
||||
context === 'switch'
|
||||
? 'Try choosing the source again. If it keeps failing, stop the stream and start a new session.'
|
||||
: context === 'preview'
|
||||
? 'Try choosing the source again. If it keeps failing, reload the page or switch browsers.'
|
||||
: 'Try again. If it keeps failing, switch servers or reload the page.',
|
||||
title:
|
||||
context === 'switch'
|
||||
? 'Could not switch the shared source'
|
||||
: context === 'preview'
|
||||
? 'Could not load the preview'
|
||||
: 'Could not start the stream',
|
||||
tone: 'destructive',
|
||||
};
|
||||
}
|
||||
|
||||
function getBrowserWarning(): PublisherIssue | null {
|
||||
if (typeof navigator === 'undefined') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const userAgent = navigator.userAgent.toLowerCase();
|
||||
const isChromium =
|
||||
userAgent.includes('chrome') || userAgent.includes('chromium') || userAgent.includes('edg/');
|
||||
|
||||
if (isChromium) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
context: 'warning',
|
||||
description:
|
||||
'You can still try this here, but screen capture and source switching are most reliable in Chrome or another Chromium-based browser.',
|
||||
title: 'This browser is supported on a best-effort basis',
|
||||
tone: 'warning',
|
||||
};
|
||||
}
|
||||
|
||||
async function getPreferredVideoCodec(): Promise<string> {
|
||||
const tempPc = new RTCPeerConnection();
|
||||
|
||||
try {
|
||||
tempPc.addTransceiver('video', { direction: 'sendonly' });
|
||||
|
||||
const offer = await tempPc.createOffer();
|
||||
const sdp = offer.sdp?.toLowerCase() ?? '';
|
||||
|
||||
for (const [codec, needle] of HLS_COMPATIBLE_VIDEO_CODECS) {
|
||||
if (sdp.includes(needle)) {
|
||||
return codec;
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
tempPc.close();
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
'This browser does not expose an HLS-compatible WebRTC video codec. MediaMTX HLS supports AV1, VP9, H265, and H264, but not VP8.'
|
||||
);
|
||||
}
|
||||
|
||||
type PublishState = 'idle' | 'previewing' | 'preview' | 'connecting' | 'live' | 'switching';
|
||||
|
||||
type UseScreensharePublisherOptions = {
|
||||
channelName: string;
|
||||
region: MediaMTXRegion;
|
||||
streamKey?: string | null;
|
||||
};
|
||||
|
||||
type PublisherIssue = {
|
||||
context: PublisherIssueContext;
|
||||
description: string;
|
||||
title: string;
|
||||
tone: 'warning' | 'destructive';
|
||||
};
|
||||
|
||||
type PublisherIssueContext = 'preview' | 'publish' | 'start' | 'switch' | 'warning';
|
||||
|
||||
type ScreenCaptureOptions = DisplayMediaStreamOptions & {
|
||||
monitorTypeSurfaces?: 'include' | 'exclude';
|
||||
selfBrowserSurface?: 'include' | 'exclude';
|
||||
surfaceSwitching?: 'include' | 'exclude';
|
||||
systemAudio?: 'include' | 'exclude';
|
||||
};
|
||||
@@ -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,155 @@ 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];
|
||||
if (!region) {
|
||||
// continuing bc of the next if check
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
console.error(
|
||||
`Failed to fetch ${r} stream stats: ${response.status} ${response.statusText}`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if (!region.apiAuthHeader) {
|
||||
throw new Error('MEDIAMTX_API_KEY is required when querying the MediaMTX API');
|
||||
}
|
||||
|
||||
type ResponseType =
|
||||
paths['/v3/paths/list']['get']['responses']['200']['content']['application/json'];
|
||||
const data = (await response.json()) as ResponseType;
|
||||
const response = await fetch(`${region.apiUrl}/v3/paths/list?itemsPerPage=1000`, {
|
||||
headers: {
|
||||
Authorization: region.apiAuthHeader,
|
||||
},
|
||||
});
|
||||
|
||||
if (data?.items) {
|
||||
for (const stream of data.items) {
|
||||
if (stream.ready && stream.name) {
|
||||
allActiveStreams.set(stream.name, r);
|
||||
if (!response.ok) {
|
||||
recordStreamSyncScrape(r, 'error');
|
||||
console.error(
|
||||
`Failed to fetch ${r} stream stats: ${response.status} ${response.statusText}`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
recordStreamSyncScrape(r, 'success');
|
||||
|
||||
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: {
|
||||
include: {
|
||||
owner: 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,
|
||||
});
|
||||
|
||||
for (const channelId of existingStream.channel.notifChannels) {
|
||||
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: channelId,
|
||||
unfurl_links: true,
|
||||
metadata: {
|
||||
type: 'custom_stream_announcement',
|
||||
managedChannelId: existingStream.channel.id,
|
||||
ownerSlackId: existingStream.channel.owner.slack_id,
|
||||
ownerChannelName: existingStream.channel.name,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
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
@@ -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,6 +1,6 @@
|
||||
import { createUploadthing, type FileRouter } from "uploadthing/next";
|
||||
import { UploadThingError } from "uploadthing/server";
|
||||
import { validateRequest } from "../../auth/validate";
|
||||
import { createUploadthing, type FileRouter } from 'uploadthing/next';
|
||||
import { UTFiles, UploadThingError } from 'uploadthing/server';
|
||||
import { validateRequest } from '../../auth/validate';
|
||||
|
||||
const f = createUploadthing();
|
||||
|
||||
@@ -9,6 +9,17 @@ const auth = async () => {
|
||||
return req.user;
|
||||
};
|
||||
|
||||
const getRenamedFile = (file: { name: string }) => {
|
||||
const suffix = crypto.randomUUID().replace(/-/g, '').slice(0, 4).toLowerCase();
|
||||
const dotIndex = file.name.lastIndexOf('.');
|
||||
const hasExtension = dotIndex > 0;
|
||||
const rawBaseName = hasExtension ? file.name.slice(0, dotIndex) : file.name;
|
||||
const extension = hasExtension ? file.name.slice(dotIndex) : '';
|
||||
const safeBaseName = rawBaseName.replace(/[^a-zA-Z0-9-_]/g, '-');
|
||||
|
||||
return `pfpup-${safeBaseName}-${suffix}${extension}`;
|
||||
};
|
||||
|
||||
// FileRouter for your app, can contain multiple FileRoutes
|
||||
export const ourFileRouter = {
|
||||
// Define as many FileRoutes as you like, each with a unique routeSlug
|
||||
@@ -18,26 +29,32 @@ export const ourFileRouter = {
|
||||
* For full list of options and defaults, see the File Route API reference
|
||||
* @see https://docs.uploadthing.com/file-routes#route-config
|
||||
*/
|
||||
maxFileSize: "1MB",
|
||||
maxFileSize: '1MB',
|
||||
maxFileCount: 1,
|
||||
},
|
||||
})
|
||||
// Set permissions and file types for this FileRoute
|
||||
.middleware(async () => {
|
||||
.middleware(async ({ files }) => {
|
||||
// This code runs on your server before upload
|
||||
const user = await auth();
|
||||
|
||||
// If you throw, the user will not be able to upload
|
||||
if (!user) throw new UploadThingError("Unauthorized");
|
||||
if (!user) throw new UploadThingError('Unauthorized');
|
||||
|
||||
// Whatever is returned here is accessible in onUploadComplete as `metadata`
|
||||
return { userId: user.id };
|
||||
return {
|
||||
userId: user.id,
|
||||
[UTFiles]: files.map((file) => ({
|
||||
...file,
|
||||
name: getRenamedFile(file),
|
||||
})),
|
||||
};
|
||||
})
|
||||
.onUploadComplete(async ({ metadata, file }) => {
|
||||
// This code RUNS ON YOUR SERVER after upload
|
||||
console.log("Upload complete for userId:", metadata.userId);
|
||||
console.log('Upload complete for userId:', metadata.userId);
|
||||
|
||||
console.log("file url", file.ufsUrl);
|
||||
console.log('file url', file.ufsUrl);
|
||||
|
||||
// !!! Whatever is returned here is sent to the clientside `onClientUploadComplete` callback
|
||||
return { uploadedBy: metadata.userId };
|
||||
|
||||
@@ -4,18 +4,37 @@ import { getEnv } from '@/lib/env';
|
||||
export interface MediaMTXClientEnvs {
|
||||
publicUrl: string;
|
||||
ingestRoute: string;
|
||||
whip: string;
|
||||
whipEnabled: boolean;
|
||||
emoji: string;
|
||||
string: string;
|
||||
}
|
||||
|
||||
export interface MediaMTXClientRegionOption {
|
||||
value: MediaMTXRegion;
|
||||
emoji: string;
|
||||
label: string;
|
||||
whipEnabled: boolean;
|
||||
}
|
||||
|
||||
export function getMediamtxClientEnvs(region: MediaMTXRegion = 'hq'): MediaMTXClientEnvs {
|
||||
const envs: Record<MediaMTXRegion, MediaMTXClientEnvs> = {
|
||||
hq: {
|
||||
publicUrl: getEnv('NEXT_PUBLIC_MEDIAMTX_URL_HQ')!,
|
||||
ingestRoute: getEnv('NEXT_PUBLIC_MEDIAMTX_INGEST_ROUTE_HQ')!,
|
||||
whip: getEnv('NEXT_PUBLIC_MEDIAMTX_WHIP_ROUTE_HQ')!,
|
||||
whipEnabled: false,
|
||||
emoji: '🇺🇸',
|
||||
string: 'HQ Server A',
|
||||
},
|
||||
ethande: {
|
||||
publicUrl: getEnv('NEXT_PUBLIC_MEDIAMTX_URL_ETHANDE')!,
|
||||
ingestRoute: getEnv('NEXT_PUBLIC_MEDIAMTX_INGEST_ROUTE_ETHANDE')!,
|
||||
whip: getEnv('NEXT_PUBLIC_MEDIAMTX_WHIP_ROUTE_ETHANDE')!,
|
||||
whipEnabled: true,
|
||||
emoji: '🇩🇪',
|
||||
string: 'eth0\'s VPS',
|
||||
},
|
||||
};
|
||||
|
||||
const regionEnvs = envs[region];
|
||||
@@ -27,3 +46,19 @@ export function getMediamtxClientEnvs(region: MediaMTXRegion = 'hq'): MediaMTXCl
|
||||
return regionEnvs;
|
||||
}
|
||||
|
||||
export function getMediamtxClientRegionOptions(): MediaMTXClientRegionOption[] {
|
||||
return [
|
||||
{
|
||||
value: 'hq',
|
||||
emoji: '🇺🇸',
|
||||
label: 'HQ Server A',
|
||||
whipEnabled: false,
|
||||
},
|
||||
{
|
||||
value: 'ethande',
|
||||
emoji: '🇩🇪',
|
||||
label: 'eth0\'s VPS',
|
||||
whipEnabled: true,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
@@ -1 +1 @@
|
||||
export type MediaMTXRegion = 'hq';
|
||||
export type MediaMTXRegion = 'hq' | 'ethande';
|
||||
|
||||
@@ -2,12 +2,12 @@ import { MediaMTXRegion } from './regions';
|
||||
|
||||
export interface MediaMTXEnvs {
|
||||
apiUrl: string;
|
||||
apiAuthHeader?: string;
|
||||
}
|
||||
|
||||
export const MEDIAMTX_SERVER_REGIONS: Record<MediaMTXRegion, MediaMTXEnvs> = {
|
||||
hq: {
|
||||
apiUrl: process.env.MEDIAMTX_API_HQ!,
|
||||
},
|
||||
export const MEDIAMTX_SERVER_REGIONS: Partial<Record<MediaMTXRegion, MediaMTXEnvs>> = {
|
||||
hq: createMediamtxEnvs(process.env.MEDIAMTX_API_HQ),
|
||||
ethande: createMediamtxEnvs(process.env.MEDIAMTX_API_ETHANDE),
|
||||
};
|
||||
|
||||
export function getMediamtxEnvs(region: MediaMTXRegion = 'hq'): MediaMTXEnvs {
|
||||
@@ -19,3 +19,24 @@ export function getMediamtxEnvs(region: MediaMTXRegion = 'hq'): MediaMTXEnvs {
|
||||
|
||||
return envs;
|
||||
}
|
||||
|
||||
function getMediamtxApiAuthHeader() {
|
||||
const apiKey = process.env.MEDIAMTX_API_KEY;
|
||||
|
||||
if (!apiKey) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return `Basic ${Buffer.from(`hctv-api:${apiKey}`).toString('base64')}`;
|
||||
}
|
||||
|
||||
function createMediamtxEnvs(apiUrl?: string): MediaMTXEnvs | undefined {
|
||||
if (!apiUrl) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return {
|
||||
apiUrl,
|
||||
apiAuthHeader: getMediamtxApiAuthHeader(),
|
||||
};
|
||||
}
|
||||
|
||||
531
apps/web/src/lib/utils/mediamtx/webrtc.ts
Normal file
@@ -0,0 +1,531 @@
|
||||
// based off https://github.com/bluenviron/mediamtx/blob/v1.17.1/internal/servers/webrtc/publisher.js
|
||||
// modified by codex to typescript and to suit the platform's needs!
|
||||
export type OnError = (err: string) => void;
|
||||
export type OnConnected = () => void;
|
||||
|
||||
export type PublisherState = 'running' | 'restarting' | 'closed';
|
||||
type MediaKind = 'audio' | 'video';
|
||||
|
||||
export type PublisherConfig = {
|
||||
url: string;
|
||||
user?: string;
|
||||
pass?: string;
|
||||
token?: string;
|
||||
stream: MediaStream;
|
||||
videoCodec: string;
|
||||
videoBitrate: number;
|
||||
audioCodec: string;
|
||||
audioBitrate: number;
|
||||
audioVoice: boolean;
|
||||
onError?: OnError;
|
||||
onConnected?: OnConnected;
|
||||
};
|
||||
|
||||
type OfferData = {
|
||||
iceUfrag: string;
|
||||
icePwd: string;
|
||||
medias: string[];
|
||||
};
|
||||
|
||||
type ParsedIceServer = RTCIceServer & {
|
||||
credentialType?: 'password';
|
||||
};
|
||||
|
||||
/** WebRTC/WHIP publisher. */
|
||||
export class MediaMTXWebRTCPublisher {
|
||||
private readonly retryPause = 2000;
|
||||
private readonly conf: PublisherConfig;
|
||||
private stream: MediaStream;
|
||||
private state: PublisherState = 'running';
|
||||
private restartTimeout: ReturnType<typeof setTimeout> | null = null;
|
||||
private pc: RTCPeerConnection | null = null;
|
||||
private offerData: OfferData | null = null;
|
||||
private sessionUrl: string | null = null;
|
||||
private queuedCandidates: RTCIceCandidate[] = [];
|
||||
private trackSenders: Partial<Record<MediaKind, RTCRtpSender>> = {};
|
||||
|
||||
constructor(conf: PublisherConfig) {
|
||||
if (
|
||||
typeof window === 'undefined' ||
|
||||
typeof RTCPeerConnection === 'undefined' ||
|
||||
typeof MediaStream === 'undefined'
|
||||
) {
|
||||
throw new Error('MediaMTXWebRTCPublisher can only be used in a browser environment.');
|
||||
}
|
||||
|
||||
this.conf = conf;
|
||||
this.stream = conf.stream;
|
||||
this.start();
|
||||
}
|
||||
|
||||
close = (): void => {
|
||||
this.state = 'closed';
|
||||
|
||||
if (this.restartTimeout !== null) {
|
||||
clearTimeout(this.restartTimeout);
|
||||
}
|
||||
|
||||
this.resetConnection();
|
||||
this.disposeSession();
|
||||
};
|
||||
|
||||
replaceStream = async (stream: MediaStream): Promise<void> => {
|
||||
if (this.state !== 'running' || this.pc === null) {
|
||||
throw new Error('publisher is not running');
|
||||
}
|
||||
|
||||
const nextTracks: Record<MediaKind, MediaStreamTrack | null> = {
|
||||
audio: stream.getAudioTracks()[0] ?? null,
|
||||
video: stream.getVideoTracks()[0] ?? null,
|
||||
};
|
||||
|
||||
await Promise.all(
|
||||
(['audio', 'video'] as const).map(async (kind) => {
|
||||
const sender = this.trackSenders[kind];
|
||||
|
||||
if (!sender) {
|
||||
return;
|
||||
}
|
||||
|
||||
await sender.replaceTrack(nextTracks[kind]);
|
||||
})
|
||||
);
|
||||
|
||||
this.stream = stream;
|
||||
};
|
||||
|
||||
private resetConnection(): void {
|
||||
if (this.pc !== null) {
|
||||
this.pc.close();
|
||||
this.pc = null;
|
||||
}
|
||||
|
||||
this.offerData = null;
|
||||
this.queuedCandidates = [];
|
||||
this.trackSenders = {};
|
||||
}
|
||||
|
||||
private disposeSession(): void {
|
||||
if (this.sessionUrl !== null) {
|
||||
void fetch(this.sessionUrl, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
this.sessionUrl = null;
|
||||
}
|
||||
}
|
||||
|
||||
static #unquoteCredential(value: string): string {
|
||||
return JSON.parse(`"${value}"`) as string;
|
||||
}
|
||||
|
||||
static #linkToIceServers(links: string | null): ParsedIceServer[] {
|
||||
if (links === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return links.split(', ').flatMap((link) => {
|
||||
const match = link.match(
|
||||
/^<(.+?)>; rel="ice-server"(; username="(.*?)"; credential="(.*?)"; credential-type="password")?/i
|
||||
);
|
||||
|
||||
if (!match) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const iceServer: ParsedIceServer = {
|
||||
urls: [match[1]],
|
||||
};
|
||||
|
||||
if (match[3] !== undefined && match[4] !== undefined) {
|
||||
iceServer.username = this.#unquoteCredential(match[3]);
|
||||
iceServer.credential = this.#unquoteCredential(match[4]);
|
||||
iceServer.credentialType = 'password';
|
||||
}
|
||||
|
||||
return [iceServer];
|
||||
});
|
||||
}
|
||||
|
||||
static #parseOffer(offer: string): OfferData {
|
||||
const parsedOffer: OfferData = {
|
||||
iceUfrag: '',
|
||||
icePwd: '',
|
||||
medias: [],
|
||||
};
|
||||
|
||||
for (const line of offer.split('\r\n')) {
|
||||
if (line.startsWith('m=')) {
|
||||
parsedOffer.medias.push(line.slice('m='.length));
|
||||
} else if (parsedOffer.iceUfrag === '' && line.startsWith('a=ice-ufrag:')) {
|
||||
parsedOffer.iceUfrag = line.slice('a=ice-ufrag:'.length);
|
||||
} else if (parsedOffer.icePwd === '' && line.startsWith('a=ice-pwd:')) {
|
||||
parsedOffer.icePwd = line.slice('a=ice-pwd:'.length);
|
||||
}
|
||||
}
|
||||
|
||||
return parsedOffer;
|
||||
}
|
||||
|
||||
static #generateSdpFragment(offerData: OfferData, candidates: RTCIceCandidate[]): string {
|
||||
const candidatesByMedia: Record<number, RTCIceCandidate[]> = {};
|
||||
|
||||
for (const candidate of candidates) {
|
||||
const mid = candidate.sdpMLineIndex;
|
||||
if (mid === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (candidatesByMedia[mid] === undefined) {
|
||||
candidatesByMedia[mid] = [];
|
||||
}
|
||||
candidatesByMedia[mid].push(candidate);
|
||||
}
|
||||
|
||||
let fragment = `a=ice-ufrag:${offerData.iceUfrag}\r\n` + `a=ice-pwd:${offerData.icePwd}\r\n`;
|
||||
|
||||
let mid = 0;
|
||||
|
||||
for (const media of offerData.medias) {
|
||||
if (candidatesByMedia[mid] !== undefined) {
|
||||
fragment += `m=${media}\r\n` + `a=mid:${mid}\r\n`;
|
||||
|
||||
for (const candidate of candidatesByMedia[mid]) {
|
||||
fragment += `a=${candidate.candidate}\r\n`;
|
||||
}
|
||||
}
|
||||
mid++;
|
||||
}
|
||||
|
||||
return fragment;
|
||||
}
|
||||
|
||||
static #setCodec(section: string, codec: string): string {
|
||||
const normalizedCodec = codec.toLowerCase();
|
||||
const lines = section.split('\r\n');
|
||||
const filteredLines: string[] = [];
|
||||
const payloadFormats: string[] = [];
|
||||
|
||||
for (const line of lines) {
|
||||
if (!line.startsWith('a=rtpmap:')) {
|
||||
filteredLines.push(line);
|
||||
} else if (line.toLowerCase().includes(normalizedCodec)) {
|
||||
payloadFormats.push(line.slice('a=rtpmap:'.length).split(' ')[0]);
|
||||
filteredLines.push(line);
|
||||
}
|
||||
}
|
||||
|
||||
const rewrittenLines: string[] = [];
|
||||
let firstLine = true;
|
||||
|
||||
for (const line of filteredLines) {
|
||||
if (firstLine) {
|
||||
firstLine = false;
|
||||
rewrittenLines.push(line.split(' ').slice(0, 3).concat(payloadFormats).join(' '));
|
||||
} else if (line.startsWith('a=fmtp:')) {
|
||||
if (payloadFormats.includes(line.slice('a=fmtp:'.length).split(' ')[0])) {
|
||||
rewrittenLines.push(line);
|
||||
}
|
||||
} else if (line.startsWith('a=rtcp-fb:')) {
|
||||
if (payloadFormats.includes(line.slice('a=rtcp-fb:'.length).split(' ')[0])) {
|
||||
rewrittenLines.push(line);
|
||||
}
|
||||
} else {
|
||||
rewrittenLines.push(line);
|
||||
}
|
||||
}
|
||||
|
||||
return rewrittenLines.join('\r\n');
|
||||
}
|
||||
|
||||
static #setVideoBitrate(section: string, bitrate: number): string {
|
||||
let lines = section.split('\r\n');
|
||||
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
if (lines[i].startsWith('c=')) {
|
||||
lines = [
|
||||
...lines.slice(0, i + 1),
|
||||
`b=TIAS:${(bitrate * 1024).toString()}`,
|
||||
...lines.slice(i + 1),
|
||||
];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return lines.join('\r\n');
|
||||
}
|
||||
|
||||
static #setAudioBitrate(section: string, bitrate: number, voice: boolean): string {
|
||||
let opusPayloadFormat = '';
|
||||
const lines = section.split('\r\n');
|
||||
|
||||
for (const line of lines) {
|
||||
if (line.startsWith('a=rtpmap:') && line.toLowerCase().includes('opus/')) {
|
||||
opusPayloadFormat = line.slice('a=rtpmap:'.length).split(' ')[0];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (opusPayloadFormat === '') {
|
||||
return section;
|
||||
}
|
||||
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
if (lines[i].startsWith(`a=fmtp:${opusPayloadFormat} `)) {
|
||||
if (voice) {
|
||||
lines[i] =
|
||||
`a=fmtp:${opusPayloadFormat} minptime=10;useinbandfec=1;maxaveragebitrate=${(bitrate * 1024).toString()}`;
|
||||
} else {
|
||||
lines[i] =
|
||||
`a=fmtp:${opusPayloadFormat} maxplaybackrate=48000;stereo=1;sprop-stereo=1;maxaveragebitrate=${(bitrate * 1024).toString()}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return lines.join('\r\n');
|
||||
}
|
||||
|
||||
static #editOffer(
|
||||
sdp: string,
|
||||
videoCodec: string,
|
||||
audioCodec: string,
|
||||
audioBitrate: number,
|
||||
audioVoice: boolean
|
||||
): string {
|
||||
const sections = sdp.split('m=');
|
||||
|
||||
for (let i = 0; i < sections.length; i++) {
|
||||
if (sections[i].startsWith('video')) {
|
||||
sections[i] = this.#setCodec(sections[i], videoCodec);
|
||||
} else if (sections[i].startsWith('audio')) {
|
||||
sections[i] = this.#setAudioBitrate(
|
||||
this.#setCodec(sections[i], audioCodec),
|
||||
audioBitrate,
|
||||
audioVoice
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return sections.join('m=');
|
||||
}
|
||||
|
||||
static #editAnswer(sdp: string, videoBitrate: number): string {
|
||||
const sections = sdp.split('m=');
|
||||
|
||||
for (let i = 0; i < sections.length; i++) {
|
||||
if (sections[i].startsWith('video')) {
|
||||
sections[i] = this.#setVideoBitrate(sections[i], videoBitrate);
|
||||
}
|
||||
}
|
||||
|
||||
return sections.join('m=');
|
||||
}
|
||||
|
||||
private async start(): Promise<void> {
|
||||
try {
|
||||
const iceServers = await this.requestIceServers();
|
||||
const offer = await this.setupPeerConnection(iceServers);
|
||||
const answer = await this.sendOffer(offer);
|
||||
await this.setAnswer(answer);
|
||||
} catch (error) {
|
||||
this.handleError(error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
}
|
||||
|
||||
private handleError(err: string): void {
|
||||
if (this.state === 'running') {
|
||||
this.resetConnection();
|
||||
this.disposeSession();
|
||||
this.state = 'restarting';
|
||||
|
||||
this.restartTimeout = setTimeout(() => {
|
||||
this.restartTimeout = null;
|
||||
this.state = 'running';
|
||||
void this.start();
|
||||
}, this.retryPause);
|
||||
|
||||
this.conf.onError?.(`${err}, retrying in some seconds`);
|
||||
}
|
||||
}
|
||||
|
||||
private authHeader(): HeadersInit {
|
||||
if (this.conf.user !== undefined && this.conf.user !== '') {
|
||||
const credentials = btoa(`${this.conf.user}:${this.conf.pass ?? ''}`);
|
||||
return { Authorization: `Basic ${credentials}` };
|
||||
}
|
||||
if (this.conf.token !== undefined && this.conf.token !== '') {
|
||||
return { Authorization: `Bearer ${this.conf.token}` };
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
private async requestIceServers(): Promise<ParsedIceServer[]> {
|
||||
const response = await fetch(this.conf.url, {
|
||||
method: 'OPTIONS',
|
||||
headers: {
|
||||
...this.authHeader(),
|
||||
},
|
||||
});
|
||||
|
||||
return MediaMTXWebRTCPublisher.#linkToIceServers(response.headers.get('Link'));
|
||||
}
|
||||
|
||||
private async setupPeerConnection(iceServers: RTCIceServer[]): Promise<string> {
|
||||
if (this.state !== 'running') {
|
||||
throw new Error('closed');
|
||||
}
|
||||
|
||||
this.pc = new RTCPeerConnection({
|
||||
iceServers,
|
||||
});
|
||||
|
||||
this.pc.onicecandidate = (event) => this.onLocalCandidate(event);
|
||||
this.pc.onconnectionstatechange = () => this.onConnectionState();
|
||||
this.trackSenders = {};
|
||||
|
||||
this.stream.getTracks().forEach((track) => {
|
||||
const sender = this.pc?.addTrack(track, this.stream);
|
||||
|
||||
if (sender && (track.kind === 'audio' || track.kind === 'video')) {
|
||||
this.trackSenders[track.kind] = sender;
|
||||
}
|
||||
});
|
||||
|
||||
const offer = await this.pc.createOffer();
|
||||
if (!offer.sdp) {
|
||||
throw new Error('missing offer SDP');
|
||||
}
|
||||
|
||||
this.offerData = MediaMTXWebRTCPublisher.#parseOffer(offer.sdp);
|
||||
await this.pc.setLocalDescription(offer);
|
||||
|
||||
return offer.sdp;
|
||||
}
|
||||
|
||||
private async sendOffer(offer: string): Promise<string> {
|
||||
if (this.state !== 'running') {
|
||||
throw new Error('closed');
|
||||
}
|
||||
|
||||
const editedOffer = MediaMTXWebRTCPublisher.#editOffer(
|
||||
offer,
|
||||
this.conf.videoCodec,
|
||||
this.conf.audioCodec,
|
||||
this.conf.audioBitrate,
|
||||
this.conf.audioVoice
|
||||
);
|
||||
|
||||
const response = await fetch(this.conf.url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
...this.authHeader(),
|
||||
'Content-Type': 'application/sdp',
|
||||
},
|
||||
body: editedOffer,
|
||||
});
|
||||
|
||||
switch (response.status) {
|
||||
case 201:
|
||||
break;
|
||||
case 400: {
|
||||
const errorBody = (await response.json()) as { error?: string };
|
||||
throw new Error(errorBody.error ?? 'bad request');
|
||||
}
|
||||
default:
|
||||
throw new Error(`bad status code ${response.status}`);
|
||||
}
|
||||
|
||||
const location = response.headers.get('location');
|
||||
if (!location) {
|
||||
throw new Error('missing session location');
|
||||
}
|
||||
|
||||
this.sessionUrl = new URL(location, this.conf.url).toString();
|
||||
|
||||
return response.text();
|
||||
}
|
||||
|
||||
private async setAnswer(answer: string): Promise<void> {
|
||||
if (this.state !== 'running') {
|
||||
throw new Error('closed');
|
||||
}
|
||||
|
||||
const peerConnection = this.pc;
|
||||
if (peerConnection === null) {
|
||||
throw new Error('missing peer connection');
|
||||
}
|
||||
|
||||
const editedAnswer = MediaMTXWebRTCPublisher.#editAnswer(answer, this.conf.videoBitrate);
|
||||
|
||||
await peerConnection.setRemoteDescription(
|
||||
new RTCSessionDescription({
|
||||
type: 'answer',
|
||||
sdp: editedAnswer,
|
||||
})
|
||||
);
|
||||
|
||||
if (this.state !== 'running') {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.queuedCandidates.length !== 0) {
|
||||
this.sendLocalCandidates(this.queuedCandidates);
|
||||
this.queuedCandidates = [];
|
||||
}
|
||||
}
|
||||
|
||||
private onLocalCandidate(event: RTCPeerConnectionIceEvent): void {
|
||||
if (this.state !== 'running') {
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.candidate !== null) {
|
||||
if (this.sessionUrl === null) {
|
||||
this.queuedCandidates.push(event.candidate);
|
||||
} else {
|
||||
this.sendLocalCandidates([event.candidate]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private sendLocalCandidates(candidates: RTCIceCandidate[]): void {
|
||||
if (this.sessionUrl === null || this.offerData === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
void fetch(this.sessionUrl, {
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
'Content-Type': 'application/trickle-ice-sdpfrag',
|
||||
'If-Match': '*',
|
||||
},
|
||||
body: MediaMTXWebRTCPublisher.#generateSdpFragment(this.offerData, candidates),
|
||||
})
|
||||
.then((response) => {
|
||||
switch (response.status) {
|
||||
case 204:
|
||||
break;
|
||||
case 404:
|
||||
throw new Error('stream not found');
|
||||
default:
|
||||
throw new Error(`bad status code ${response.status}`);
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
this.handleError(error instanceof Error ? error.message : String(error));
|
||||
});
|
||||
}
|
||||
|
||||
private onConnectionState(): void {
|
||||
if (this.state !== 'running' || this.pc === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.pc.connectionState === 'failed' || this.pc.connectionState === 'closed') {
|
||||
this.handleError('peer connection closed');
|
||||
} else if (this.pc.connectionState === 'connected') {
|
||||
this.conf.onConnected?.();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default MediaMTXWebRTCPublisher;
|
||||
@@ -1,8 +1,20 @@
|
||||
import { Queue, Worker } from 'bullmq';
|
||||
import { getRedisConnection } from '@hctv/db';
|
||||
|
||||
export type SlackNotificationJobData = {
|
||||
channel: string;
|
||||
text: string;
|
||||
unfurl_links?: boolean;
|
||||
metadata?: {
|
||||
type: 'custom_stream_announcement';
|
||||
managedChannelId: string;
|
||||
ownerSlackId: string;
|
||||
ownerChannelName: string;
|
||||
};
|
||||
};
|
||||
|
||||
const globalForNotifier = global as unknown as {
|
||||
notificationQueue: Queue | null;
|
||||
notificationQueue: Queue<SlackNotificationJobData> | null;
|
||||
notificationWorker: Worker | null;
|
||||
|
||||
thumbnailQueue: Queue | null;
|
||||
@@ -14,9 +26,9 @@ if (!globalForNotifier.notificationQueue) {
|
||||
globalForNotifier.notificationWorker = null;
|
||||
}
|
||||
|
||||
export function getNotificationQueue(): Queue {
|
||||
export function getNotificationQueue(): Queue<SlackNotificationJobData> {
|
||||
if (!globalForNotifier.notificationQueue) {
|
||||
globalForNotifier.notificationQueue = new Queue('notifications', {
|
||||
globalForNotifier.notificationQueue = new Queue<SlackNotificationJobData>('notifications', {
|
||||
connection: getRedisConnection().options,
|
||||
defaultJobOptions: {
|
||||
attempts: 3,
|
||||
@@ -44,4 +56,4 @@ export function getThumbnailQueue(): Queue {
|
||||
});
|
||||
}
|
||||
return globalForNotifier.thumbnailQueue;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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');
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Worker } from 'bullmq';
|
||||
import { getRedisConnection } from '@hctv/db';
|
||||
import { getRedisConnection, prisma } from '@hctv/db';
|
||||
import snClient from '@/lib/services/slackNotifier';
|
||||
import type { SlackNotificationJobData } from '@/lib/workers';
|
||||
|
||||
const globalForWorker = global as unknown as {
|
||||
notificationWorker: Worker | null;
|
||||
@@ -18,14 +19,47 @@ export async function registerNotificationWorker(): Promise<void> {
|
||||
|
||||
console.log('Registering notification worker...');
|
||||
|
||||
const worker = new Worker('notifications', async (job) => {
|
||||
const worker = new Worker<SlackNotificationJobData>('notifications', async (job) => {
|
||||
try {
|
||||
await snClient.chat.postMessage(job.data);
|
||||
const { metadata: _metadata, ...slackMessage } = job.data;
|
||||
await snClient.chat.postMessage(slackMessage);
|
||||
return { success: true };
|
||||
} catch (e) {
|
||||
console.error('Slack notification failed:', e);
|
||||
// @ts-ignore e is unknown
|
||||
return { success: false, error: e.message };
|
||||
|
||||
if (job.data.metadata?.type === 'custom_stream_announcement') {
|
||||
const channel = await prisma.channel.findUnique({
|
||||
where: { id: job.data.metadata.managedChannelId },
|
||||
select: {
|
||||
notifChannels: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (channel?.notifChannels.includes(job.data.channel)) {
|
||||
await prisma.channel.update({
|
||||
where: { id: job.data.metadata.managedChannelId },
|
||||
data: {
|
||||
notifChannels: channel.notifChannels.filter(
|
||||
(channelId) => channelId !== job.data.channel
|
||||
),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
await snClient.chat.postMessage({
|
||||
channel: job.data.metadata.ownerSlackId,
|
||||
text: `I couldn't send a go-live notification for *${job.data.metadata.ownerChannelName}* to Slack channel \`${job.data.channel}\`, so I removed it from that channel's notification list.\nIf you still want notifications there, please make sure the bot can post in that channel and add it again in settings.`,
|
||||
});
|
||||
} catch (ownerNotificationError) {
|
||||
console.error('Failed to notify channel owner about Slack notification removal:', ownerNotificationError);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
error: e instanceof Error ? e.message : 'Unknown Slack notification error',
|
||||
};
|
||||
}
|
||||
}, {
|
||||
connection: getRedisConnection().options,
|
||||
@@ -45,4 +79,4 @@ export async function closeNotificationWorker(): Promise<void> {
|
||||
await globalForWorker.notificationWorker.close();
|
||||
globalForWorker.notificationWorker = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,7 +45,8 @@ export async function registerThumbnailWorker(): Promise<void> {
|
||||
);
|
||||
return { success: true };
|
||||
} catch (ffmpegError) {
|
||||
console.error(`FFmpeg error for ${name} on server ${server}:`, ffmpegError);
|
||||
// commenting since its mostly due to the fact that the stream is likely offline
|
||||
// console.error(`FFmpeg error for ${name} on server ${server}:`, ffmpegError);
|
||||
return { success: false, error: ffmpegError instanceof Error ? ffmpegError.message : String(ffmpegError) };
|
||||
}
|
||||
} catch (e) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
'use server';
|
||||
|
||||
import { ZodType } from 'zod';
|
||||
import { z } from 'zod';
|
||||
|
||||
type SuccessResult<T> = {
|
||||
success: true;
|
||||
@@ -14,7 +14,10 @@ type ErrorResult = {
|
||||
|
||||
type VerifyResult<T> = SuccessResult<T> | ErrorResult;
|
||||
|
||||
export default async function zodVerify<T>(schema: ZodType<T>, data: FormData | Object): Promise<VerifyResult<T>> {
|
||||
export default async function zodVerify<TSchema extends z.ZodTypeAny>(
|
||||
schema: TSchema,
|
||||
data: FormData | Object
|
||||
): Promise<VerifyResult<z.output<TSchema>>> {
|
||||
let obj: any = data;
|
||||
if (data instanceof FormData) {
|
||||
obj = Object.fromEntries(data.entries());
|
||||
@@ -27,8 +30,11 @@ export default async function zodVerify<T>(schema: ZodType<T>, data: FormData |
|
||||
|
||||
const zod = schema.safeParse(obj);
|
||||
if (!zod.success) {
|
||||
const [issue] = zod.error.issues;
|
||||
const path = issue.path[0] === undefined ? 'form' : String(issue.path[0]);
|
||||
|
||||
return {
|
||||
error: `From ${zod.error.errors[0].path[0]}: ${zod.error.errors[0].message}`,
|
||||
error: `From ${path}: ${issue.message}`,
|
||||
success: false,
|
||||
};
|
||||
}
|
||||
@@ -36,4 +42,4 @@ export default async function zodVerify<T>(schema: ZodType<T>, data: FormData |
|
||||
success: true,
|
||||
data: zod.data,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,109 +1,20 @@
|
||||
import type { Config } from "tailwindcss"
|
||||
import { uploadthingPlugin } from 'uploadthing/tw'
|
||||
import * as tan from 'tailwindcss-animate'
|
||||
import { uploadthingPlugin } from 'uploadthing/tw';
|
||||
import type { Config } from 'tailwindcss';
|
||||
|
||||
const config = {
|
||||
darkMode: ["class"],
|
||||
content: [
|
||||
'./pages/**/*.{ts,tsx}',
|
||||
'./components/**/*.{ts,tsx}',
|
||||
'./app/**/*.{ts,tsx}',
|
||||
'./src/**/*.{ts,tsx}',
|
||||
],
|
||||
prefix: "",
|
||||
darkMode: 'class',
|
||||
content: ['./src/**/*.{ts,tsx}'],
|
||||
prefix: '',
|
||||
theme: {
|
||||
container: {
|
||||
center: true,
|
||||
padding: '2rem',
|
||||
screens: {
|
||||
'2xl': '1400px'
|
||||
}
|
||||
},
|
||||
extend: {
|
||||
colors: {
|
||||
border: 'hsl(var(--border))',
|
||||
input: 'hsl(var(--input))',
|
||||
ring: 'hsl(var(--ring))',
|
||||
background: 'hsl(var(--background))',
|
||||
foreground: 'hsl(var(--foreground))',
|
||||
primary: {
|
||||
DEFAULT: 'hsl(var(--primary))',
|
||||
foreground: 'hsl(var(--primary-foreground))'
|
||||
},
|
||||
secondary: {
|
||||
DEFAULT: 'hsl(var(--secondary))',
|
||||
foreground: 'hsl(var(--secondary-foreground))'
|
||||
},
|
||||
destructive: {
|
||||
DEFAULT: 'hsl(var(--destructive))',
|
||||
foreground: 'hsl(var(--destructive-foreground))'
|
||||
},
|
||||
muted: {
|
||||
DEFAULT: 'hsl(var(--muted))',
|
||||
foreground: 'hsl(var(--muted-foreground))'
|
||||
},
|
||||
accent: {
|
||||
DEFAULT: 'hsl(var(--accent))',
|
||||
foreground: 'hsl(var(--accent-foreground))'
|
||||
},
|
||||
popover: {
|
||||
DEFAULT: 'hsl(var(--popover))',
|
||||
foreground: 'hsl(var(--popover-foreground))'
|
||||
},
|
||||
card: {
|
||||
DEFAULT: 'hsl(var(--card))',
|
||||
foreground: 'hsl(var(--card-foreground))'
|
||||
},
|
||||
surface1: {
|
||||
DEFAULT: 'hsl(var(--surface-1))'
|
||||
},
|
||||
surface2: {
|
||||
DEFAULT: 'hsl(var(--surface-2))'
|
||||
},
|
||||
mantle: {
|
||||
DEFAULT: 'hsl(var(--mantle))'
|
||||
},
|
||||
sidebar: {
|
||||
DEFAULT: 'hsl(var(--sidebar-background))',
|
||||
foreground: 'hsl(var(--sidebar-foreground))',
|
||||
primary: 'hsl(var(--sidebar-primary))',
|
||||
'primary-foreground': 'hsl(var(--sidebar-primary-foreground))',
|
||||
accent: 'hsl(var(--sidebar-accent))',
|
||||
'accent-foreground': 'hsl(var(--sidebar-accent-foreground))',
|
||||
border: 'hsl(var(--sidebar-border))',
|
||||
ring: 'hsl(var(--sidebar-ring))'
|
||||
}
|
||||
},
|
||||
borderRadius: {
|
||||
lg: 'var(--radius)',
|
||||
md: 'calc(var(--radius) - 2px)',
|
||||
sm: 'calc(var(--radius) - 4px)'
|
||||
},
|
||||
keyframes: {
|
||||
'accordion-down': {
|
||||
from: {
|
||||
height: '0'
|
||||
},
|
||||
to: {
|
||||
height: 'var(--radix-accordion-content-height)'
|
||||
}
|
||||
},
|
||||
'accordion-up': {
|
||||
from: {
|
||||
height: 'var(--radix-accordion-content-height)'
|
||||
},
|
||||
to: {
|
||||
height: '0'
|
||||
}
|
||||
}
|
||||
},
|
||||
animation: {
|
||||
'accordion-down': 'accordion-down 0.2s ease-out',
|
||||
'accordion-up': 'accordion-up 0.2s ease-out'
|
||||
}
|
||||
}
|
||||
container: {
|
||||
center: true,
|
||||
padding: '2rem',
|
||||
screens: {
|
||||
'2xl': '1400px',
|
||||
},
|
||||
},
|
||||
},
|
||||
plugins: [tan, uploadthingPlugin],
|
||||
} satisfies Config
|
||||
plugins: [uploadthingPlugin],
|
||||
} satisfies Config;
|
||||
|
||||
export default config
|
||||
export default config;
|
||||
|
||||
48
compose.yml
@@ -58,8 +58,52 @@ services:
|
||||
volumes:
|
||||
- 'hctv_redis:/data'
|
||||
mediamtx:
|
||||
image: 'bluenviron/mediamtx:latest'
|
||||
build:
|
||||
context: .
|
||||
dockerfile: docker/mediamtx/Dockerfile
|
||||
environment:
|
||||
SSL_CERT_FILE: /etc/ssl/certs/ca-certificates.crt
|
||||
MTX_AUTHHTTPADDRESS: ${MEDIAMTX_AUTH_HTTP_ADDRESS:-http://hctv:3000/api/mediamtx/publish}
|
||||
MTX_WEBRTCADDITIONALHOSTS: ${MEDIAMTX_WEBRTC_ADDITIONAL_HOSTS:-}
|
||||
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'
|
||||
- '--storage.tsdb.path=/prometheus'
|
||||
- '--web.enable-lifecycle'
|
||||
volumes:
|
||||
- './mediamtx.yml:/mediamtx.yml'
|
||||
- './observability/prometheus.yml:/etc/prometheus/prometheus.yml:ro'
|
||||
- './observability/web_username:/etc/prometheus/web_username'
|
||||
- './observability/web_password:/etc/prometheus/web_password'
|
||||
- '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,60 @@ 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
|
||||
- 8889:8889
|
||||
- 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 +72,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,8 +6,16 @@ srt: yes
|
||||
srtAddress: :8890
|
||||
|
||||
hls: yes
|
||||
hlsVariant: lowLatency
|
||||
hlsSegmentDuration: 2s
|
||||
hlsPartDuration: 500ms
|
||||
hlsSegmentCount: 10
|
||||
|
||||
webrtc: yes
|
||||
|
||||
authMethod: http
|
||||
authHTTPAddress: http://host.docker.internal:3000/api/mediamtx/publish
|
||||
|
||||
api: yes
|
||||
metrics: yes
|
||||
metricsAddress: :9998
|
||||
|
||||